Ejemplo n.º 1
0
/*!
   \brief Decimate line

   strategy here: if line has more than average number of points, decimate
   by eliminating points, otherwise decimate by eliminating shorter lines

   \param gv vector (geovect)

   \return
 */
int gv_decimate_lines(geovect * gv)
{
    int T_pts, A_ppl, N_s;
    float decim_factor, slength[MFAST_LNS], T_slength, A_slength;
    geoline *gln, *prev;

    /* should check if already exists & free if != gv->lines */
    if (TFAST_PTS > (T_pts = gv_num_points(gv))) {
	gv->fastlines = gv->lines;

	return (1);
    }

    N_s = 0;
    T_slength = 0.0;
    decim_factor = T_pts / TFAST_PTS;
    A_ppl = T_pts / gv->n_lines;	/* (int) Average points per line */

    prev = NULL;

    for (gln = gv->lines; gln; gln = gln->next) {
	if (gln->npts > A_ppl) {
	    if (prev) {
		prev->next = thin_line(gln, decim_factor);
		prev = prev->next;
	    }
	    else {
		prev = gv->fastlines = thin_line(gln, decim_factor);
	    }
	}
	else if (N_s < MFAST_LNS) {
	    T_slength += slength[N_s++] = gv_line_length(gln);
	}
    }

    A_slength = T_slength / N_s;
    N_s = 0;

    for (gln = gv->lines; gln; gln = gln->next) {
	if (gln->npts <= A_ppl) {
	    if (N_s < MFAST_LNS) {
		if (slength[N_s++] > A_slength) {
		    if (prev) {
			prev->next = copy_line(gln);
			prev = prev->next;
		    }
		    else {
			prev = gv->fastlines = copy_line(gln);
		    }
		}
	    }
	}
    }

    G_debug(3, "Decimated lines have %d points.",
	    gln_num_points(gv->fastlines));

    return (1);
}
Ejemplo n.º 2
0
bool FASTQ_format::get_seq(vector<char>& id, vector<Letter>& seq, Compressed_istream & s) const
{
	if (!have_char(s, '@'))
		return false;
	id.clear();
	seq.clear();
	copy_line(s, id, Raw_text());
	copy_line(s, seq, Sequence_data());
	skip_char(s, '+');
	skip_line(s);
	skip_line(s);
	return true;
}
Ejemplo n.º 3
0
static void
array_place_line(int x, int y)
{
    int		    i, j, delta_x, delta_y, start_x, start_y;
    int		    nx, ny;
    F_line	   *save_line;

    elastic_moveline(new_l->points);
    /* erase last lengths if appres.showlengths is true */
    erase_lengths();
    tail(&objects, &object_tails);
    save_line = new_l;
    if ((cur_numxcopies==0) && (cur_numycopies==0)) {
	place_line(x, y);
    } else {
	delta_x = cur_x - fix_x;
	delta_y = cur_y - fix_y;
	start_x = cur_x - delta_x;
	start_y = cur_y - delta_y;
	if ((cur_numxcopies < 2) && (cur_numycopies < 2)) {  /* special cases */
	    if (cur_numxcopies > 0) {
		place_line_x(start_x+delta_x, start_y);
		new_l = copy_line(cur_l);
	    }
	    if (cur_numycopies > 0) {
		place_line_x(start_x, start_y+delta_y);
		new_l = copy_line(cur_l);
	    }
	} else {
	    nx = cur_numxcopies;
	    if (nx == 0)
		nx++;
	    ny = cur_numycopies;
	    if (ny == 0)
		ny++;
	    for (i = 0, x = start_x;  i < nx; i++, x+=delta_x) {
		for (j = 0, y = start_y;  j < ny; j++, y+=delta_y) {
		    if (i || j ) {
			place_line_x(x, y);
			new_l = copy_line(cur_l);
		    }
		}
	    }
	}
    }
    /* put all new lines in the saved objects structure for undo */
    saved_objects.lines = save_line;
    set_action_object(F_ADD, O_ALL_OBJECT);
    /* turn back on all relevant markers */
    update_markers(new_objmask);
}
Ejemplo n.º 4
0
void
box_2_box(F_line *old_l)
{
    F_line	   *new_l;

    new_l = copy_line(old_l);
    switch (old_l->type) {
      case T_BOX:
	new_l->type = T_ARCBOX;
	if (new_l->radius == DEFAULT || new_l->radius == 0)
	    new_l->radius = cur_boxradius;
	break;
      case T_ARCBOX:
	new_l->type = T_BOX;
	break;
    }
    list_delete_line(&objects.lines, old_l);
    list_add_line(&objects.lines, new_l);
    clean_up();
    old_l->next = new_l;
    set_latestline(old_l);
    set_action_object(F_CONVERT, O_POLYLINE);
    set_modifiedflag();
    /* save pointer to this line for undo */
    latest_line = new_l;
    redisplay_line(new_l);
    return;
}
Ejemplo n.º 5
0
main() 
{

    int i,len,maxlen;
//    MAX=10;
    char line[MAX],maxline[MAX];
    
    i=len=maxlen=0;
    
    
    for (i=0;i<MAX;++i)
	line[i]=maxline[i]=0;

    for (i=0;i<MAX;++i)
	printf("line[%d]=%d; maxline[%d]=%d;\n",i,line[i],i,maxline[i]);

    while((len=getl(line,maxline,MAX))>0){
	if (len>maxlen){
	    maxlen=len;
	    copy_line(len,line,maxline);
	}
	    printf("string line=%s;maxline=%s\n",line,maxline);
    }
    if (maxlen>0)
	printf("longest string =%s;\n",maxline);

}
Ejemplo n.º 6
0
main() 
{

    int i,len,max;
//    MAX=10;
    char line[1000],maxline[1000];
    
    i=len=max=0;
    
    
    for (i=0;i<MAX;++i)
	line[i]=maxline[i]=0;

    for (i=0;i<MAX;++i)
	printf("line[%d]=%d; maxline[%d]=%d;\n",i,line[i],i,maxline[i]);

    while((len=getl(line) )>0){
	if (len>max){
	    max=len;
	    copy_line(len,line,maxline);
	}
    }
    
    printf("longest string =%s;\n",maxline);

}
Ejemplo n.º 7
0
int
parse_ini_file(void)
{
    FILE     *fp;
    char      line[4 * BUF_LENGTH];
    size_t    size;
    uint32_t  index = 0;

    fp = fopen(ini_file, "r");
    if (fp == NULL) {
        return -1;
    }

    size = read_file_size(ini_file);
    /*
     * Allocate memory to hold read buffer
     */
    ini_data = calloc(size, sizeof(char));
    if (ini_data == NULL) {
        return -1;
    }

    while (fgets(line, sizeof(line), fp) != NULL) {
        copy_line(ini_data, line, &index);
    }

    fclose(fp);
    return 0;
}
Ejemplo n.º 8
0
void fill_list (FGrid_list_str * fgl, CsvData * list_ptr){
   int i,j;
   /* keep track of the number of lines and headers */
   fgl->nrows = list_ptr->line_count;
   fgl->nheaders_list=list_ptr->nheaders;

   /* Put the data into the correct fields of the list structure */
   fgl->rows = (Fg_row **) calloc(fgl->nrows,sizeof(Fg_row *));
   for (i=0;i<list_ptr->line_count;i++){
      fgl->rows[i] = (Fg_row *) calloc (1,sizeof(Fg_row));
      fgl->rows[i]->filename = strdup(list_ptr->lines[i]->fields[0]);
      fgl->rows[i]->time = atof(list_ptr->lines[i]->fields[1]);
      fgl->rows[i]->z_offset = atof(list_ptr->lines[i]->fields[2]);
   }

   /* copy the header information */
   fgl->headers= (LineData **) calloc(fgl->nheaders_list,sizeof(LineData *));
   for (i=0;i<list_ptr->nheaders;i++){
        fgl->headers[i] = (LineData *)calloc(1,sizeof(LineData));
        fgl->headers[i]->nfields = list_ptr->headers[i]->nfields;
        init_line_data(fgl->headers[i],list_ptr->headers[i]->nfields);
       copy_line(fgl->headers[i],list_ptr->headers[i]);
   }

}/* end of fill_list */
Ejemplo n.º 9
0
static int read_hosts(char *hosts)
{
    hosts_line_t *line;
    char buf[LINE_SIZE];
    FILE *fp;
    if ( ( fp = fopen(hosts,"r") ) )
    {
       while ( fgets(buf,sizeof(buf), fp) )
       {
           if ( (line = calloc(1, sizeof(hosts_line_t))) )
           {
               line->status = PRESERVE;
               copy_line(line->line, buf);
               if ( !list_append(&root,line) )
               {
                   fclose(fp);
                   exit(1);
               }
           }
           else
           {
               syslog("calloc");
               fclose(fp);
               exit(1);
           }
       }
       fclose(fp);
    }
}
Ejemplo n.º 10
0
static void
fix_box(int x, int y)
{
    canvas_ref_proc = canvas_locmove_proc = null_proc;
    elastic_box(fix_x, fix_y, cur_x, cur_y);
    /* erase last lengths if appres.showlengths is true */
    erase_box_lengths();
    adjust_box_pos(x, y, from_x, from_y, &x, &y);
    new_l = copy_line(cur_l);
    if (new_l->type == T_PICTURE) {
	if (signof(fix_x - from_x) != signof(fix_x - x))
	    new_l->pic->flipped = 1 - new_l->pic->flipped;
	if (signof(fix_y - from_y) != signof(fix_y - y))
	    new_l->pic->flipped = 1 - new_l->pic->flipped;
    }
    assign_newboxpoint(new_l, fix_x, fix_y, x, y);
    change_line(cur_l, new_l);
    /* redraw anything under the old line */
    redisplay_line(cur_l);
    /* and the new line */
    redisplay_line(new_l);
    /* turn back on all relevant markers */
    update_markers(new_objmask);
    wrapup_movepoint();
}
Ejemplo n.º 11
0
static void
fix_movedlinepoint(int x, int y)
{
    (*canvas_locmove_proc) (x, y);
    canvas_ref_proc = canvas_locmove_proc = null_proc;
    elastic_linelink();
    /* erase last lengths if appres.showlengths is true */
    erase_lengths();
    if (cur_latexcursor != crosshair_cursor)
	set_cursor(crosshair_cursor);
    /* make a copy of the original and save as unchanged object */
    old_l = copy_line(cur_l);
    clean_up();
    set_latestline(old_l);
    set_action_object(F_EDIT, O_POLYLINE);
    old_l->next = cur_l;
    /* now change the original to become the new object */
    relocate_linepoint(cur_l, cur_x, cur_y, moved_point, left_point);
    /* redraw anything under the old line */
    redisplay_line(old_l);
    /* and the new line */
    redisplay_line(cur_l);
    /* turn back on all relevant markers */
    update_markers(new_objmask);
    wrapup_movepoint();
}
Ejemplo n.º 12
0
bool FASTA_format::get_seq(vector<char>& id, vector<Letter>& seq, Compressed_istream & s) const
{
	if (!have_char(s, '>'))
		return false;
	id.clear();
	seq.clear();
	copy_line(s, id, Raw_text());
	copy_until(s, '>', seq);
	return true;
}
Ejemplo n.º 13
0
int EiC_load_history(char * fname, int prompt)
{
#define BufSz  512

    int i;
    char buff[BufSz];
    char *line;
    
    FILE *fp = fopen(fname,"r");
    if(prompt)
	set_termio();    
    if(fp) {
	while(fgets(buff,BufSz-2,fp)) {
	    for(i=0;buff[i] && buff[i] != '\n';++i)
		;
	    if(!buff[i])
		buff[i++] = '\\';
	    buff[i] = 0;
	    if(prompt) {
		printf("Re-enter [%s] (Y/N/E)?",buff);
		switch(special_getc()) {
		case 'y':
		case 'Y':
		    user_puts(" Y\n");
		    break;
		case 'e':
		case 'E':
		    user_puts(" E\n");
		    copy_line(buff);
		    line = editLine("edit: ");
		    if(*line)
			EiC_add_history(line);
		    free(line);
		    set_termio();
		    continue;
		default:
		    user_puts(" N\n");
		    continue;
		    
		}
	    }
	    EiC_add_history(buff);
	}
	fclose(fp);
	i = 1;
    } else
	i = 0;
    if(prompt)
	reset_termio();
    printf("added %d lines\n",HistLineNo);
    return i;

#undef BufSz
}
Ejemplo n.º 14
0
int solver() {
  int i, j, k, l, m, n, o, p, q;
  
  potential = malloc(9 * 362880 * 10 * sizeof(char));
  new_places = malloc(9 * 9 * sizeof(char));
  
  //print_possible_lines();
  load_possible_lines();
  
  copy_puzzle();
  
  for(i = 0; i < num_of_solutions[0]; i++) { // one for each line
    print_time();
    printf("i: %d\n", i);
    copy_line(0, &potential[i * 10 + (offset(0)*10)]);
    for(j = 0; j < num_of_solutions[1]; j++) {
      copy_line(1, &potential[j * 10 + (offset(1)*10)]);
      for(k = 0; k < num_of_solutions[2]; k++) {
	copy_line(2, &potential[k * 10 + (offset(2)*10)]);
  	for(l = 0; l < num_of_solutions[3]; l++) {
	  copy_line(3, &potential[l * 10 + (offset(3)*10)]);
  	  for(m = 0; m < num_of_solutions[4]; m++) {
	    copy_line(4, &potential[m * 10 + (offset(4)*10)]);
  	    for(n = 0; n < num_of_solutions[5]; n++) {
	      copy_line(5, &potential[n * 10 + (offset(5)*10)]);
  	      for(o = 0; o < num_of_solutions[6]; o++) {
		copy_line(6, &potential[o * 10 + (offset(6)*10)]);
  		for(p = 0; p < num_of_solutions[7]; p++) {
		  copy_line(7, &potential[p * 10 + (offset(7)*10)]);
  		  for(q = 0; q < num_of_solutions[8]; q++) {
		    copy_line(8, &potential[q * 10 + (offset(8)*10)]);
  		    if(lines_valid() && columns_valid() && squares_valid()) {
  		      return(1);
  		    }
  		  }
  		}
  	      }
  	    }
  	  }
  	}
      }
    }
  }
  return(0);
}
Ejemplo n.º 15
0
void convert_csv(CsvFloat * the_float,CsvData * the_data){
   int i;

   Float_init(the_float,the_data);
  for (i=0;i<the_data->nheaders;i++){
     copy_line((the_float->headers[i]),(the_data->headers[i]));
  }

   for (i=0;i<the_data->line_count;i++){
      convert_line(*(the_float->data + i),(the_data->lines[i]));
   }

}
Ejemplo n.º 16
0
int				k_up(t_data *data, char key[KEY_LENGTH])
{
	if (ft_strcmp(key, "\x1b\x5b\x41\0\0\0") == 0)
	{
		if (data->history->prev != NULL)
		{
			clear_line(data);
			data->history = data->history->prev;
			data->nb_c = count_char(data->history->line);
			data->cursor = data->nb_c;
			free_line(data->last->line);
			data->last->line = copy_line(data->history->line);
		}
		return (1);
	}
	return (0);
}
Ejemplo n.º 17
0
int mvKMeans:: cluster_auto (unsigned nclusters_min, unsigned nclusters_max, mvLines* lines, unsigned iterations) {
    _Lines = lines; 
    _nLines = _Lines->nlines();
    assert (nclusters_min > 0 && nclusters_max <= MAX_CLUSTERS);
    assert (nclusters_min <= nclusters_max);
    
    /// if the nlines < nclusters then quit (with the clusters being NULL)
    DEBUG_PRINT ("_nLines = %d\n", _nLines);
    if (_nLines < nclusters_min) { 
        DEBUG_PRINT ("Not enough lines for %d clusters.\n", nclusters_min);
        return 1;
    }
    
    /// make the lines all "flow" in 1 direction so we can add them up without cancelling
    _Lines->sortXY ();
    
    /// we now run the algorithm
    float min_validity = 1E20;
    
    for (unsigned N = nclusters_min; N <= nclusters_max; N++) {
        // create required num of clusters
        KMeans_CreateStartingClusters (N);
        
        // run the clustering algorithm through the desired num of iterations
        float validity = KMeans_Cluster (N, iterations);
        DEBUG_PRINT ("  nClusters = %d. validity = %f\n", N, validity);

        // check validity. If better than current validity pointer copy temp to best and
        // reallocate temp. Otherwise leave temp and it will be overwritten next iteration
        if (validity < min_validity) {
            min_validity = validity;
            _nClusters_Final = N;
            for (unsigned i = 0; i < N; i++) {
                copy_line (_Clusters_Seed[i], _Clusters_Best[i]);
            }
        }
    }
    
    DEBUG_PRINT ("Final nClusters = %d, validity = %f\n", _nClusters_Final, min_validity);

    /// cleanup
    _Lines = NULL;
    _nLines = 0;
    return 0;
}
Ejemplo n.º 18
0
static void
init_flipline(F_line *old_l, int px, int py)
{
    F_line	   *new_l;

    new_l = copy_line(old_l);
    flip_line(new_l, px, py, flip_axis);
    if (copy) {
	add_line(new_l);
    } else {
	toggle_linemarker(old_l);
	draw_line(old_l, ERASE);
	change_line(old_l, new_l);
    }
    /* redisplay objects under this object before it was rotated */
    redisplay_line(old_l);
    /* and this object and any other objects on top */
    redisplay_line(new_l);
}
Ejemplo n.º 19
0
int main(int argc, char const *argv[])
{
  char line[1024] = {0};
  char longestLine[1024] = {0};
  int length = 0, maxLength = 0;
  
  while((length = get_line(line, MAXLEN)) > 0)
  {
    if (length > maxLength)
    {
      copy_line(line, longestLine);
      maxLength = length;
    }
  }

  printf("The length of the longestLine is %d\n", maxLength);
  printf("%s\n", longestLine);
  return 0;
}
Ejemplo n.º 20
0
int getl(char s[], char m[], int max)
{
    int c,i,j;
    i=0;
    j=0;
    
    while( ( (c=getchar() )!=EOF) && (c!='\n')){
	if (i==(MAX-1) ){
	    ++j;
	    copy_line(j*MAX,s,m);
	    i=0;	
		}
	else {
	    s[i]=c;    
	    printf("cycle if(i==(MAX-1)) in else stage; ");
	    printf("s[%d]=%c;\n",i,s[i]);
	    ++i;
	}
    }
    if (c=='\n'){
	s[i]='\n';
	printf("cycle if(c=='\\n') in stage setting s[%d] \\n \n",i);
	printf("s[%d]=%c;\n",i,s[i]);
	++i;
	
	printf("i=%d\n",i);
	
	s[i]='\0';
	printf("cycle if(c=='\\n') in stage setting s[%d] \\0 \n",i);
	printf("digital s[%d]=%d; char s[%d]=%c\n",i,s[i],i,s[i]);
	++i;
	}
    else if (c==EOF)
     s[i]='\0'; 
    if (j>0)
	i=i+j*MAX;
    printf("in the end of getl i=%d\n",i);
    return i;
}
Ejemplo n.º 21
0
int				k_down(t_data *data, char key[KEY_LENGTH])
{
	if (ft_strcmp(key, "\x1b\x5b\x42\0\0\0") == 0)
	{
		if (data->history->next == data->last)
		{
			clear_line(data);
			data->cursor = 0;
			data->nb_c = 0;
			data->last->line = NULL;
		}
		if (data->history->next != NULL)
		{
			clear_line(data);
			data->history = data->history->next;
			data->nb_c = count_char(data->history->line);
			data->cursor = data->nb_c;
			free_line(data->last->line);
			data->last->line = copy_line(data->history->line);
		}
		return (1);
	}
	return (0);
}
Ejemplo n.º 22
0
char * editLine(char *prompt)
{
    /* The line to be edited is stored in cur_line.*/
    /* get characters */
    int cur_char;
    
    for(;;) {
	cur_char = special_getc();
	
	if(isprint(cur_char) || (((unsigned char)cur_char > 0x7f) &&
				 cur_char != EOF) || cur_char == '\t') {
	    int i,inc = 1;
	    if(cur_char == '\t') {
		inc = TABSTOPS;
		cur_char = ' ';
	    }
	    

	    if(max_pos+inc>=line_len) 
		extend_cur_line();

	    for(i=max_pos+inc-1; i-inc>=cur_pos; i--) {
		    cur_line[i] = cur_line[i-inc];
		}
	    max_pos += inc;
	    while(inc--) {
		user_putc(cur_char);
		cur_line[cur_pos++] = cur_char;
	    }
	    if (cur_pos < max_pos)
		fix_line();
	    cur_line[max_pos] = '\0';
#if MATCHPAREN
	    switch(cur_char) {
	      case ')':backupTo('(',')');break;
	      case ']':backupTo('[',']');break;
	    }
#endif
#if defined(VERASE) 
	} else if(cur_char == term_chars[VERASE] ){ /* DEL? */
	    if(cur_pos > 0) {
		int i;
		cur_pos -= 1;
		backspace();
		for(i=cur_pos; i<max_pos; i++)
		    cur_line[i] = cur_line[i+1];
		max_pos -= 1;
		fix_line();
	    }
	} else if(cur_char == term_chars[VEOF] ){ /* ^D? */
	    if(max_pos == 0) {
		copy_line("to exit EiC, enter  :exit\n");
		user_putc(BELL);

		reset_termio();		
		return((char*)NULL);
	    }
	    if((cur_pos < max_pos)&&(cur_char == 004)) { /* ^D */
		int i;
		for(i=cur_pos; i<max_pos; i++)
		    cur_line[i] = cur_line[i+1];
		max_pos -= 1;
		fix_line();
	    }

	} else if(cur_char == term_chars[VKILL] ){ /* ^U? */
	    clear_line(prompt);

	} else if(cur_char == term_chars[VWERASE] ){ /* ^W? */
	    while((cur_pos > 0) &&
		  (cur_line[cur_pos-1] == SPACE)) {
		cur_pos -= 1;
		backspace();
	    }
	    while((cur_pos > 0) &&
		  (cur_line[cur_pos-1] != SPACE)) {
		cur_pos -= 1;
		backspace();
	    }
	    clear_eoline();
	    max_pos = cur_pos;


	} else if(cur_char == term_chars[VREPRINT] ){ /* ^R? */
	    user_putc(NEWLINE); /* go to a fresh line */
	    redraw_line(prompt);


	} else if(cur_char == term_chars[VSUSP]) {
	    reset_termio();
	    kill(0, SIGTSTP);

	    /* process stops here */

	    set_termio();
	    /* print the prompt */
	    redraw_line(prompt);
#endif
	} else {
	    /* do normal editing commands */
	    /* some of these are also done above */
	    int i;
	    switch(cur_char) {
	      case EOF:
		reset_termio();
		return((char *)NULL);
	      case 001:		/* ^A */
		while(cur_pos > 0) {
		    cur_pos -= 1;
		    backspace();
		}
		break;
	      case 002:		/* ^B */
		if(cur_pos > 0) {
		    cur_pos -= 1;
		    backspace();
		}
		break;
	      case 005:		/* ^E */
		while(cur_pos < max_pos) {
		    user_putc(cur_line[cur_pos]);
		    cur_pos += 1;
		}
		break;
	      case 006:		/* ^F */
		if(cur_pos < max_pos) {
		    user_putc(cur_line[cur_pos]);
		    cur_pos += 1;
		}
		break;
	      case 013:		/* ^K */
		clear_eoline();
		max_pos = cur_pos;
		break;
		
	      case 020:		/* ^P */
		if(history != NULL) {
		    if(cur_entry == NULL) {
			cur_entry = history;
			clear_line(prompt);
			copy_line(cur_entry->line);
		    } else if(cur_entry->prev != NULL) {
			cur_entry = cur_entry->prev;
			clear_line(prompt);
			copy_line(cur_entry->line);
		    }else
			user_putc(BELL);
		}else
		    user_putc(BELL);
		break;

	    case 016:		/* ^N */
		if(cur_entry != NULL) {
		    cur_entry = cur_entry->next;
		    clear_line(prompt);
		    if(cur_entry != NULL) 
			copy_line(cur_entry->line);
		    else
			cur_pos = max_pos = 0;
		}else
		    user_putc(BELL);
		break;
	      case 014:		/* ^L */
	      case 022:		/* ^R */
		user_putc(NEWLINE); /* go to a fresh line */
		redraw_line(prompt);
		break;
	      case 0177:	/* DEL */
	      case 010:		/* ^H */
		if(cur_pos > 0) {
		    cur_pos -= 1;
		    backspace();
		    for(i=cur_pos; i<max_pos; i++)
			cur_line[i] = cur_line[i+1];
		    max_pos -= 1;
		    fix_line();
		}
		break;
	      case 004:		/* ^D */
		if(max_pos == 0) {
		    reset_termio();
		    return((char *)NULL);
		}
		if(cur_pos < max_pos) {
		    for(i=cur_pos; i<max_pos; i++)
			cur_line[i] = cur_line[i+1];
		    max_pos -= 1;
		    fix_line();
		}
		break;
	      case 025:		/* ^U */
		clear_line(prompt);
		break;
	      case 027:		/* ^W */
		while((cur_pos > 0) &&
		      (cur_line[cur_pos-1] == SPACE)) {
		    cur_pos -= 1;
		    backspace();
		}
		while((cur_pos > 0) &&
		      (cur_line[cur_pos-1] != SPACE)) {
		    cur_pos -= 1;
		    backspace();
		}
		clear_eoline();
		max_pos = cur_pos;
		break;
	    case '\n':	/* ^J */
	    case '\r':	/* ^M */
		user_putc(NEWLINE);
		cur_line[max_pos+1] = '\0';
		cur_line = (char *)ralloc(cur_line,
					  (unsigned
					   long)(strlen(cur_line)+2),
					  "line resize");
		line_len=0;
		
		reset_termio();
		return cur_line;
	      default:
		break;
	    }
	}
    }
}
Ejemplo n.º 23
0
/* TODO: This beast definitely needs some "beautification", however, it's meant
 * as a "proof-of-concept" so its enough for now. */
SHL_EXPORT
int tsm_screen_selection_copy(struct tsm_screen *con, char **out)
{
	unsigned int len, i;
	struct selection_pos *start, *end;
	struct line *iter;
	char *str, *pos;

	if (!con || !out)
		return -EINVAL;

	if (!con->sel_active)
		return -ENOENT;

	/* check whether sel_start or sel_end comes first */
	if (!con->sel_start.line && con->sel_start.y == SELECTION_TOP) {
		if (!con->sel_end.line && con->sel_end.y == SELECTION_TOP) {
			str = strdup("");
			if (!str)
				return -ENOMEM;
			*out = str;
			return 0;
		}
		start = &con->sel_start;
		end = &con->sel_end;
	} else if (!con->sel_end.line && con->sel_end.y == SELECTION_TOP) {
		start = &con->sel_end;
		end = &con->sel_start;
	} else if (con->sel_start.line && con->sel_end.line) {
		if (con->sel_start.line->sb_id < con->sel_end.line->sb_id) {
			start = &con->sel_start;
			end = &con->sel_end;
		} else if (con->sel_start.line->sb_id > con->sel_end.line->sb_id) {
			start = &con->sel_end;
			end = &con->sel_start;
		} else if (con->sel_start.x < con->sel_end.x) {
			start = &con->sel_start;
			end = &con->sel_end;
		} else {
			start = &con->sel_end;
			end = &con->sel_start;
		}
	} else if (con->sel_start.line) {
		start = &con->sel_start;
		end = &con->sel_end;
	} else if (con->sel_end.line) {
		start = &con->sel_end;
		end = &con->sel_start;
	} else if (con->sel_start.y < con->sel_end.y) {
		start = &con->sel_start;
		end = &con->sel_end;
	} else if (con->sel_start.y > con->sel_end.y) {
		start = &con->sel_end;
		end = &con->sel_start;
	} else if (con->sel_start.x < con->sel_end.x) {
		start = &con->sel_start;
		end = &con->sel_end;
	} else {
		start = &con->sel_end;
		end = &con->sel_start;
	}

	/* calculate size of buffer */
	len = 0;
	iter = start->line;
	if (!iter && start->y == SELECTION_TOP)
		iter = con->sb_first;

	while (iter) {
		if (iter == start->line && iter == end->line) {
			if (iter->size > start->x) {
				if (iter->size > end->x)
					len += end->x - start->x + 1;
				else
					len += iter->size - start->x;
			}
			break;
		} else if (iter == start->line) {
			if (iter->size > start->x)
				len += iter->size - start->x;
		} else if (iter == end->line) {
			if (iter->size > end->x)
				len += end->x + 1;
			else
				len += iter->size;
			break;
		} else {
			len += iter->size;
		}

		++len;
		iter = iter->next;
	}

	if (!end->line) {
		if (start->line || start->y == SELECTION_TOP)
			i = 0;
		else
			i = start->y;
		for ( ; i < con->size_y; ++i) {
			if (!start->line && start->y == i && end->y == i) {
				if (con->size_x > start->x) {
					if (con->size_x > end->x)
						len += end->x - start->x + 1;
					else
						len += con->size_x - start->x;
				}
				break;
			} else if (!start->line && start->y == i) {
				if (con->size_x > start->x)
					len += con->size_x - start->x;
			} else if (end->y == i) {
				if (con->size_x > end->x)
					len += end->x + 1;
				else
					len += con->size_x;
				break;
			} else {
				len += con->size_x;
			}

			++len;
		}
	}

	/* allocate buffer */
	len *= 4;
	++len;
	str = malloc(len);
	if (!str)
		return -ENOMEM;
	pos = str;

	/* copy data into buffer */
	iter = start->line;
	if (!iter && start->y == SELECTION_TOP)
		iter = con->sb_first;

	while (iter) {
		if (iter == start->line && iter == end->line) {
			if (iter->size > start->x) {
				if (iter->size > end->x)
					len = end->x - start->x + 1;
				else
					len = iter->size - start->x;
				pos += copy_line(iter, pos, start->x, len);
			}
			break;
		} else if (iter == start->line) {
			if (iter->size > start->x)
				pos += copy_line(iter, pos, start->x,
						 iter->size - start->x);
		} else if (iter == end->line) {
			if (iter->size > end->x)
				len = end->x + 1;
			else
				len = iter->size;
			pos += copy_line(iter, pos, 0, len);
			break;
		} else {
			pos += copy_line(iter, pos, 0, iter->size);
		}

		*pos++ = '\n';
		iter = iter->next;
	}

	if (!end->line) {
		if (start->line || start->y == SELECTION_TOP)
			i = 0;
		else
			i = start->y;
		for ( ; i < con->size_y; ++i) {
			iter = con->lines[i];
			if (!start->line && start->y == i && end->y == i) {
				if (con->size_x > start->x) {
					if (con->size_x > end->x)
						len = end->x - start->x + 1;
					else
						len = con->size_x - start->x;
					pos += copy_line(iter, pos, start->x, len);
				}
				break;
			} else if (!start->line && start->y == i) {
				if (con->size_x > start->x)
					pos += copy_line(iter, pos, start->x,
							 con->size_x - start->x);
			} else if (end->y == i) {
				if (con->size_x > end->x)
					len = end->x + 1;
				else
					len = con->size_x;
				pos += copy_line(iter, pos, 0, len);
				break;
			} else {
				pos += copy_line(iter, pos, 0, con->size_x);
			}

			*pos++ = '\n';
		}
	}

	/* return buffer */
	*pos = 0;
	*out = str;
	return pos - str;
}
void
f_pixbuf_copy_with_orientation (GdkPixbuf *src, GdkPixbuf *dest, int orientation)
{
	gboolean rotate = FALSE;
	gboolean flip = FALSE;
	gboolean mirror = FALSE;
	
	int sw = gdk_pixbuf_get_width (src);
	int sh = gdk_pixbuf_get_height (src);
	int dw = gdk_pixbuf_get_width (dest);
	int dh = gdk_pixbuf_get_height (dest);
	

	int channels = gdk_pixbuf_get_n_channels (src);
	
	int dstride = gdk_pixbuf_get_rowstride (dest);
	int sstride = gdk_pixbuf_get_rowstride (src);
	
	guchar *sp = gdk_pixbuf_get_pixels (src);
	guchar *dp = gdk_pixbuf_get_pixels (dest);		
	int offset = sstride;

	if (channels != gdk_pixbuf_get_n_channels (dest)) {
		g_warning ("source and dest channels do no match");
		return;
	}
	
	switch (orientation) {
	case 1: // TopLeft
		break;
	case 2: // TopRight
		flip = TRUE;
		break;
	case 3: // BottomRight
		mirror = TRUE;
		flip = TRUE;
		break;
	case 4: // BottomLeft
		mirror = TRUE;
		break;
	case 5: // LeftTop
		rotate = TRUE;
		break;
	case 6: // RightTop
		mirror = TRUE;
		rotate = TRUE;
		break;
	case 7: // RightBottom
		flip = TRUE;
		mirror = TRUE;
		rotate = TRUE;
		break;
	case 8: // LeftBottom
		flip = TRUE;
		rotate = TRUE;
		break;
	}

	if (rotate && (dh != sw || dw != sh)) {
		g_warning ("source and destination sizes do not match orientation");
		return;
	}
	
	//g_warning ("rotate = %d, flip = %d, mirror = %d", rotate, flip, mirror);
	if (mirror) {
		offset = -sstride;
		sp = sp + (sh - 1) * sstride;
	}
	
	while (sh --) {
		if (rotate) {
			rotate_line (sp, dp, sw, dstride, channels, flip);
			dp += channels;
		} else {
				
			copy_line (sp, dp, sw, channels, flip);
			dp += dstride;
		}
		sp += offset;
	}
}
Ejemplo n.º 25
0
/*
 * Name:    flush_right
 * Purpose: flush line on right margin
 * Date:    November 27, 1991
 * Passed:  window:  pointer to current window
 */
int  flush_right( WINDOW *window )
{
int  len;               /* length of current line */
int  i;
int  spaces;
char *source;
char *dest;
register int rcol;
int  rm;
register WINDOW *win;   /* put window pointer in a register */

   win = window;
   copy_line( win->ll );
   detab_linebuff( );
   source = g_status.line_buff;
   len = g_status.line_buff_len;
   if (!is_line_blank( (text_ptr)source, len )) {
      rm = mode.right_margin;
      for (rcol=len-1; rcol>=0 && *(source+rcol) == ' ';)
         rcol--;
      if (rcol != rm) {

         /*
          * if rcol is less than right margin then we need to add spaces.
          */
         if (rcol < rm) {
            spaces = rm - rcol;
            dest = source + spaces;
            if (len + spaces > MAX_LINE_LENGTH) {
               /*
                * line would be too long
                */
               error( WARNING, win->bottom_line, ww1 );
               return( ERROR );
            } else {
               load_undo_buffer( win->file_info, win->ll->line, win->ll->len );

               assert( len >= 0 );
               assert( len < MAX_LINE_LENGTH );

               memmove( dest, source, len );
               g_status.line_buff_len += spaces;
               while (spaces--)
                  *source++ = ' ';
               win->file_info->dirty = GLOBAL;
            }

         /*
          * if rcol is greater than right margin then we need to sub spaces.
          */
         } else {
            load_undo_buffer( win->file_info, win->ll->line, win->ll->len );
            rcol = rcol - rm;
            i = first_non_blank( (text_ptr)source, len );
            if (rcol > i)
               rcol = i;
            dest = source + rcol;

            assert( len - rcol >= 0 );
            assert( len - rcol < MAX_LINE_LENGTH );

            memmove( source, dest, len - rcol );
            g_status.line_buff_len -= (rcol - rm);
            win->file_info->dirty = GLOBAL;
         }
         win->ll->dirty = TRUE;
         show_changed_line( win );
      }
   }
   return( OK );
}
Ejemplo n.º 26
0
/*
 * Name:    flush_center
 * Purpose: flush line in center of margins
 * Date:    November 27, 1991
 * Passed:  window:  pointer to current window
 */
int  flush_center( WINDOW *window )
{
int  len;               /* length of current line */
char *source;           /* temp line buffer pointers */
char *dest;
int  rm;
int  lm;
register int spaces;    /* center of text on current line */
int  center;            /* center of current margins */
int  first;             /* column of first char on line */
int  last;              /* column of last char on line */
register WINDOW *win;   /* put window pointer in a register */

   win = window;
   copy_line( win->ll );
   detab_linebuff( );
   source = g_status.line_buff;
   len = g_status.line_buff_len;
   if (!is_line_blank( (text_ptr)source, len )) {
      rm = mode.right_margin;
      lm = mode.left_margin;
      center = (rm + lm) / 2;
      first = first_non_blank( (text_ptr)source, len );
      for (last=len-1; last>=0 && *(source+last) == ' ';)
         last--;
      spaces = last + first - 1;
      spaces = (spaces / 2) + (spaces & 1);
      if (spaces != center) {

         /*
          * if spaces is less than center margin then we need to add spaces.
          */
         if (spaces < center) {
            spaces = center - spaces;
            dest = source + spaces;
            if (len + spaces > MAX_LINE_LENGTH) {
               /*
                * line would be too long
                */
               error( WARNING, win->bottom_line, ww1 );
               return( ERROR );
            } else {
               load_undo_buffer( win->file_info, win->ll->line, win->ll->len );

               assert( len >= 0 );
               assert( len < MAX_LINE_LENGTH );

               memmove( dest, source, len );
               g_status.line_buff_len += spaces;
               while (spaces--)
                  *source++ = ' ';
               win->file_info->dirty = GLOBAL;
            }

         /*
          * if spaces is greater than center margin then we need to sub spaces.
          */
         } else {
            load_undo_buffer( win->file_info, win->ll->line, win->ll->len );
            spaces = spaces - center;
            if (spaces > first)
               spaces = first;
            dest = source + spaces;

            assert( len - spaces >= 0 );
            assert( len - spaces < MAX_LINE_LENGTH );

            memmove( source, dest, len - spaces );
            g_status.line_buff_len -= spaces;
            win->file_info->dirty = GLOBAL;
         }
         win->ll->dirty = TRUE;
         show_changed_line( win );
      }
   }
   return( OK );
}
Ejemplo n.º 27
0
void mvKMeans:: KMeans_CreateStartingClusters (unsigned nClusters) {
/* creates N starting clusters for the KMeans algorithm. A "cluster" really means the
 * start/endpoints of the line that other lines can bin to. The clusters are chosen thus:
 * The first cluster is just the strongest line (line[0] from HoughLines)
 * The n+1'th cluster is the line which is most different from existing clusters. This is
 * calculated as the line whose minimum difference wrt existing clusters is the greatest.
 */   
    bool line_already_chosen[_nLines];
    for (unsigned i = 0; i < _nLines; i++)
        line_already_chosen[i] = false;
    
    /// choose first seed cluster, then 2nd, etc in this loop
    for (unsigned N = 0; N < nClusters; N++) {  
        //DEBUG_PRINT ("Choosing cluster %d\n", N);
        
        /// For first cluster choose line[0];
        if (N == 0) {
            // I cant believe this is what happens when you pass in pointers like you are supposed to
            //_Clusters_Seed[N] = (*_Lines)[0];     // pointer copy 
            copy_line ((*_Lines)[0], _Clusters_Seed[N]);
            continue;
        }
        
        /// For other clusters, loop over each line and chose a line based on the method specified
        unsigned next_cluster_index = 0;       
        unsigned next_cluster_max_diff = 0;
        
        #ifdef CREATE_STARTING_CLUSTERS_APPROX   /// find the line most different from the last line chosen as a cluster
        
        for (unsigned line_index = 0; line_index < _nLines; line_index++) { 
            if (line_already_chosen[line_index] == true) continue;
            
            // calculate the diff between this line and last selected cluster
            unsigned diff_from_last_cluster = Get_Line_ClusterSeed_Diff (N-1, line_index);
            
            if (diff_from_last_cluster > next_cluster_max_diff) {
                next_cluster_max_diff = diff_from_last_cluster;
                next_cluster_index = line_index;
            }
        }
        
        #else                                    /// find the line whose min diff from any of the prev clusters is greatest
        
        for (unsigned line_index = 0; line_index < _nLines; line_index++) { 
            if (line_already_chosen[line_index] == true) continue;
            
            unsigned long min_diff_from_cluster = 1E9;       // init this to a huge number
            // loop to find min_diff_from_cluster
            for (unsigned cluster_index = 0; cluster_index < N; cluster_index++) {   
                unsigned diff_from_cluster_i = Get_Line_ClusterSeed_Diff (cluster_index, line_index);
                //DEBUG_PRINT ("      Cluster %d - line %d: diff = %d\n", cluster_index,line_index,diff_from_cluster_i);
                
                if (diff_from_cluster_i < min_diff_from_cluster)
                    min_diff_from_cluster = diff_from_cluster_i;
            }
            
            if (min_diff_from_cluster > next_cluster_max_diff) {
                next_cluster_max_diff = min_diff_from_cluster;
                next_cluster_index = line_index;
            }
        }
        
        #endif
        
        /// now copy the data for the line chosen to be the next cluster
        //printf ("  Using line %d for cluster %d\n", next_cluster_index, N);
        copy_line ((*_Lines)[next_cluster_index], _Clusters_Seed[N]); // copy starting point
        line_already_chosen[next_cluster_index] = true;
    }
}
Ejemplo n.º 28
0
float mvKMeans:: KMeans_Cluster (unsigned nClusters, unsigned iterations) {
/* bins each line to the closest starting/seed cluster, then averages the bins to get the starting/seed cluster
 * for the next iteration.
 * We also calculate a "validity" score for the clustering configuration. validity is defined as "avg_intra_cluster_diff"
 * divided by "minimum_inter_cluster_diff". Essentially it is the spread of lines in a cluster divided by the spread
 * amongst clusters. The smaller the validity the better.
 * Note minimum_inter_cluster_diff is not defined for nClusters == 1, so we wing it. See below. 
 */    
    unsigned weight;
    unsigned short cluster_of_line[_nLines]; // stores which cluster a line is binned to
    unsigned lines_per_cluster[nClusters];
    unsigned weight_per_cluster[nClusters];    
    
    for (unsigned iter = 0; iter < iterations; iter++) {       
        /// first clear the temp clusters
        for (unsigned i = 0; i < nClusters; i++) {   
            _Clusters_Temp[i][0] = cvPoint (0,0);
            _Clusters_Temp[i][1] = cvPoint (0,0);
            weight_per_cluster[i] = 0;
            lines_per_cluster[i] = 0;
        }

        /// loop over each line and bin that line to a cluster
        for (unsigned line_index = 0; line_index < _nLines; line_index++) {
            unsigned closest_cluster_index = 0;
            unsigned long closest_cluster_diff = 1E9;
            unsigned cluster_diff_i;
            
            /// go thru each cluster and find the one that is closest (least diff) wrt this line
            for (unsigned cluster_index = 0; cluster_index < nClusters; cluster_index++) {
                cluster_diff_i = Get_Line_ClusterSeed_Diff (cluster_index, line_index);
                
                if (cluster_diff_i < closest_cluster_diff) {
                    closest_cluster_diff = cluster_diff_i;
                    closest_cluster_index = cluster_index;
                }
            }

            /// rejection routine: if the closest_cluster_diff is too high, simply ignore this line


            /// add the line to the temp cluster
            weight = line_sqr_length((*_Lines)[line_index]);
            _Clusters_Temp[closest_cluster_index][0].x += weight * ((*_Lines)[line_index][0].x);
            _Clusters_Temp[closest_cluster_index][0].y += weight * ((*_Lines)[line_index][0].y);
            _Clusters_Temp[closest_cluster_index][1].x += weight * ((*_Lines)[line_index][1].x);
            _Clusters_Temp[closest_cluster_index][1].y += weight * ((*_Lines)[line_index][1].y);

            lines_per_cluster[closest_cluster_index]++;
            weight_per_cluster[closest_cluster_index] += weight;
            cluster_of_line[line_index] = closest_cluster_index; /*****************/
        }
        
        /// calculate the next iteration's clusters and copy them over to clusters_seed
        for (unsigned i = 0; i < nClusters; i++) {
            if (weight_per_cluster[i] == 0) continue;
            
            _Clusters_Temp[i][0].x /= weight_per_cluster[i];
            _Clusters_Temp[i][0].y /= weight_per_cluster[i];
            _Clusters_Temp[i][1].x /= weight_per_cluster[i];
            _Clusters_Temp[i][1].y /= weight_per_cluster[i];
            
            copy_line (_Clusters_Temp[i], _Clusters_Seed[i]);
        }
    }
    
    float avg_intra_cluster_diff = 0.0;
    //float avg_inter_cluster_diff = 0.0;
    float minimum_inter_cluster_diff = 1E12;

    /// calculate avg_intra_cluster_diff
    if (nClusters == _nLines) {
        avg_intra_cluster_diff = GLOBAL_INT_FACTOR * SINGLE_LINE__CLUSTER_INTRA_DIFF;
    }
    else {
        for (unsigned line_index = 0; line_index < _nLines; line_index++) {
            avg_intra_cluster_diff += Get_Line_ClusterSeed_Diff (cluster_of_line[line_index], line_index);
        }
    }
    /*for (unsigned i = 0, product_of_lines_per_cluster = 1; i < nClusters; i++) {
        product_of_lines_per_cluster *= lines_per_cluster[i];
    }*/
    avg_intra_cluster_diff = avg_intra_cluster_diff / _nLines;//product_of_lines_per_cluster / nClusters;
    
    /// now calculate the minimum_inter_cluster_diff and the validity score
    if (nClusters == 1) {
        // this equation basically says "when comparing 1 cluster vs 2 clusters, the 2 clusters have to be a ratio
        // of perpendicular dist over length of less than 0.2 to be better than the 1 cluster configuration
        minimum_inter_cluster_diff = GLOBAL_INT_FACTOR * SINGLE_CLUSTER__INTER_DIFF; // * line_sqr_length(_Clusters_Seed[0]);
        //avg_inter_cluster_diff = GLOBAL_INT_FACTOR * SINGLE_CLUSTER__INTER_DIFF; // * line_sqr_length(_Clusters_Seed[0]);
    }
    else {
        for (unsigned i = 0; i < nClusters; i++) { // loop over all combinations of clusters, find min_inter_cluster_diff
            for (unsigned j = i+1; j < nClusters; j++) {
                float temp_diff = Line_Difference_Metric (_Clusters_Seed[i], _Clusters_Seed[j]);
                if (temp_diff < minimum_inter_cluster_diff)
                    minimum_inter_cluster_diff = temp_diff;
                //avg_inter_cluster_diff += temp_diff;
            }
        }
    }

    DEBUG_PRINT ("  nClusters = %d.  intra = %f,  inter = %f\n", nClusters, avg_intra_cluster_diff, minimum_inter_cluster_diff);
    return avg_intra_cluster_diff / minimum_inter_cluster_diff; 
}
Ejemplo n.º 29
0
char *
readline(const char *prompt)
{
    int cur_char;
    char *new_line;


    /* start with a string of MAXBUF chars */
    if (line_len != 0) {
	free(cur_line);
	line_len = 0;
    }
    cur_line = gp_alloc(MAXBUF, "readline");
    line_len = MAXBUF;

    /* set the termio so we can do our own input processing */
    set_termio();

    /* print the prompt */
    fputs(prompt, stderr);
    cur_line[0] = '\0';
    cur_pos = 0;
    max_pos = 0;
    cur_entry = NULL;

    /* get characters */
    for (;;) {

	cur_char = special_getc();

	/* Accumulate ascii (7bit) printable characters
	 * and all leading 8bit characters.
	 */
	if ((isprint(cur_char)
	      || (((cur_char & 0x80) != 0) && (cur_char != EOF)))
	    && (cur_char != 0x09) /* TAB is a printable character in some locales */
	    ) {
	    size_t i;

	    if (max_pos + 1 >= line_len) {
		extend_cur_line();
	    }
	    for (i = max_pos; i > cur_pos; i--) {
		cur_line[i] = cur_line[i - 1];
	    }
	    user_putc(cur_char);

	    cur_line[cur_pos] = cur_char;
	    cur_pos += 1;
	    max_pos += 1;
	    cur_line[max_pos] = '\0';

	    if (cur_pos < max_pos) {
		switch (encoding) {
		case S_ENC_UTF8:
		    if ((cur_char & 0xc0) == 0)
			fix_line(); /* Normal ascii character */
		    else if ((cur_char & 0xc0) == 0xc0)
			; /* start of a multibyte sequence. */
		    else if (((cur_char & 0xc0) == 0x80) &&
			 ((unsigned char)(cur_line[cur_pos-2]) >= 0xe0))
			; /* second byte of a >2 byte sequence */
		    else {
			/* Last char of multi-byte sequence */
			fix_line();
		    }
		    break;
		default:
		    fix_line();
		    break;
		}
	    }

	/* else interpret unix terminal driver characters */
#ifdef VERASE
	} else if (cur_char == term_chars[VERASE]) {	/* ^H */
	    delete_backward();
#endif /* VERASE */
#ifdef VEOF
	} else if (cur_char == term_chars[VEOF]) {	/* ^D? */
	    if (max_pos == 0) {
		reset_termio();
		return ((char *) NULL);
	    }
	    delete_forward();
#endif /* VEOF */
#ifdef VKILL
	} else if (cur_char == term_chars[VKILL]) {	/* ^U? */
	    clear_line(prompt);
#endif /* VKILL */
#ifdef VWERASE
	} else if (cur_char == term_chars[VWERASE]) {	/* ^W? */
	    delete_previous_word();
#endif /* VWERASE */
#ifdef VREPRINT
	} else if (cur_char == term_chars[VREPRINT]) {	/* ^R? */
	    putc(NEWLINE, stderr);	/* go to a fresh line */
	    redraw_line(prompt);
#endif /* VREPRINT */
#ifdef VSUSP
	} else if (cur_char == term_chars[VSUSP]) {
	    reset_termio();
	    kill(0, SIGTSTP);

	    /* process stops here */

	    set_termio();
	    /* print the prompt */
	    redraw_line(prompt);
#endif /* VSUSP */
	} else {
	    /* do normal editing commands */
	    /* some of these are also done above */
	    switch (cur_char) {
	    case EOF:
		reset_termio();
		return ((char *) NULL);
	    case 001:		/* ^A */
		while (cur_pos > 0)
		    backspace();
		break;
	    case 002:		/* ^B */
		if (cur_pos > 0)
		    backspace();
		break;
	    case 005:		/* ^E */
		while (cur_pos < max_pos) {
		    user_putc(cur_line[cur_pos]);
		    cur_pos += 1;
		}
		break;
	    case 006:		/* ^F */
		if (cur_pos < max_pos) {
		    step_forward();
		}
		break;
#if defined(HAVE_DIRENT_H) || defined(WIN32)
	    case 011:		/* ^I / TAB */
		tab_completion(TRUE); /* next tab completion */
		break;
	    case 034:		/* remapped by wtext.c or ansi_getc from Shift-Tab */
		tab_completion(FALSE); /* previous tab completion */
		break;
#endif
	    case 013:		/* ^K */
		clear_eoline(prompt);
		max_pos = cur_pos;
		break;
	    case 020:		/* ^P */
		if (history != NULL) {
		    if (cur_entry == NULL) {
			cur_entry = history;
			clear_line(prompt);
			copy_line(cur_entry->line);
		    } else if (cur_entry->prev != NULL) {
			cur_entry = cur_entry->prev;
			clear_line(prompt);
			copy_line(cur_entry->line);
		    }
		}
		break;
	    case 016:		/* ^N */
		if (cur_entry != NULL) {
		    cur_entry = cur_entry->next;
		    clear_line(prompt);
		    if (cur_entry != NULL)
			copy_line(cur_entry->line);
		    else
			cur_pos = max_pos = 0;
		}
		break;
	    case 014:		/* ^L */
	    case 022:		/* ^R */
		putc(NEWLINE, stderr);	/* go to a fresh line */
		redraw_line(prompt);
		break;
#ifndef DEL_ERASES_CURRENT_CHAR
	    case 0177:		/* DEL */
	    case 023:		/* Re-mapped from CSI~3 in ansi_getc() */
#endif
	    case 010:		/* ^H */
		delete_backward();
		break;
	    case 004:		/* ^D */
		if (max_pos == 0) {
		    reset_termio();
		    return ((char *) NULL);
		}
		/* intentionally omitting break */
#ifdef DEL_ERASES_CURRENT_CHAR
	    case 0177:		/* DEL */
	    case 023:		/* Re-mapped from CSI~3 in ansi_getc() */
#endif
		delete_forward();
		break;
	    case 025:		/* ^U */
		clear_line(prompt);
		break;
	    case 027:		/* ^W */
		delete_previous_word();
		break;
	    case '\n':		/* ^J */
	    case '\r':		/* ^M */
		cur_line[max_pos + 1] = '\0';
#ifdef OS2
		while (cur_pos < max_pos) {
		    user_putc(cur_line[cur_pos]);
		    cur_pos += 1;
		}
#endif
		putc(NEWLINE, stderr);

		/* Shrink the block down to fit the string ?
		 * if the alloc fails, we still own block at cur_line,
		 * but this shouldn't really fail.
		 */
		new_line = (char *) gp_realloc(cur_line, strlen(cur_line) + 1,
					       "line resize");
		if (new_line)
		    cur_line = new_line;
		/* else we just hang on to what we had - it's not a problem */

		line_len = 0;
		FPRINTF((stderr, "Resizing input line to %d chars\n", strlen(cur_line)));
		reset_termio();
		return (cur_line);
	    default:
		break;
	    }
	}
    }
}
Ejemplo n.º 30
0
static void sanitize_group(void) {
	struct stat s;
	if (stat("/etc/group", &s) == -1)
		return;
	assert(gid_min);
	if (arg_debug)
		printf("Sanitizing /etc/group, GID_MIN %d\n", gid_min);
	if (is_link("/etc/group")) {
		fprintf(stderr, "Error: invalid /etc/group\n");
		exit(1);
	}

	FILE *fpin = NULL;
	FILE *fpout = NULL;

	// open files
	/* coverity[toctou] */
	fpin = fopen("/etc/group", "r");
	if (!fpin)
		goto errout;
	fpout = fopen(RUN_GROUP_FILE, "w");
	if (!fpout)
		goto errout;

	// read the file line by line
	char buf[MAXBUF];
	gid_t mygid = getgid();
	while (fgets(buf, MAXBUF, fpin)) {
		// comments and empty lines
		if (*buf == '\0' || *buf == '#')
			continue;

		// sample line:
		// 	pulse:x:115:netblue,bingo
		// drop lines with uid > 1000 and not the current user group
		char *ptr = buf;

		// advance to uid
		while (*ptr != ':' && *ptr != '\0')
			ptr++;
		if (*ptr == '\0')
			goto errout;
		ptr++;
		while (*ptr != ':' && *ptr != '\0')
			ptr++;
		if (*ptr == '\0')
			goto errout;
		ptr++;
		if (*ptr == '\0')
			goto errout;

		// process uid
		int gid;
		int rv = sscanf(ptr, "%d:", &gid);
		if (rv == 0 || gid < 0)
			goto errout;
		assert(gid_min);
		if (gid < gid_min || gid == 65534) { // on Debian platforms 65534 is group nogroup
			if (copy_line(fpout, buf, ptr))
				goto errout;
			continue;
		}
		if ((gid_t) gid != mygid) {
			continue; // skip line
		}
		if (copy_line(fpout, buf, ptr))
			goto errout;
	}
	fclose(fpin);
	SET_PERMS_STREAM(fpout, 0, 0, 0644);
	fclose(fpout);

	// mount-bind tne new group file
	if (mount(RUN_GROUP_FILE, "/etc/group", "none", MS_BIND, "mode=400,gid=0") < 0)
		errExit("mount");
	fs_logger("create /etc/group");

	return;

errout:
	fwarning("failed to clean up /etc/group\n");
	if (fpin)
		fclose(fpin);
	if (fpout)
		fclose(fpout);
}