Пример #1
0
int main(int argc, const char *argv[])
{
    char s[] = "Heljo, world!";

    printf("%s\n", s);

    delete_char(s, 'l');
    
    printf("%s\n", s);
    return 0;
}
Пример #2
0
void ttext_::handle_key_delete(SDLMod /*modifier*/, bool& handled)
{
    DBG_GUI_E << LOG_SCOPE_HEADER << '\n';

    handled = true;
    if(selection_length_ != 0) {
        delete_selection();
    } else if (selection_start_ < text_.get_length()) {
        delete_char(false);
    }
}
Пример #3
0
void ttext_::handle_key_backspace(SDLMod /*modifier*/, bool& handled)
{
	DBG_GUI_E << LOG_SCOPE_HEADER << '\n';

	handled = true;
	if(selection_length_ != 0) {
		delete_selection();
	} else if(selection_start_){
		delete_char(true);
	}
	fire(event::NOTIFY_MODIFIED, *this, NULL);
}
Пример #4
0
void ttext_::handle_key_delete(SDL_Keymod /*modifier*/, bool& handled)
{
	DBG_GUI_E << LOG_SCOPE_HEADER << '\n';

	handled = true;
	if(selection_length_ != 0) {
		delete_selection();
	} else if(selection_start_ < text_.get_length()) {
		delete_char(false);
	}
	fire(event::NOTIFY_MODIFIED, *this, nullptr);
}
Пример #5
0
/*加密(<<POINTERS ON C>> Chapter 9.12/13/14 at page 190) */
int prepare_key(char * key)
{
	char letter[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	char ch;
	char * p;
	p = key;
	
	/*  */
	if(p == NULL || *p == '\0')
		return 0;
	/* to all charters Upper 
	   检查是否有非法字符
	*/
	while(*p != '\0')
	{
		if(!isalpha(*p))
			return 0;
		*p = toupper(*p);
		p++;
	}

	p = key;
	while((ch = *p) != '\0')
	{
		p++;
		delete_char(p,ch);
	}
	
	p = key;
	while((ch = *p++) != '\0')
	{
		delete_char(letter,ch);
	}

	strcat(key,letter);

	
	return 1;
}
Пример #6
0
void tpassword_box::handle_key_delete(SDLMod /*modifier*/, bool& handled) {
	pre_function();

	// Copy & paste from ttext_::handle_key_delete()
	DBG_GUI_E << LOG_SCOPE_HEADER << '\n';

	handled = true;
	if(get_selection_length() != 0) {
		delete_selection();
	} else if (get_selection_start() < get_text_length(text())) {
		delete_char(false);
	}

	post_function();
}
Пример #7
0
Файл: FED.C Проект: MegaGod/TW
int select_font( int *page, char *status ) {
	static int ch = 0;
	char tmp;
	int dum;
	extern int cur_char;
	unsigned maxx, maxy;
	int save = get_active_clock( );
	static new_page = -1;
	char key, ch2;

	start_clock( SELECT_FONT );

	maxx = 256 / char_per_col( );
	maxy = char_per_col( );
	cur_char = ch;
	while ( !( ( key = get_pos( &sel_x, &sel_y, maxx, maxy - 1, 1, 1 ) ) == RET ||
		key == 3 ) ) {
		ch = sel_y + sel_x*char_per_col( );
		if ( ch>255 ) {
			sel_x = maxx;
			sel_y = char_per_col( ) - ( ( char_per_col( )*( 1 + sel_x ) ) - 255 );
			ch = 255;
		};
		cur_char = ch;
		if ( new_page == -1 ) {
			switch ( tolower( key ) ) {
			case 'o':
				new_page = 0;
				ch2 = select_font( &dum, &tmp );
				if ( *status == RET ) {
					or_char( ch, ch2 );
					print_table( which_page( ch ) );
				}
				new_page = -1;
				break;
			case '?':
				help_select( ); break;
			case 1:
				insert_char( ch ); break;
			case 2:
				delete_char( ch ); break;
			}
		}
	}
	start_clock( save );
	*status = key;
	return ch;
}
Пример #8
0
void centerline(unsigned y)
{
    int i,j,k,count;
    for(i=1;(workline.middle[i] == ' ') || (workline.middle[i] == WRAPBLANK);i++);
    for(j = strlen(workline.middle) - 1;
        (workline.middle[j] == ' ') || (workline.middle[j] == WRAPBLANK);j--);
    if ((rightmar - leftmar) > (j - i)) {
      k = leftmar + ((rightmar - leftmar) - (j - i))/2;
      if (k < i) {
        for (count = i - k;count > 0;count--)
          delete_char(0);
      } else {
        for (count = k - i;count > 0;count--)
          insertblank(1,' ');
      }
      refreshline(0,y);
    }
}
Пример #9
0
/*
 * Revert an action.  Return the next undo entry.
 */
static Undo *
revert_action (Undo * up)
{
  size_t i;
  Point pt;

  pt.n = up->n;
  pt.o = up->o;

  doing_undo = true;

  if (up->type == UNDO_END_SEQUENCE)
    {
      undo_save (UNDO_START_SEQUENCE, pt, 0, 0);
      up = up->next;
      while (up->type != UNDO_START_SEQUENCE)
        up = revert_action (up);
      pt.n = up->n;
      pt.o = up->o;
      undo_save (UNDO_END_SEQUENCE, pt, 0, 0);
      goto_point (pt);
      return up->next;
    }

  goto_point (pt);

  if (up->type == UNDO_REPLACE_BLOCK)
    {
      undo_save (UNDO_REPLACE_BLOCK, pt,
                 up->block.size, up->block.osize);
      undo_nosave = true;
      for (i = 0; i < up->block.size; ++i)
        delete_char ();
      insert_nstring (astr_cstr (up->block.text), up->block.osize);
      undo_nosave = false;
    }

  doing_undo = false;

  if (up->unchanged)
    set_buffer_modified (cur_bp, false);

  return up->next;
}
Пример #10
0
static void		skip_quotes_replace_string(t_cmd *cmd, char **str, size_t *i)
{
	while ((*str)[*i] && !ft_isspace2((*str)[*i]) && !is_sep(i, *str, 0, cmd))
	{
		if ((*str)[*i] == '\\')
		{
			if ((*str)[*i + 1])
				*str = delete_char(*str, *i + 1);
		}
		else
		{
			if ((is_redir(i, *str, 0, cmd) || is_aggr(i, *str, 0)) &&
			ft_isdigit((*str)[*i]))
			{
				(*i)++;
				break ;
			}
			if (is_quote_open((*str)[*i]) && !is_escaped_char(*str, *i))
				join_inside_quote(i, str);
		}
		if ((*str)[*i])
			(*i)++;
	}
}
Пример #11
0
/*------------------------------------------------------------------------------
 * main -- Open terminal and launch keypad thread.
 *         Check for button input and respond appropriately
 *------------------------------------------------------------------------------
 */
int main (void) {
//  int i;
  int ret;
  char *emergency="! EMERGENCY !";
  char button_read = FALSE;  // Local snapshot of Global 'Button'
  char prev_button = 0;

  /* error handling - reset LEDs */
  atexit(closing_time);
  signal(SIGINT, closing_time);

  term_initio();
  rs232_open();
  
  setup_ports();
  ret = pthread_create( &keypad_thread, NULL, keypad, NULL);
    
  while(alive){
    button_read = button;
    if(button_read){
      if(prev_button != button_read){
        if(blocking){
          while(blocking == TRUE && alive){
            usleep(SLEEP);
          }
        }
        else{
          printf("button: %c\n",button_read);
          switch(button_read){
            case 'A':
              display_string("Hello. =)",BLOCKING);
              break;
            case 'B':
              move_cursor(LEFT);
              break;
            case 'C':
              display_string("Cancel =(",NOT_BLOCKING);
              break;
            case 'D':
              delete_char();
              break;
            case 'E':
              display_string(emergency,BLOCKING);
              break;
            case 'F':
              move_cursor(RIGHT);
              break;
            case ERROR:
              break;
            default:
              insert_char(button_read);
              break;
          }
        }
      }
    }
    prev_button = button_read;
  }

  pthread_join(keypad_thread, NULL);

  term_exitio();
  rs232_close();
  return 0;
}
Пример #12
0
char *get_command_line(int new_cmd, int comp_type)
{
	int	c, ind = 0, len = 0, res;
	char	input_buf[READ_BUF_SIZE];
	char	*str;

	if (set_term_flags() != 0)
		exit(1);
	get_history_new(new_cmd);
	memset(input_buf, 0, READ_BUF_SIZE);
	for (;;) {
		c = getchar();
		len = strlen(input_buf);
		if (len >= (READ_BUF_SIZE - 1)) c = NL_KEY;
		switch (c) {
		case CTRL_A_KEY:
			go_to_begin(ind);
			ind = print_str_by_index(input_buf, 0, 0);
			break;
		case CTRL_B_KEY:
			printf("%c", '\b');
			ind--;
			if (ind < 0) {
				ind = 0;
				printf("%c", ' ');
			};
			break;
		case CTRL_D_KEY:
			if (ind == len) break;
			ind = delete_char(input_buf, len, ind, 1);
			break;
		case CTRL_E_KEY:
			ind = print_str_by_index(input_buf, ind, len);
			break;
		case CTRL_G_KEY:
		case CTRL_L_KEY:
			printf("%c", c);
			break;
		case CTRL_F_KEY:
			ind = print_str_by_index(input_buf, ind, ind + 1);
			break;
		case TAB_KEY:
			res = completion_func(comp_type, input_buf,
				&complition_struct);
			if (res == 0) break;
			if (res == 1) {
				strcpy(input_buf, complition_struct.items[0]);
				strcat(input_buf, " ");
				ind = print_str_by_index(input_buf, ind, -1);
				break;
			};
			memset(input_buf, 0, READ_BUF_SIZE);
			strncpy(input_buf, complition_struct.items[0],
				complition_struct.comp_len);
			ind = print_str_by_index(input_buf, ind, -1);
			break;
		case NL_KEY:
			printf("%c", c);
			if (current_hist_ind != hist_ind)
				add_to_history(input_buf, hist_ind);
			if (strlen(input_buf) == 0) return("");
			add_to_history(input_buf, current_hist_ind);
			return(History[current_hist_ind]);
		case CTRL_K_KEY:
			clear_line(ind, len);
			memset(input_buf + ind, 0, len - ind);
			print_str_by_index(input_buf, 0, ind);
			break;
		case CTRL_N_KEY:
			ungetc(DOWN_KEY, stdin);
			ungetc(CTRL2_KEY, stdin);
			ungetc(CTRL1_KEY, stdin);
			break;
		case CTRL_R_KEY:
		case CTRL_S_KEY:
			res = find_command(input_buf, hist_ind,
				(c == CTRL_S_KEY));
			if (res != hist_ind) {
				hist_ind = res;
				memset(input_buf, 0, READ_BUF_SIZE);
				strcpy(input_buf, History[hist_ind]);
			};
			print_str_by_index(Title, 0, -1);
			ind = print_str_by_index(input_buf, 0, -1);
			break;
		case CTRL1_KEY:
			c = getchar();
			if (c != CTRL2_KEY) break;
			c = getchar();
			switch (c) {
			case INSERT_KEY:
				getchar();
				is_insert_key = (is_insert_key) ? 0 : 1;
				break;
			case DELETE_KEY:
				getchar();
				if (ind == len) break;
				ind = delete_char(input_buf, len, ind, 1);
				break;
			case LEFT_KEY:
				printf("%c", '\b');
				ind--;
				if (ind < 0) {
					ind = 0;
					printf("%c", ' ');
				};
				break;
			case RIGHT_KEY:
				ind++;
				if (ind > len) ind = len;
				else print_str_by_index(input_buf, ind - 1, ind);
				break;
			case UP_KEY:
			case DOWN_KEY:
				clear_line(ind, len);
				if (c == UP_KEY)
					str = get_history_prev(input_buf);
				else
					str = get_history_next(input_buf);
				memset(input_buf, 0, READ_BUF_SIZE);
				strcpy(input_buf, str);
				len = strlen(input_buf);
				ind = print_str_by_index(input_buf, 0, len);
				break;
			case PGUP_KEY:
			case PGDOWN_KEY:
				getchar();
				add_to_history(input_buf, hist_ind);
				clear_line(ind, len);
				hist_ind = (c == PGUP_KEY) ? 0 : current_hist_ind;
				str = History[hist_ind];
				memset(input_buf, 0, READ_BUF_SIZE);
				strcpy(input_buf, str);
				len = strlen(input_buf);
				ind = print_str_by_index(input_buf, 0, len);
				break;
			case HOME_KEY:
				go_to_begin(ind);
				ind = print_str_by_index(input_buf, 0, 0);
				break;
			case END_KEY:
				ind = print_str_by_index(input_buf, ind, len);
				break;
			};
			break;
		case CTRL_H_KEY:
		case BACKSP_KEY:
			ind = (ind <= 0) ? 0 : delete_char(input_buf, len, ind, 0);
			break;
		default:
			if (ind == len) {
				input_buf[ind++] = c;
				printf("%c", c);
				break;
			};
			ind = add_char(input_buf, len, c, ind);
			break;
		};
		if (ind >= (READ_BUF_SIZE - 1)) {
			if (current_hist_ind != hist_ind)
				add_to_history(input_buf, hist_ind);
			add_to_history(input_buf, current_hist_ind);
			return(History[current_hist_ind]);
		}
	};
	return((char *)NULL);
}
Пример #13
0
/*
 * Prompt for input and read a line.
 * If  CONFIG_BOOT_RETRY_TIME is defined and retry_time >= 0,
 * time out when time goes past endtime (timebase time in ticks).
 * Return:	number of read characters
 *		-1 if break
 *		-2 if timed out
 */
int readline(const char * const prompt){
	char *p = console_buffer;
	int n = 0; /* buffer index		*/
	int plen = 0; /* prompt length	*/
	int col; /* output column cnt	*/
	char c;

	/* print prompt */
	if(prompt){
		plen = strlen(prompt);
		puts(prompt);
	}
	col = plen;

	for(;;){
		c = getc();

		/*
		 * Special character handling
		 */
		switch(c){
			case '\r': /* Enter		*/
			case '\n':
				*p = '\0';
				puts("\r\n");
				return(p - console_buffer);

			case '\0': /* nul			*/
				continue;

			case 0x03: /* ^C - break		*/
				console_buffer[0] = '\0'; /* discard input */
				return(-1);

			case 0x15: /* ^U - erase line	*/
				while(col > plen){
					puts(erase_seq);
					--col;
				}
				p = console_buffer;
				n = 0;
				continue;

			case 0x17: /* ^W - erase word 	*/
				p = delete_char(console_buffer, p, &col, &n, plen);
				while((n > 0) && (*p != ' ')){
					p = delete_char(console_buffer, p, &col, &n, plen);
				}
				continue;

			case 0x08: /* ^H  - backspace	*/
			case 0x7F: /* DEL - backspace	*/
				p = delete_char(console_buffer, p, &col, &n, plen);
				continue;

			default:
				/*
				 * Must be a normal character then
				 */
				if(n < CFG_CBSIZE - 2){
					if(c == '\t'){ /* expand TABs		*/
						puts(tab_seq + (col & 07));
						col += 8 - (col & 07);
					} else {
						++col; /* echo input		*/
						putc(c);
					}
					*p++ = c;
					++n;
				} else { /* Buffer full		*/
					putc('\a');
				}
		}
	}
}
Пример #14
0
/**
 *  @brief Volume control from the Menu.
 *
 *    This function uses the Alsa API to get and set
 *    the volume for the master channel.
 *    The use inputs a two digit number to set the volume,
 *    or presses the 'F' and 'B' buttons to adjust the
 *    value incrementally.
 *
 *    The volume control behaves differently from the menu,
 *    so menu flag is set to FALSE.
 *
 *  @param Void.
 *  @return Void.
 */
void volume(void){
  static long output = 50;
  int count = 0;

  char button_read = FALSE;  // Local snapshot of Global 'Button'
  int state_read = SUBMENU_SELECT;

  get_volume(&output);
  display_volume(output);
  set_menu(FALSE);

  while(alive && state_read == SUBMENU_SELECT){

    if(count == 0){
      display_volume(output);
    }

    pthread_mutex_lock(&button_Mutex);
    pthread_cond_wait(&button_Signal, &button_Mutex); // Wait for press
    button_read = button;               // Read the button pressed
    pthread_mutex_unlock(&button_Mutex);

    get_volume(&output);
    if(count == 0){
      display_volume(output);
    }

    pthread_mutex_lock(&state_Mutex);
    state_read = state;
    pthread_mutex_unlock(&state_Mutex);
    if(state_read == EMERGENCY || alive == FALSE){
      set_menu(FALSE); // in display.c
      break; // Get out if there's an emergency
    }

/* Button has been pressed. Now what? */
    switch(button_read){
      case '0':
      case '1':
      case '2':
      case '3':
      case '4':
      case '5':
      case '6':
      case '7':
      case '8':
      case '9':
        if(count == 0){
          reset_buffers();
        }
        if(++count <= 2){
          insert_char(button_read);
        }
        if(count == 2){
          output = (long)atoi(input_buffer);
          SetAlsaVolume(output);
          reset_buffers();
          count = 0;
        }
        break;

      case 'D':
        if(count){
          count--;
          delete_char();
        }
        break;

      case 'B': // Down
        if(--output >= 0){
          SetAlsaVolume(output);
          printd("output: %lu\n",output);
        }
        else{
          output = 0;
          printd("output: MIN\n");
        }
        break;
      case 'F': // Up
        if(++output < 100){
          SetAlsaVolume(output);
          printd("output: %lu\n",output);
        }
        else{
          output = 99;
          printd("output: MAX\n");
        }
        break;

     /* Accept, Cancel or Enter
      * The ACE case ;)
      */
      case 'A':
      case 'C':
      case 'E':
        pthread_mutex_lock(&state_Mutex);
        reset_buffers();
        state = MENU_SELECT; // Go back to menu
        state_read = state;
        pthread_mutex_unlock(&state_Mutex);
        set_menu(TRUE);
        break;
      default:
        break;
    }
  }
  return;
}
Пример #15
0
void
dialog(XEvent *event, KeySym keysym, char *buffer)
{
    InputItem *item;

    item = gWindow->page->current_item;
    if (item == 0) {
        if (!((keysym >= XK_Shift_L) && (keysym <= XK_Hyper_R)))
            /** if something other than a modifier key was hit **/
            BeepAtTheUser();
        return;
    }


    /*
     * First check if the user had hit an enter key
     */

    if ((keysym == XK_Return) || (keysym == XK_KP_Enter))
        enter_new_line(item);
    /*
     * Else did the user actual type a character I can understand
     */

    else if (((keysym >= XK_KP_Space) && (keysym <= XK_KP_9))
             || ((keysym >= XK_space) && (keysym <= XK_asciitilde)))
    {
        /* only handle normal keys */

        if (event->xkey.state & UnsupportedModMask)
            BeepAtTheUser();
        else
            add_buffer_to_sym(buffer, item);
    }

    else if ((keysym >= XK_Shift_L) && (keysym <= XK_Hyper_R))
        ;

    /*
     * do nothing, a modifier was hit
     */

    else if ((keysym >= XK_F2) && (keysym <= XK_F35)) {

        /*
         * A function key was hit
         */

        if (strlen(buffer) == 0)
            BeepAtTheUser();
        else
            /* If I got characters then add it to the buffer */

            add_buffer_to_sym(buffer, item);
    }
    else
        switch (keysym) {
          case XK_Escape:
            if (event->xkey.state & ModifiersMask)
                BeepAtTheUser();
            else {
                move_cursor_home(item);
                delete_rest_of_line(item);
            }
            break;
          case XK_F1:
            if (event->xkey.state & ModifiersMask)
                BeepAtTheUser();
            else {
                gWindow->page->helppage = alloc_string(InputAreaHelpPage);
                helpForHyperDoc();
            }
            break;
          case XK_Up:
            if (event->xkey.state & ModifiersMask)
                BeepAtTheUser();
            else
                move_cursor_up(item);
            break;
          case XK_Down:
            if (event->xkey.state & ModifiersMask)
                BeepAtTheUser();
            else
                move_cursor_down(item);
            break;
          case XK_Delete:
            if (event->xkey.state & ModifiersMask)
                BeepAtTheUser();
            else
                delete_char(item);
            break;
          case XK_BackSpace:
            if (event->xkey.state & ModifiersMask)
                BeepAtTheUser();
            else
                back_over_char(item);
            break;
          case XK_Left:
            if (event->xkey.state & ModifiersMask)
                BeepAtTheUser();
            else
                move_cursor_backward(item);
            break;
          case XK_Right:
            if (event->xkey.state & ModifiersMask)
                BeepAtTheUser();
            else
                move_cursor_forward(item);
            break;
          case XK_Insert:
            if (event->xkey.state & ModifiersMask)
                BeepAtTheUser();
            else {
                gInInsertMode = ((gInInsertMode) ? (0) : (1));
                item->curr_line->changed = 1;
                update_inputsymbol(item);
            }
            break;
          case XK_Home:
            if (event->xkey.state & ModifiersMask)
                BeepAtTheUser();
            else
                move_cursor_home(item);
            break;
          case XK_End:
            if (event->xkey.state & ControlMask)
                /* delete from here to the end of the line */

                delete_rest_of_line(item);
            else if (event->xkey.state & ModifiersMask)
                BeepAtTheUser();
            else
                move_cursor_end(item);
            break;
          default:
            BeepAtTheUser();
            break;
        }
}
Пример #16
0
Файл: CW.C Проект: kytulendu/TW
int main( int argc, char *argv[] ) {
	/* (x,y) position of edit window. x column, y line -> (0,0) at upper left on screen */
	unsigned int xCursorPos = 0;
	unsigned int yCursorPos = 0;

	unsigned int curmenu = 0x1100;
	int i;

	cwsetup( argc, argv );

	writestatus( 0 );
	writetab( );

	splashscreen( );

	/* Main program loop */
	do {
		dispstrhgc( "   ", wind.col, 2, NORMALATTR );
		i = pulled_down_menu( &curmenu, &xCursorPos, &yCursorPos );
		if ( filename[0] != '\0' ) {
			switch ( i ) {
			case RETKEY:
				keymain = menu_to_key( curmenu );
				break;

			case ESCKEY:
				waitkbd( wind.col + xCursorPos, wind.row + yCursorPos );		/* Show blinking cursor */
				keymain = readkbd( );		/* If keypressed Get it */
				break;

			default:
				keymain = i;
				break;
			}

			while ( keymain != ESCKEY ) {
				if ( ( keymain & 0xff ) >= 32 ) {
					keymain = changekey( keymain );
					if ( insertmode ) {
						if ( !insert_char( keymain, &xCursorPos, &yCursorPos ) ) {
							linetoolong( );
						}
					} else {
						if ( !ovrwrite_char( keymain, &xCursorPos, &yCursorPos ) ) {
							linetoolong( );
						}
					}
					refreshline( xCursorPos, yCursorPos );
				} else {	/*  Function Key  */
					switch ( keymain ) {
					case PGUPKEY:
					case CNTRL_R:
						page_up( );
						break;

					case PGDNKEY:
					case CNTRL_C:
						page_down( );
						break;

					case UPKEY:
					case CNTRL_E:
						cursor_up( );
						break;

					case DNKEY:
					case CNTRL_X:
						cursor_down( yCursorPos );
						break;

					case LEKEY:
					case CNTRL_S:
						cursor_left( &xCursorPos );
						break;

					case 0x2301:
						gobeginblk( &xCursorPos );
						break;

					case 0x2401:
						goendblk( &xCursorPos );
						break;

					case RIKEY:
					case CNTRL_D:
						cursor_right( &xCursorPos, yCursorPos );
						break;

					case CNTRL_W:
						scroll_up( );
						break;

					case CNTRL_Z:
						scroll_down( );
						break;

					case CHOMEKEY:
						top_of_page( );
						break;

					case CPGUPKEY:
						topfile( &xCursorPos );
						break;

					case CENDKEY:
						bottom_of_page( );
						break;

					case CPGDNKEY:
						endfile( &xCursorPos );
						break;

					case DELKEY:
					case CNTRL_G:
						delete_char( xCursorPos );
						refreshline( xCursorPos, yCursorPos );
						changeflag = YES;
						break;

					case CNTRL_T:
						delete_word( xCursorPos );
						refreshline( xCursorPos, yCursorPos );
						changeflag = YES;
						break;

					case CNTRL_Y:
						delete_line( );
						changeflag = YES;
						break;

					case CNTRL_M:
					case RETKEY:
						if ( insertmode == NO ) {
							returnkey( &xCursorPos, yCursorPos );
						} else {
							ret_with_ins( &xCursorPos, yCursorPos );
							changeflag = YES;
						}
						break;

					case BSKEY:
					case CNTRL_H:
						backspace( &xCursorPos );
						yCursorPos = findrow( );
						refreshline( 0, yCursorPos );
						changeflag = YES;
						break;

					case INSKEY:
					case CNTRL_V:
						insertmode = !insertmode;
						writeinsmode( );
						break;

					case CNTRL_N:
						insert_ret( &xCursorPos );
						break;

					case F10KEY:
						thaimode = !thaimode;
						writelanguage( );
						break;

					case F1KEY:
						fontused = 0x00;
						writeattr( );
						break;

					case F2KEY:
						fontused = fontused | ITALICATTR;
						writeattr( );
						break;

					case F3KEY:
						fontused = fontused | ONELINEATTR;
						fontused = fontused & 0x7f;
						writeattr( );
						break;

					case F4KEY:
						fontused = fontused | TWOLINEATTR;
						fontused = fontused & 0xfe;
						writeattr( );
						break;

					case F5KEY:
						fontused = fontused | BOLDATTR;
						writeattr( );
						break;

					case F6KEY:
						fontused = fontused | ENLARGEATTR;
						writeattr( );
						break;

					case F7KEY:
						fontused = fontused | SUPERATTR;
						if ( ( fontused & SUBATTR ) == SUBATTR ) {
							fontused = fontused ^ SUBATTR;
						}
						writeattr( );
						break;

					case F8KEY:
						fontused = fontused | SUBATTR;
						if ( ( fontused & SUPERATTR ) == SUPERATTR ) {
							fontused = fontused ^ SUPERATTR;
						}
						writeattr( );
						break;

					case F9KEY:
						manualwrap( &xCursorPos, &yCursorPos );
						break;

					case ALTM:
						editmacro( );
						break;

					case TABKEY:
					case CNTRL_I:
						movetotab( &xCursorPos, yCursorPos );
						break;

					case CNTRL_K:
						blockcommand( &xCursorPos );
						break;

					case 0x1401:
						blkcmd( 'p', &xCursorPos );
						break;
					case 0x6101:
						blkcmd( 'b', &xCursorPos );
						break;
					case 0x6201:
						blkcmd( 'k', &xCursorPos );
						break;
					case 0x6301:
						blkcmd( 'c', &xCursorPos );
						break;
					case 0x6401:
						blkcmd( 'y', &xCursorPos );
						break;
					case 0x6501:
						blkcmd( 'v', &xCursorPos );
						break;
					case 0x6601:
						blkcmd( 'r', &xCursorPos );
						break;
					case 0x6701:
						blkcmd( 'w', &xCursorPos );
						break;
					case 0x6801:
						blkcmd( 'h', &xCursorPos );
						break;

					case CNTRL_O:
						onscreen( xCursorPos, yCursorPos );
						break;

					case 0x7101:
						doonscrn( 'l', xCursorPos, yCursorPos );
						break;
					case 0x7201:
						doonscrn( 'r', xCursorPos, yCursorPos );
						break;
					case 0x7301:
						doonscrn( 'i', xCursorPos, yCursorPos );
						break;
					case 0x7401:
						doonscrn( 'n', xCursorPos, yCursorPos );
						break;
					case 0x7501:
						doonscrn( 'c', xCursorPos, yCursorPos );
						break;
					case 0x7601:
						doonscrn( 'p', xCursorPos, yCursorPos );
						break;
					case 0x7701:
						doonscrn( 'x', xCursorPos, yCursorPos );
						break;

					case CNTRL_Q:
						quick( &xCursorPos, &yCursorPos );
						break;

					case 0x3501:
						deltoendline( xCursorPos, yCursorPos );
						break;

					case 0x8111:
						inscntrl( CNTRL_W, xCursorPos, yCursorPos );
						break;
					case 0x8211:
						inscntrl( CNTRL_S, xCursorPos, yCursorPos );
						break;
					case 0x8311:
						inscntrl( CNTRL_R, xCursorPos, yCursorPos );
						break;
					case 0x8411:
						inscntrl( CNTRL_B, xCursorPos, yCursorPos );
						break;
					case 0x8511:
						inscntrl( CNTRL_E, xCursorPos, yCursorPos );
						break;
					case 0x8611:
						inscntrl( CNTRL_T, xCursorPos, yCursorPos );
						break;
					case 0x8711:
						inscntrl( CNTRL_V, xCursorPos, yCursorPos );
						break;

					case CNTRL_P:
						printcntrl( xCursorPos, yCursorPos );
						break;

					case HOMEKEY:
						home( &xCursorPos );
						break;

					case ENDKEY:
						endline( &xCursorPos );
						break;

					case CLEKEY:
					case CNTRL_A:
						backword( &xCursorPos );
						break;

					case CRIKEY:
					case CNTRL_F:
						nextword( &xCursorPos, yCursorPos );
						break;

					case CNTRL_L:
						if ( source[0] != '\0' ) {
							if ( replaceflag == NO ) {
								if ( searchfwd( &xCursorPos, &yCursorPos ) == NO ) {
									wordnotfound( );
								}
							} else {
								if ( searchreplace( &xCursorPos, &yCursorPos ) == NO ) {
									wordnotfound( );
								}
							}
						}
						break;

					case CNTRL_B:
						reform( );
						break;

					case ALTP:
						gotopage( );
						break;

					case CNTRL_J:
					case ALTL:
						gotoline( );
						break;

					case 0x5101:
						searching( &xCursorPos, &yCursorPos );
						break;

					case 0x5201:
						replacing( &xCursorPos, &yCursorPos );
						break;

					case 0x8501:
						loadtoline( curline->text );
						refreshline( 0, yCursorPos );
						break;

					case CF1KEY:
						insertmacro( &macro[0][0], &xCursorPos, &yCursorPos );
						break;
					case CF2KEY:
						insertmacro( &macro[1][0], &xCursorPos, &yCursorPos );
						break;
					case CF3KEY:
						insertmacro( &macro[2][0], &xCursorPos, &yCursorPos );
						break;
					case CF4KEY:
						insertmacro( &macro[3][0], &xCursorPos, &yCursorPos );
						break;
					case CF5KEY:
						insertmacro( &macro[4][0], &xCursorPos, &yCursorPos );
						break;
					case CF6KEY:
						insertmacro( &macro[5][0], &xCursorPos, &yCursorPos );
						break;
					case CF7KEY:
						insertmacro( &macro[6][0], &xCursorPos, &yCursorPos );
						break;
					case CF8KEY:
						insertmacro( &macro[7][0], &xCursorPos, &yCursorPos );
						break;
					case CF9KEY:
						insertmacro( &macro[8][0], &xCursorPos, &yCursorPos );
						break;
					case CF10KEY:
						insertmacro( &macro[9][0], &xCursorPos, &yCursorPos );
						break;

					case AF2KEY:
						inscntrl( ITALICCODE, xCursorPos, yCursorPos );
						break;
					case AF3KEY:
						inscntrl( ONELINECODE, xCursorPos, yCursorPos );
						break;
					case AF4KEY:
						inscntrl( TWOLINECODE, xCursorPos, yCursorPos );
						break;
					case AF5KEY:
						inscntrl( BOLDCODE, xCursorPos, yCursorPos );
						break;
					case AF6KEY:
						inscntrl( ENLARGECODE, xCursorPos, yCursorPos );
						break;
					case AF7KEY:
						inscntrl( SUPERCODE, xCursorPos, yCursorPos );
						break;
					case AF8KEY:
						inscntrl( SUBCODE, xCursorPos, yCursorPos );
						break;

#ifdef WANT_TO_USE_GRAPH
					case ALTG:
						insertgraph( );
						break;
					case ALTD:
						deletegraph( );
						break;
#endif

					case ALTX:
						quitprog = YES;
						keymain = ESCKEY;
						break;

					default:
						if ( ( alt_char_map( keymain ) ) != -1 ) {
							keymain = alt_char_map( keymain );
							if ( insertmode ) {
								if ( !insert_char( keymain, &xCursorPos, &yCursorPos ) ) {
									linetoolong( );
								}
							} else {
								if ( !ovrwrite_char( keymain, &xCursorPos, &yCursorPos ) ) {
									linetoolong( );
								}
							}
							refreshline( xCursorPos, yCursorPos );
						}
						break;
					} /* switch ( keymain ) */
				}
				adjustcol( &xCursorPos );
				while ( ( yCursorPos = findrow( ) ) > ( wind.width - 1 ) ) {
					storeline( curline );
					curline = curline->previous;
					loadtoline( curline->text );
					lineno--;
				}
				if ( !keypressed( ) ) {
					if ( !pagecomplete ) {
						showpage( );
					}
					if ( !keypressed( ) ) {
						writecolno( firstcol + xCursorPos );
						dispstrhgc( "   ", wind.col, 2, NORMALATTR );
						if ( !keypressed( ) ) {
							writepageline( );
						}
					}
				}
				if ( quitprog != YES ) {
					waitkbd( wind.col + xCursorPos, wind.row + yCursorPos );
					keymain = readkbd( );
					dispkey( keymain );
				}
			}	/* while */
		} else {	/* if filename[0] != '\0' */
			errorsound( );
		}
	} while ( !quitprog );

	if ( changeflag ) {

		blockmsg( 5 );
		dispstrhgc( "ÂѧäÁèä´é¨Ñ´à¡çºá¿éÁ¢éÍÁÙÅ µéͧ¡ÒèѴà¡çºËÃ×ÍäÁè (Y/N)?", ( 16 + center_factor ) + 7, 5, REVERSEATTR );

		keymain = 0;
		while ( ( keymain != 'n' ) && ( keymain != 'N' )
			&& ( keymain != 'y' ) && ( keymain != 'Y' ) ) {
			keymain = ebioskey( 0 ) & 0xff;
			if ( ( keymain == 'y' ) || ( keymain == 'Y' ) ) {
				writeblk( filename, sentinel->next, 0, sentinel->previous, MAXCOL );
			}
		}
	}
	settext( );

	return 0;
}
Пример #17
0
int vedit(const char *filename, const char *saveheader, char *bname)
{
	int ch, foo;
	int lastcharindent = -1;
	BOOL firstkey = TRUE;
	char bakfile[PATHLEN];
	int old_rows = t_lines, old_columns = t_columns;

	sethomefile(bakfile, curuser.userid, UFNAME_EDIT);

	if ((saveheader || uinfo.mode == EDITPLAN || uinfo.mode == EDITBMWEL)
	    && isfile(bakfile)	/* lthuang */
#ifdef GUEST
	 && strcmp(curuser.userid, GUEST)
#endif
	 )
	{
		clear();
		outs(_msg_edit_8);
		if (getkey() != '2')
			mycp(bakfile, filename);
	}
	if (!isfile(filename))
		unlink(bakfile);
	if (saveheader)
		do_article_sig(filename);

	read_file(filename);

	top_of_win = firstline;
	currline = firstline;
	curr_window_line = 0;
	currpnt = 0;

	ansi_mode = FALSE;

	clear();
	display_buffer();

	move(curr_window_line, currpnt);
	while ((ch = getkey()) != EOF)
	{
		if (firstkey)
		{
			firstkey = FALSE;
			show_help_msg();
		}
		if (talkrequest)	/* lthuang */
		{
			backup_file(bakfile);
			talkreply();
			pressreturn();
			ch = CTRL('G');		/* redraw screen */
		}
		else if (msqrequest)	/* lthuang */
		{
			msqrequest = FALSE;
			msq_reply();
#if 0
			ch = CTRL('G');
#endif
		}
		if (old_rows != t_lines || old_columns != t_columns)
		{
			static const char *msg_resized = "螢幕大小已改變, 按(Ctrl-G)回到頁首!";

			old_rows = t_lines;
			old_columns = t_columns;

			top_of_win = firstline;
			currline = top_of_win;
			curr_window_line = 0;
			currpnt = 0;
			shift = 0;
			redraw_everything = TRUE;
			move(t_lines / 2, (t_columns - strlen(msg_resized)) / 2);
			outs(msg_resized);
			while (getkey() != CTRL('G'));
		}
		else if (ch < 0x100 && isprint2(ch))
		{
			insert_char(ch);
			lastcharindent = -1;
		}
		else
			switch (ch)
			{
			case KEY_UP:
				if (lastcharindent == -1)
					lastcharindent = currpnt;
				if (!currline->prev)
				{
					bell();
					break;
				}
				curr_window_line--;
				currline = currline->prev;
				currpnt = (currline->len > lastcharindent) ? lastcharindent : currline->len;
				break;
			case KEY_DOWN:
				if (lastcharindent == -1)
					lastcharindent = currpnt;
				if (!currline->next)
				{
					bell();
					break;
				}
				curr_window_line++;
				currline = currline->next;
				currpnt = (currline->len > lastcharindent) ? lastcharindent : currline->len;
				break;
			default:
				lastcharindent = -1;
				switch (ch)
				{
				case CTRL('T'):
					top_of_win = back_line(lastline, b_lines - 2);
					currline = lastline;
					curr_window_line = getlineno();
					currpnt = 0;
					redraw_everything = TRUE;
					break;
				case CTRL('S'):
					top_of_win = firstline;
					currline = top_of_win;
					curr_window_line = 0;
					currpnt = 0;
					redraw_everything = TRUE;
					break;
				case '\t':
					do
					{
						insert_char(' ');
					}
					while (currpnt & 0x7);
					break;
				case CTRL('U'):
				case CTRL('V'):
					insert_char(0x1b);
					break;
				case CTRL('C'):
					insert_char(0x1b);
					insert_char('[');
					insert_char('m');
					break;
				case KEY_RIGHT:
				case CTRL('F'):
					if (currline->len == currpnt)
					{
						if (!currline->next)
							bell();
						else
						{
							currpnt = 0;
							curr_window_line++;
							currline = currline->next;
						}
					}
					else
						currpnt++;
					break;
				case KEY_LEFT:
				case CTRL('B'):
					if (currpnt == 0)
					{
						if (!currline->prev)
							bell();
						else
						{
							currline = currline->prev;
							currpnt = currline->len;
							curr_window_line--;
						}
					}
					else
						currpnt--;
					break;
				case CTRL('G'):
					clear();
					redraw_everything = TRUE;
					break;
				case CTRL('Z'):
					vedit_help();
					break;
				case KEY_PGUP:
				case CTRL('P'):
					top_of_win = back_line(top_of_win, b_lines - 2);
					currline = top_of_win;
					currpnt = 0;
					curr_window_line = 0;
					redraw_everything = TRUE;
					break;
				case KEY_PGDN:
				case CTRL('N'):
					top_of_win = forward_line(top_of_win, b_lines - 2);
					currline = top_of_win;
					currpnt = 0;
					curr_window_line = 0;
					redraw_everything = TRUE;
					break;
				case KEY_HOME:
				case CTRL('A'):
					currpnt = 0;
					break;
				case KEY_END:
				case CTRL('E'):
					currpnt = currline->len;
					break;
				case CTRL('R'):
#if 0
					backup_file(bakfile);
#endif
					msq_reply();
#if 0
					redraw_everything = TRUE;	/* lthuang */
#endif
					break;
				case CTRL('Q'):
					ansi_mode = TRUE;
					display_buffer();
					pressreturn();
					ansi_mode = FALSE;
					display_buffer();
					break;
				case CTRL('X'):
				case CTRL('W'):
					backup_file(bakfile);
					clear();
					foo = write_file(filename, saveheader, bname);
					if (foo == BACKUP_EDITING)
						return foo;
					else if (foo != KEEP_EDITING)
					{
						unlink(bakfile);
						return foo;
					}
					redraw_everything = TRUE;	/* lthuang */
					break;
				case '\r':
				case '\n':
					split(currline, currpnt);
					/* lthuang: reduce the times of backup */
					if (total_num_of_line % 7 == 0)
						backup_file(bakfile);
					break;
				case '\177':
				case CTRL('H'):
					if (currpnt == 0)
					{
						if (!currline->prev)
						{
							bell();
							break;
						}
						curr_window_line--;
						currline = currline->prev;
						currpnt = currline->len;
						if (*killsp(currline->next->data) == '\0') {
							delete_line(currline->next);
							redraw_everything = TRUE;
						} else {
							join_currline();
						}
						if (curr_window_line == -1) {
							curr_window_line = 0;
							top_of_win = currline;
							rscroll();
						}
						break;
					}
					currpnt--;
					delete_char();
					break;
				case CTRL('D'):
					if (currline->len == currpnt)
						join_currline();
					else
						delete_char();
					break;
				case CTRL('Y'):
					currpnt = 0;
					currline->len = 0;
					delete_currline();
					break;
				case CTRL('K'):
					if (currline->len == 0)
						delete_currline();
					else if (currline->len == currpnt)
						join_currline();
					else
					{
						currline->len = currpnt;
						currline->data[currpnt] = '\0';
					}
					break;
				default:
					break;
				}
				break;
			}
		if (curr_window_line == -1)
		{
			curr_window_line = 0;
			if (!top_of_win->prev)
			{
				indigestion(6);
				bell();
			}
			else
			{
				top_of_win = top_of_win->prev;
				rscroll();
			}
		}
		if (curr_window_line == t_lines - 1)
		{
			curr_window_line = t_lines - 2;
			if (!top_of_win->next)
			{
				indigestion(7);
				bell();
			}
			else
			{
				top_of_win = top_of_win->next;
				scroll();
			}
		}

		/* lthuang: 99/07 */
		if (currpnt - shift >= t_columns - 1)
		{
			shift = (currpnt / (t_columns - 1)) * (t_columns - 1) - 1;
			redraw_everything = TRUE;
		}
		else if (currpnt - shift < 0)
		{
			shift = 0;
			redraw_everything = TRUE;
		}

		if (redraw_everything)
		{
			display_buffer();
			redraw_everything = FALSE;
		}
		else
		{
			move(curr_window_line, 0);
			clrtoeol();	/* lthuang */
			vedit_outs(currline->data);
		}

		move(curr_window_line, currpnt - shift);	/* lthuang: 99/07 */
	}
	if (uinfo.mode == POSTING || uinfo.mode == SMAIL)
		unlink(filename);
	return ABORT_EDITING;
}
Пример #18
0
int ubreadline_into_buffer(const char *const prompt, char *buffer, int timeout)
{
	char *p = buffer;
	unsigned int len = CONFIG_SYS_CBSIZE;
	int rc;
	static int initted = 0;

	/*
	 * History uses a global array which is not
	 * writable until after relocation to RAM.
	 * Revert to non-history version if still
	 * running from flash.
	 */
	if (0) {
		if (!initted) {
			hist_init();
			initted = 1;
		}

		if (prompt)
			printf (prompt);

		rc = cread_line(prompt, p, &len, timeout);
		return rc < 0 ? rc : len;

	} else {
	char * p_buf = p;
	int	n = 0;				/* buffer index		*/
	int	plen = 0;			/* prompt length	*/
	int	col;				/* output column cnt	*/
	char	c;

	/* print prompt */
	if (prompt) {
		plen = strlen (prompt);
		printf (prompt);
	}
	col = plen;

	for (;;) {

		c = serial_getchar();

		/*
		 * Special character handling
		 */
		switch (c) {
		case '\r':			/* Enter		*/
		case '\n':
			*p = '\0';
			printf ("\r\n");
			return p - p_buf;

		case '\0':			/* nul			*/
			continue;

		case 0x03:			/* ^C - break		*/
			p_buf[0] = '\0';	/* discard input */
			return -1;

		case 0x15:			/* ^U - erase line	*/
			while (col > plen) {
				printf (erase_seq);
				--col;
			}
			p = p_buf;
			n = 0;
			continue;

		case 0x17:			/* ^W - erase word	*/
			p=delete_char(p_buf, p, &col, &n, plen);
			while ((n > 0) && (*p != ' ')) {
				p=delete_char(p_buf, p, &col, &n, plen);
			}
			continue;

		case 0x08:			/* ^H  - backspace	*/
		case 0x7F:			/* DEL - backspace	*/
			p=delete_char(p_buf, p, &col, &n, plen);
			continue;

		default:
			/*
			 * Must be a normal character then
			 */
			if (n < CONFIG_SYS_CBSIZE-2) {
				if (c == '\t') {	/* expand TABs */
					/* if auto completion triggered just continue */
					*p = '\0';
					if (cmd_auto_complete(prompt, console_buffer, &n, &col)) {
						p = p_buf + n;	/* reset */
						continue;
					}
					printf (tab_seq+(col&07));
					col += 8 - (col&07);
				} else {
					char buf[2];

					/*
					 * Echo input using printf() to force an
					 * LCD flush if we are using an LCD
					 */
					++col;
					buf[0] = c;
					buf[1] = '\0';
					printf(buf);
				}
				*p++ = c;
				++n;
			} else {			/* Buffer full		*/
				serial_putchar('\a');
			}
		}
	}
	}
}
Пример #19
0
int main(int argc, char **argv) {
    to_send = (message *)malloc(sizeof(message)); // message struct to talk to server with
    message *received = (message *)malloc(sizeof(message));
    client *me = (client *)malloc(sizeof(client)); // ME!
    tbuf B = 0;
    char welcome_msg[100];

    signal(SIGINT, sigint_handler);

    // handle command line args
    int i;
    if (argc > 0) {
        for (i = 0 ; i < argc ; i++) {
            if (*argv[i] == '-') {
                switch(*(argv[i] + 1)) {
                    case 'n':
                        strncpy(NAME, argv[++i], sizeof(NAME));
                        break;

                    case 'h':
                        printf("%s\n", HELP);
                        exit(1);
                        break;

                    case 'l': // local use
                        CONN = 0;
                        me->room_id = 0;
                        break;

                    case 'j': // not creating a room, but joining
                        ROOM_NO = atoi(argv[++i]);
                        break;

                    case 't':
                        DEBUG = 1;
                        break;
                }
            }

            else if(i > 0) {
                strncpy(filename, argv[i], sizeof(filename));
                B = read_from_file(argv[i]);
                debug("reading done (%s)\n", argv[i]);
            }
        }
    }

    if (!NAME[0] && CONN) { // name is not set yet and connecting to network
        printf("%s\n", HELP);
        exit(1);
    }
    
    if (!B) {

        B = new_tbuf();
        printf("is this it?\n");

    }


    // build socket connection
    if (CONN) {
        if ((FROM_SERVER = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
            fprintf(stderr, "Fatal - Cannot create socket\n");
            close(1);
        }

        serv_addr.sin_family = AF_INET;
        serv_addr.sin_port = htons(CLIENT_PORT);
        serv_addr.sin_addr.s_addr = inet_addr(SERVER_ADDR);

        if (connect(FROM_SERVER, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
            fprintf(stderr, "Fatal - Connection to server failed\n");
            close(1);
        }

        // setup terminal args and handshake with server
        // 1. join server request
        strncpy(to_send->cmd, CONN_REQUEST, sizeof(CONN_REQUEST));
        strncpy(to_send->content, NAME, sizeof(NAME));
        debug("Name sent to server: %s\n", to_send->content);
        write(FROM_SERVER, to_send, sizeof(message));
        read(FROM_SERVER, &to_send->remote_client_id, sizeof(int));
        debug("Received from server: %d\n", to_send->remote_client_id);

        // let us assume that you are creating a room here
        
        if (ROOM_NO != -1) { // join a given room
            me->room = ROOM_NO;
            strncpy(to_send->cmd, "join", 5);
            to_send->to_distribute = 1;
            sprintf(to_send->content, "%d", ROOM_NO);
            debug("command sent: %s\n", to_send->cmd);
            send_to_server(to_send, sizeof(message));
            room_state *current_room = (room_state *)malloc(sizeof(room_state));
            read(FROM_SERVER, current_room, sizeof(room_state));
            B = chararr2tbuf(current_room->buf);
            memcpy(usernames, current_room->usernames, sizeof(usernames));
            read(FROM_SERVER, &me->room_id, sizeof(int));
            to_send->local_client_id = me->room_id;
            strncpy(usernames[me->room_id], NAME, sizeof(NAME));
            sprintf(welcome_msg, "<SERVER> You have just joined room %d", me->room);
        }
        else { // create a room
            strncpy(to_send->cmd, "new", 4);
            debug("command sent: %s\n", to_send->cmd);
            send_to_server(to_send, sizeof(message));
            read(FROM_SERVER, &ROOM_NO, sizeof(int));
            to_send->local_client_id = 0; // create a room = 0
            me->room = ROOM_NO;
            me->room_id = 0;
            strncpy(usernames[me->room_id], NAME, sizeof(NAME));
            debug("recv from server: in room %d\n", me->room);
            sprintf(welcome_msg, "<SERVER> You are now the owner of %d", me->room);
        }
        to_send->to_distribute = 1;
    }
    else {
        sprintf(welcome_msg, "You are currently running NetScribe locally");
    }


    //getchar();

    // setup GUI
    WINDOW *mainwin = initscr();
    cbreak();
    noecho();
    keypad(mainwin, true);
    int vis = curs_set(0);

    int ncols = getmaxx(mainwin);
    int nlines = getmaxy(mainwin);
    int begx = getbegx(mainwin);
    int begy = getbegy(mainwin);

    debug("%d, %d, %d, %d\n", ncols, nlines, begx, begy);

    WINDOW *canvas = subwin(mainwin,
                            nlines - 4, // save 2 lines for bottom status
                            ncols, // same as main
                            begy + 2, // save one line for title and one line for 'chat'
                            begx);

    WINDOW *topbar = subwin(mainwin, 1, ncols, begy, begx);
    WINDOW *chatbar = subwin(mainwin, 1, ncols, begy + 1, begx);
    WINDOW *botbar = subwin(mainwin, 1, ncols, nlines - 2, begx);
    WINDOW *inputbar = subwin(mainwin, 1, ncols, nlines - 1, begx);

    render_topbar(topbar);
    render_string(chatbar, welcome_msg);
    render_botbar(botbar);
    wrefresh(mainwin);

    debug("setup done\n");

    // setup the select program
    char c[3];
    fd_set readfds, current;

    FD_ZERO(&readfds);
    FD_ZERO(&current);

    FD_SET(STDIN_FILENO, &readfds);

    if (CONN) {
        FD_SET(FROM_SERVER, &readfds);
    }

    while (1) {
        if (!DEBUG) {
            render_tbuf(B, canvas); // FIXME OVERWRITING STUFF
        }

        current = readfds;

        debug("BEFORE SELECT\n");

        if (select(FROM_SERVER + 1, &current, NULL, NULL, NULL) < 0) {
            fprintf(stderr, "Error %d: %s", errno, strerror(errno));
        }

        debug("HELLO!\n");

        if (FD_ISSET(FROM_SERVER, &current)) { // receive msg from server
            read(FROM_SERVER, received, sizeof(message));
            debug("MSG FROM SERVER: %s\n", received->cmd);
            int c_user = received->local_client_id;

            if (strstr(received->cmd, "chat")) { // this is a chat command
                time_t t;
                struct tm *tinfo;
                time(&t);
                tinfo = localtime(&t);
                char time_s[20];
                if (!strftime(time_s, sizeof(time_s), "%H:%M:%S", tinfo)) {
                    fprintf(stderr, "Error %d: %s", errno, strerror(errno));
                    exit(1);
                }
                char to_put_up[100];
                sprintf(to_put_up, "[%s] %s: %s", time_s,
                        usernames[received->local_client_id],
                        received->content);

                render_string(chatbar, to_put_up);
            }

            if (strstr(received->cmd, "join")) { // if new user joins
                debug("THIS IS A JOIN REQUEST\n");
                strncpy(usernames[received->local_client_id], received->content, 16);
                time_t t;
                struct tm *tinfo;
                time(&t);
                tinfo = localtime(&t);
                char time_s[20];
                if (!strftime(time_s, sizeof(time_s), "%H:%M:%S", tinfo)) {
                    fprintf(stderr, "Error %d: %s", errno, strerror(errno));
                    exit(1);
                }
                char to_put_up[100];
                sprintf(to_put_up, "[%s] <SERVER>: %s has joined", time_s,
                        usernames[received->local_client_id]);

                render_string(chatbar, to_put_up);
            }

            if (strstr(received->cmd, "exit")) { // if user exits
                time_t t;
                struct tm *tinfo;
                time(&t);
                tinfo = localtime(&t);
                char time_s[20];
                if (!strftime(time_s, sizeof(time_s), "%H:%M:%S", tinfo)) {
                    fprintf(stderr, "Error %d: %s", errno, strerror(errno));
                    exit(1);
                }
                char to_put_up[100];
                sprintf(to_put_up, "[%s] <SERVER>: %s has exited", time_s,
                        usernames[received->local_client_id]);

                render_string(chatbar, to_put_up);
                memset(usernames[received->local_client_id], 0, sizeof(usernames[received->local_client_id]));
            }

            if (strstr(received->cmd, SERVER_EXIT)) { // server died :(
                SERVER_DIED = 1;
                break;
            }

            if (strstr(received->cmd, BUF_REQUEST)) { // you are the owner and the server asked you for the buffer
                debug("HELLO I GOTCHU\n");
                //assert(me->room_id == 0); // i should be the owner
                room_state *current_state = (room_state *)malloc(sizeof(room_state));
                strncpy(current_state->buf, tbuf2chararr(B), 20480);
                memcpy(current_state->usernames, usernames, sizeof(usernames));
                debug("conversion done\n");
                write(FROM_SERVER, current_state, sizeof(room_state)); // only except to the RO rule
                debug("Wrote to server\n");
            }

            if (strstr(received->cmd, "edit")) {
                memcpy(c, received->content, sizeof(c));

                if (c[0] == 27) {
                    switch (c[2]) {
                        case 'C': // move cursor right
                            backward_char(B, c_user);
                            break;

                        case 'D':
                            forward_char(B, c_user);
                            break;
                    }
                }

                else if (c[0] == 127) { // backspace
                    delete_char(B, c_user);
                }

                else if (0 < c[0] && c[0] < 127) { // other characters
                    insert_char(B, c[0], c_user);
                }
            }
        }

        if (FD_ISSET(STDIN_FILENO, &current)) { // reading from stdin
            read(STDIN_FILENO, &c, 1);

            if (c[0] == 24) { // ^X --> exit
                break; // exit out of the listening loop
            }

            switch (mode) {
                case EDIT_MODE:
                    if (c[0] == 12) { // ^L --> redraw
                        wclear(mainwin);
                        render_topbar(topbar);
                        render_string(chatbar, "");
                        render_tbuf(B, canvas);
                        wrefresh(mainwin);
                    }

                    else if (c[0] == 15) { // ^O --> saving mode
                        mode = SAVE_MODE;
                    }

                    else if (c[0] == 8) { // ^H --> chat
                        mode = CHAT_MODE;
                        werase(inputbar);
                        wmove(inputbar, 0, 1);
                        waddstr(inputbar, "Chat (press enter to send): ");
                        wrefresh(inputbar);
                        msg_i = 0;
                    }

                    else { // these will be sent
                        strncpy(to_send->cmd, "edit", 5);

                        if (c[0] == 27) {
                            read(STDIN_FILENO, &c[1], 2);
                            switch (c[2]) {
                                case 'C': // move cursor right
                                    backward_char(B, me->room_id);
                                    break;

                                case 'D':
                                    forward_char(B, me->room_id);
                                    break;
                            }
                            memcpy(to_send->content, c, 3);
                        }

                        else if (c[0] == 127) { // backspace
                            delete_char(B, me->room_id);
                            memcpy(to_send->content, c, 3);
                        }

                        else if (0 < c[0] && c[0] < 127) { // other characters
                            printf("%c\n", c[0]);
                            insert_char(B, c[0], me->room_id);
                            memcpy(to_send->content, c, 3);
                        }

                        send_to_server(to_send, sizeof(message));
                    }

                    break;

                case CHAT_MODE: // when user is inputing things for the chat
                    if (c[0] == 13) { // enter
                        msg[msg_i] = 0; // null terminator
                        strncpy(to_send->cmd, "chat", 5);
                        strncpy(to_send->content, msg, sizeof(to_send->content));
                        send_to_server(to_send, sizeof(message));
                        werase(inputbar);
                        wrefresh(inputbar);
                        mode = EDIT_MODE;
                    }

                    else if (0 < c[0] && c[0] < 127) { // other chars
                        msg[msg_i] = c[0];
                        msg_i++;
                        waddch(inputbar, c[0]);
                        wrefresh(inputbar);
                    }
                    break;

                case SAVE_MODE: // when user is typing in the to-save filename
                    break;
            }
        }

    }

    if (CONN && !SERVER_DIED) { // send off closing request
        strncpy(to_send->cmd, "exit", 5);
        send_to_server(to_send, sizeof(message));
    }

    curs_set(vis);
    endwin();
    if (SERVER_DIED) {
        printf("The server has shutdown or the owner of the room has quit\n");
    }
    else {
        printf("Exiting...\n");
    }
    return 0;
}
Пример #20
0
void LineEdit::_input_event(InputEvent p_event) {


    switch(p_event.type) {

    case InputEvent::MOUSE_BUTTON: {

        const InputEventMouseButton &b = p_event.mouse_button;

        if (b.pressed && b.button_index==BUTTON_RIGHT) {
            menu->set_pos(get_global_transform().xform(get_local_mouse_pos()));
            menu->set_size(Vector2(1,1));
            menu->popup();
            grab_focus();
            return;
        }

        if (b.button_index!=BUTTON_LEFT)
            break;

        _reset_caret_blink_timer();
        if (b.pressed) {

            shift_selection_check_pre(b.mod.shift);

            set_cursor_at_pixel_pos(b.x);

            if (b.mod.shift) {

                selection_fill_at_cursor();
                selection.creating=true;

            } else {

                if (b.doubleclick) {

                    selection.enabled=true;
                    selection.begin=0;
                    selection.end=text.length();
                    selection.doubleclick=true;
                }

                selection.drag_attempt=false;

                if ((cursor_pos<selection.begin) || (cursor_pos>selection.end) || !selection.enabled)  {

                    selection_clear();
                    selection.cursor_start=cursor_pos;
                    selection.creating=true;
                } else if (selection.enabled) {

                    selection.drag_attempt=true;
                }
            }

            //			if (!editable)
            //	non_editable_clicked_signal.call();
            update();

        } else {

            if ( (!selection.creating) && (!selection.doubleclick)) {
                selection_clear();
            }
            selection.creating=false;
            selection.doubleclick=false;

            if (OS::get_singleton()->has_virtual_keyboard())
                OS::get_singleton()->show_virtual_keyboard(text,get_global_rect());
        }

        update();
    }
    break;
    case InputEvent::MOUSE_MOTION: {

        const InputEventMouseMotion& m=p_event.mouse_motion;

        if (m.button_mask&BUTTON_LEFT) {

            if (selection.creating) {
                set_cursor_at_pixel_pos(m.x);
                selection_fill_at_cursor();
            }
        }

    }
    break;
    case InputEvent::KEY: {

        const InputEventKey &k =p_event.key;

        if (!k.pressed)
            return;
        unsigned int code  = k.scancode;


        if (k.mod.command) {

            bool handled=true;

            switch (code) {

            case (KEY_X): { // CUT

                if(editable) {
                    cut_text();
                }

            }
            break;

            case (KEY_C): { // COPY

                copy_text();

            }
            break;

            case (KEY_V): { // PASTE

                if(editable) {

                    paste_text();
                }

            }
            break;

            case (KEY_Z): { // Simple One level undo

                if(editable) {

                    undo();

                }


            }
            break;

            case (KEY_U): { // Delete from start to cursor

                if(editable) {

                    selection_clear();
                    undo_text = text;
                    text = text.substr(cursor_pos,text.length()-cursor_pos);

                    Ref<Font> font = get_font("font");

                    cached_width = 0;
                    if (font != NULL) {
                        for (int i = 0; i < text.length(); i++)
                            cached_width += font->get_char_size(text[i]).width;
                    }

                    set_cursor_pos(0);
                    _text_changed();

                }


            }
            break;

            case (KEY_Y): { // PASTE (Yank for unix users)

                if(editable) {

                    paste_text();
                }

            }
            break;
            case (KEY_K): { // Delete from cursor_pos to end

                if(editable) {

                    selection_clear();
                    undo_text = text;
                    text = text.substr(0,cursor_pos);
                    _text_changed();
                }

            }
            break;
            case (KEY_A): { //Select All
                select();
            }
            break;
            default: {
                handled=false;
            }
            }

            if (handled) {
                accept_event();
                return;
            }
        }

        _reset_caret_blink_timer();
        if (!k.mod.meta) {

            bool handled=true;
            switch (code) {

            case KEY_ENTER:
            case KEY_RETURN: {

                emit_signal( "text_entered",text );
                if (OS::get_singleton()->has_virtual_keyboard())
                    OS::get_singleton()->hide_virtual_keyboard();

                return;
            }
            break;

            case KEY_BACKSPACE: {

                if (!editable)
                    break;

                if (selection.enabled) {
                    undo_text=text;
                    selection_delete();
                    break;
                }

#ifdef APPLE_STYLE_KEYS
                if (k.mod.alt) {
#else
                if (k.mod.alt) {
                    handled=false;
                    break;
                } else if (k.mod.command) {
#endif
                    int cc=cursor_pos;
                    bool prev_char=false;

                    while (cc>0) {
                        bool ischar=_is_text_char(text[cc-1]);

                        if (prev_char && !ischar)
                            break;

                        prev_char=ischar;
                        cc--;
                    }

                    delete_text(cc, cursor_pos);

                    set_cursor_pos(cc);

                } else {
                    undo_text=text;
                    delete_char();
                }

            }
            break;
            case KEY_KP_4: {
                if (k.unicode != 0) {
                    handled = false;
                    break;
                }
                // numlock disabled. fallthrough to key_left
            }
            case KEY_LEFT: {

#ifndef APPLE_STYLE_KEYS
                if (!k.mod.alt)
#endif
                    shift_selection_check_pre(k.mod.shift);

#ifdef APPLE_STYLE_KEYS
                if (k.mod.command) {
                    set_cursor_pos(0);
                } else if (k.mod.alt) {

#else
                if (k.mod.alt) {
                    handled=false;
                    break;
                } else if (k.mod.command) {
#endif
                    bool prev_char=false;
                    int cc=cursor_pos;

                    while (cc>0) {
                        bool ischar=_is_text_char(text[cc-1]);

                        if (prev_char && !ischar)
                            break;

                        prev_char=ischar;
                        cc--;
                    }

                    set_cursor_pos(cc);

                } else {
                    set_cursor_pos(get_cursor_pos()-1);
                }

                shift_selection_check_post(k.mod.shift);

            }
            break;
            case KEY_KP_6: {
                if (k.unicode != 0) {
                    handled = false;
                    break;
                }
                // numlock disabled. fallthrough to key_right
            }
            case KEY_RIGHT: {

                shift_selection_check_pre(k.mod.shift);

#ifdef APPLE_STYLE_KEYS
                if (k.mod.command) {
                    set_cursor_pos(text.length());
                } else if (k.mod.alt) {
#else
                if (k.mod.alt) {
                    handled=false;
                    break;
                } else if (k.mod.command) {
#endif
                    bool prev_char=false;
                    int cc=cursor_pos;

                    while (cc<text.length()) {
                        bool ischar=_is_text_char(text[cc]);

                        if (prev_char && !ischar)
                            break;

                        prev_char=ischar;
                        cc++;
                    }

                    set_cursor_pos(cc);

                } else {
                    set_cursor_pos(get_cursor_pos()+1);
                }

                shift_selection_check_post(k.mod.shift);

            }
            break;
            case KEY_DELETE: {

                if (!editable)
                    break;

                if (k.mod.shift && !k.mod.command && !k.mod.alt) {
                    cut_text();
                    break;
                }

                if (selection.enabled) {
                    undo_text=text;
                    selection_delete();
                    break;
                }

                int text_len = text.length();

                if (cursor_pos==text_len)
                    break; // nothing to do

#ifdef APPLE_STYLE_KEYS
                if (k.mod.alt) {
#else
                if (k.mod.alt) {
                    handled=false;
                    break;
                } else if (k.mod.command) {
#endif
                    int cc=cursor_pos;

                    bool prev_char=false;

                    while (cc<text.length()) {

                        bool ischar=_is_text_char(text[cc]);

                        if (prev_char && !ischar)
                            break;
                        prev_char=ischar;
                        cc++;
                    }

                    delete_text(cursor_pos,cc);

                } else {
                    undo_text=text;
                    set_cursor_pos(cursor_pos+1);
                    delete_char();
                }

            }
            break;
            case KEY_KP_7: {
                if (k.unicode != 0) {
                    handled = false;
                    break;
                }
                // numlock disabled. fallthrough to key_home
            }
            case KEY_HOME: {

                shift_selection_check_pre(k.mod.shift);
                set_cursor_pos(0);
                shift_selection_check_post(k.mod.shift);
            }
            break;
            case KEY_KP_1: {
                if (k.unicode != 0) {
                    handled = false;
                    break;
                }
                // numlock disabled. fallthrough to key_end
            }
            case KEY_END: {

                shift_selection_check_pre(k.mod.shift);
                set_cursor_pos(text.length());
                shift_selection_check_post(k.mod.shift);
            }
            break;


            default: {

                handled=false;
            }
            break;
        }

        if (handled) {
            accept_event();
        } else if (!k.mod.alt && !k.mod.command) {
            if (k.unicode>=32 && k.scancode!=KEY_DELETE) {

                if (editable) {
                    selection_delete();
                    CharType ucodestr[2]= {(CharType)k.unicode,0};
                    append_at_cursor(ucodestr);
                    _text_changed();
                    accept_event();
                }

            } else {
                return;
            }
        }

        update();

    }


    return;

}
break;

    }
}

void LineEdit::set_align(Align p_align) {

ERR_FAIL_INDEX(p_align, 4);
align = p_align;
update();
}

LineEdit::Align LineEdit::get_align() const {

return align;
}

Variant LineEdit::get_drag_data(const Point2& p_point) {

if (selection.drag_attempt && selection.enabled) {
    String t = text.substr(selection.begin, selection.end - selection.begin);
    Label *l = memnew( Label );
    l->set_text(t);
    set_drag_preview(l);
    return 	t;
}

return Variant();

}
bool LineEdit::can_drop_data(const Point2& p_point,const Variant& p_data) const {

return p_data.get_type()==Variant::STRING;
}
void LineEdit::drop_data(const Point2& p_point,const Variant& p_data) {

if (p_data.get_type()==Variant::STRING) {
    set_cursor_at_pixel_pos(p_point.x);
    int selected = selection.end - selection.begin;

    Ref<Font> font = get_font("font");
    if (font != NULL) {
        for (int i = selection.begin; i < selection.end; i++)
            cached_width -= font->get_char_size(text[i]).width;
    }

    text.erase(selection.begin, selected);

    append_at_cursor(p_data);
    selection.begin = cursor_pos-selected;
    selection.end = cursor_pos;
}
}


void LineEdit::_notification(int p_what) {

switch(p_what) {
#ifdef TOOLS_ENABLED
case NOTIFICATION_ENTER_TREE: {
    if (get_tree()->is_editor_hint()) {
        cursor_set_blink_enabled(EDITOR_DEF("text_editor/caret_blink", false));
        cursor_set_blink_speed(EDITOR_DEF("text_editor/caret_blink_speed", 0.65));

        if (!EditorSettings::get_singleton()->is_connected("settings_changed",this,"_editor_settings_changed")) {
            EditorSettings::get_singleton()->connect("settings_changed",this,"_editor_settings_changed");
        }
    }
}
break;
#endif
case NOTIFICATION_RESIZED: {

    set_cursor_pos( get_cursor_pos() );

}
break;
case MainLoop::NOTIFICATION_WM_FOCUS_IN: {
    window_has_focus = true;
    draw_caret = true;
    update();
}
break;
case MainLoop::NOTIFICATION_WM_FOCUS_OUT: {
    window_has_focus = false;
    draw_caret = false;
    update();
}
break;
case NOTIFICATION_DRAW: {

    if ((!has_focus() && !menu->has_focus()) || !window_has_focus) {
        draw_caret = false;
    }

    int width,height;

    Size2 size=get_size();
    width=size.width;
    height=size.height;

    RID ci = get_canvas_item();

    Ref<StyleBox> style = get_stylebox("normal");
    if (!is_editable())
        style=get_stylebox("read_only");

    Ref<Font> font=get_font("font");

    style->draw( ci, Rect2( Point2(), size ) );

    if (has_focus()) {

        get_stylebox("focus")->draw( ci, Rect2( Point2(), size ) );
    }

    int x_ofs=0;

    switch (align) {

    case ALIGN_FILL:
    case ALIGN_LEFT: {

        x_ofs=style->get_offset().x;
    }
    break;
    case ALIGN_CENTER: {

        x_ofs=int(size.width-(cached_width))/2;
    }
    break;
    case ALIGN_RIGHT: {

        x_ofs=int(size.width-style->get_offset().x-(cached_width));
    }
    break;
    }

    int ofs_max=width-style->get_minimum_size().width;
    int char_ofs=window_pos;

    int y_area=height-style->get_minimum_size().height;
    int y_ofs=style->get_offset().y;

    int font_ascent=font->get_ascent();

    Color selection_color=get_color("selection_color");
    Color font_color=get_color("font_color");
    Color font_color_selected=get_color("font_color_selected");
    Color cursor_color=get_color("cursor_color");

    const String& t = text.empty() ? placeholder : text;
    // draw placeholder color
    if(text.empty())
        font_color.a *= placeholder_alpha;

    int caret_height = font->get_height() > y_area ? y_area : font->get_height();
    while(true) {

        //end of string, break!
        if (char_ofs>=t.length())
            break;

        CharType cchar=pass?'*':t[char_ofs];
        CharType next=pass?'*':t[char_ofs+1];
        int char_width=font->get_char_size( cchar,next ).width;

        // end of widget, break!
        if ((x_ofs + char_width) > ofs_max)
            break;


        bool selected=selection.enabled && char_ofs>=selection.begin && char_ofs<selection.end;

        if (selected)
            VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(Point2(x_ofs, y_ofs), Size2(char_width, caret_height)), selection_color);


        font->draw_char(ci, Point2(x_ofs, y_ofs + font_ascent), cchar, next, selected ? font_color_selected : font_color);

        if (char_ofs==cursor_pos && draw_caret) {
            VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(
                        Point2( x_ofs , y_ofs ), Size2( 1, caret_height ) ), cursor_color );
        }

        x_ofs+=char_width;
        char_ofs++;
    }

    if (char_ofs==cursor_pos && draw_caret) {//may be at the end
        VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(
                    Point2( x_ofs , y_ofs ), Size2( 1, caret_height ) ), cursor_color );
    }
}
break;
case NOTIFICATION_FOCUS_ENTER: {

    if (!caret_blink_enabled) {
        draw_caret = true;
    }

    if (OS::get_singleton()->has_virtual_keyboard())
        OS::get_singleton()->show_virtual_keyboard(text,get_global_rect());

}
break;
case NOTIFICATION_FOCUS_EXIT: {

    if (OS::get_singleton()->has_virtual_keyboard())
        OS::get_singleton()->hide_virtual_keyboard();

}
break;

}
}

void LineEdit::copy_text() {

if(selection.enabled) {

    OS::get_singleton()->set_clipboard(text.substr(selection.begin, selection.end - selection.begin));
}
}

void LineEdit::cut_text() {

if(selection.enabled) {
    undo_text = text;
    OS::get_singleton()->set_clipboard(text.substr(selection.begin, selection.end - selection.begin));
    selection_delete();
}
}

void LineEdit::paste_text() {

String paste_buffer = OS::get_singleton()->get_clipboard();

if(paste_buffer != "") {

    if(selection.enabled) selection_delete();
    append_at_cursor(paste_buffer);

    _text_changed();
}



}

void LineEdit::undo() {

int old_cursor_pos = cursor_pos;
text = undo_text;

Ref<Font> font = get_font("font");

cached_width = 0;
for (int i = 0; i<text.length(); i++)
    cached_width += font->get_char_size(text[i]).width;

if(old_cursor_pos > text.length()) {
    set_cursor_pos(text.length());
} else {
    set_cursor_pos(old_cursor_pos);
}

_text_changed();
}
Пример #21
0
static int do_edit(int argc, char *argv[])
{
	int lastscrcol;
	int i;
	int linepos;
	int c;

	if (argc != 2)
		return COMMAND_ERROR_USAGE;

	screenwidth = 80;
	screenheight = 25;

	/* check if we are called as "sedit" instead of "edit" */
	if (*argv[0] == 's') {
		smartscroll = 1;
		getwinsize();
	}

	buffer = NULL;
	if(edit_read_file(argv[1]))
		return 1;

	cursx  = 0;
	cursy  = 0;
	textx  = 0;
	scrcol = 0;
	curline = buffer;
	scrline = curline;
	lastscrline = scrline;
	lastscrcol = 0;

	printf("%c[2J", 27);

	pos(0, -1);

	printf("%c[7m %-25s <ctrl-d>: Save and quit <ctrl-c>: quit %c[0m",
			27, argv[1], 27);
	printf("%c[2;%dr", 27, screenheight);

	screenheight--; /* status line */

	pos(0, 0);

	refresh(1);

	while (1) {
		int curlen = strlen(curline->data);

		if (textx > curlen)
			textx = curlen;
		if (textx < 1)
			textx = 0;

		screenline(curline->data, &linepos);

		if (linepos > scrcol + screenwidth)
			scrcol = linepos - screenwidth;

		if (scrcol > linepos)
			scrcol = linepos;

		cursx = linepos - scrcol;

		while (cursy >= screenheight) {
			cursy--;
			scrline = scrline->next;
		}

		while (cursy < 0) {
			cursy++;
			scrline = scrline->prev;
		}

		if (scrline != lastscrline || scrcol != lastscrcol)
			refresh(0);

		lastscrcol  = scrcol;
		lastscrline = scrline;
		pos(cursx, cursy);

		c = read_key();
		switch (c) {
		case BB_KEY_UP:
			if (!curline->prev)
				continue;

			curline = curline->prev;
			cursy--;
			textx = setpos(curline->data, linepos);
			break;
		case BB_KEY_DOWN:
			if (!curline->next)
				continue;

			curline = curline->next;
			cursy++;
			textx = setpos(curline->data, linepos);
			break;
		case BB_KEY_RIGHT:
			textx++;
			break;
		case BB_KEY_LEFT:
			textx--;
			break;
		case BB_KEY_HOME:
			textx = 0;
			break;
		case BB_KEY_END:
			textx = curlen;
			break;
		case BB_KEY_PAGEUP:
			for (i = 0; i < screenheight - 1; i++) {
				if (!curline->prev)
					break;
				cursy--;
				curline = curline->prev;
			}
			textx = setpos(curline->data, linepos);
			break;
		case BB_KEY_PAGEDOWN:
			for (i = 0; i < screenheight - 1; i++) {
				if (!curline->next)
					break;
				cursy++;
				curline = curline->next;
			}
			textx = setpos(curline->data, linepos);
			break;
		case BB_KEY_DEL:
			if (textx == curlen) {
				if (curline->next)
					merge_line(curline);
			} else
				delete_char(textx);
			break;
		case 13:
		case 10:
			split_line();
			break;
		case 127:
		case 8:
			if (textx > 0) {
				textx--;
				delete_char(textx);
			} else {
				if (!curline->prev)
					break;
				curline = curline->prev;
				cursy--;
				textx = strlen(curline->data);
				merge_line(curline);
			}
			break;
		case 4:
			save_file(argv[1]);
			goto out;
		case 3:
			goto out;
		default:
			if ((signed char)c != -1)
				insert_char(c);
		}
	}
out:
	free_buffer();
	printf("%c[2J%c[r", 27, 27);
	printf("\n");
	return 0;
}
Пример #22
0
inline void sinsp_tracerparser::parse_simple(char* evtstr)
{
	char* p = evtstr;
	uint32_t delta;

	//
	// Extract the type
	//
	m_type_str = p++;

	//
	// Skip to the scope/id
	//
	if(*p != ':')
	{
		if(*p == 0)
		{
			m_res = sinsp_tracerparser::RES_TRUNCATED;
		}
		else
		{
			m_res = sinsp_tracerparser::RES_FAILED;
		}
		return;
	}

	*p = 0;
	p++;

	//
	// Extract the scope
	//
	if(*p == '0')
	{
		m_res = sinsp_tracerparser::RES_TRUNCATED;
		return;
	}

	switch(*p)
	{
	case 't':
		m_id = m_tinfo->m_tid;
		delta = 2;
		break;
	case 'p':
		m_id = m_tinfo->m_pid;
		if(*(p + 1) == 'p')
		{
			m_id = m_tinfo->m_ptid;
			p++;
		}

		delta = 2;
		break;
	case ':':
		m_id = 0;
		delta = 1;
		break;
	case 'g':
		m_id = 0;
		delta = 2;
		break;
	default:
		m_res = parsenumber_colend(p, &m_id, &delta);
		if(m_res > sinsp_tracerparser::RES_COMMA)
		{
			return;
		}
		break;
	}

	p += delta;

	//
	// Extract the tags
	//
	if(*p == '0')
	{
		m_res = sinsp_tracerparser::RES_TRUNCATED;
		return;
	}

	if(*p != ':')
	{
		bool dont_interpret_next_char = false;

		while(true)
		{
			char* start = p;

			m_tags.push_back(p);

			while(*p != 0)
			{
				if(dont_interpret_next_char)
				{
					dont_interpret_next_char = false;
					++p;
					continue;
				}

				if(*p == '\\')
				{
					ASSERT(dont_interpret_next_char == false);
					dont_interpret_next_char = true;
					delete_char(p);
					continue;
				}

				if(*p == '.' || *p == ':')
				{
					break;
				}

				if(*p == '>' || *p == '<' || *p == '=' || *p == '\n')
				{
					m_res = sinsp_tracerparser::RES_FAILED;
					return;
				}

				++p;
			}

			m_taglens.push_back((uint32_t)(p - start));
			m_tot_taglens += (uint32_t)(p - start);

			if(*p == ':')
			{
				*p = 0;
				break;
			}
			else if(*p == 0)
			{
				m_res = sinsp_tracerparser::RES_TRUNCATED;
				return;
			}
			else
			{
				*p = 0;
				++p;
			}
		}
	}

	++p;

	//
	// Extract the arguments
	//
	if(*p == 0)
	{
		m_res = sinsp_tracerparser::RES_TRUNCATED;
		return;
	}

	if(*p != ':')
	{
		bool dont_interpret_next_char = false;

		while(true)
		{
			char* start = p;

			//
			// Arg name
			//
			m_argnames.push_back(p);

			while(*p != 0)
			{
				if(dont_interpret_next_char)
				{
					dont_interpret_next_char = false;
					++p;
					continue;
				}

				if(*p == '\\')
				{
					ASSERT(dont_interpret_next_char == false);
					dont_interpret_next_char = true;
					delete_char(p);
					continue;
				}

				if(*p == '=')
				{
					break;
				}

				if(*p == '>' || *p == '<' || *p == '\n')
				{
					m_res = sinsp_tracerparser::RES_FAILED;
					return;
				}

				++p;
			}

			m_argnamelens.push_back((uint32_t)(p - start));
			m_tot_argnamelens += (uint32_t)(p - start);

			if(*p == 0)
			{
				if(*(p - 1) == ':')
				{
					//
					// This means there was an argument without value, 
					// which we don't support
					//
					m_res = sinsp_tracerparser::RES_FAILED;
				}
				else
				{
					m_res = sinsp_tracerparser::RES_TRUNCATED;
				}
				break;
			}
			else
			{
				*p = 0;
				++p;
			}

			//
			// Arg vals
			//
			start = p;
			m_argvals.push_back(p);

			dont_interpret_next_char = false;

			while(*p != 0)
			{
				if(dont_interpret_next_char)
				{
					dont_interpret_next_char = false;
					++p;
					continue;
				}

				if(*p == '\\')
				{
					ASSERT(dont_interpret_next_char == false);
					dont_interpret_next_char = true;
					delete_char(p);
					continue;
				}

				if(*p == ',' || *p == ':' || *p == '=')
				{
					break;
				}

				++p;
			}

			m_argvallens.push_back((uint32_t)(p - start));
			m_tot_argvallens += (uint32_t)(p - start);

			if(*p == ':')
			{
				*p = 0;
				m_res = sinsp_tracerparser::RES_OK;
				break;
			}
			else if(*p == 0)
			{
				m_res = sinsp_tracerparser::RES_TRUNCATED;
				break;
			}
			else
			{
				*p = 0;
				++p;
			}
		}
	}

	//
	// All done
	//
	return;
}
Пример #23
0
static __inline__ int abortboot(int bootdelay){
	char stopc;
	int abort = 0;

#ifdef CONFIG_SILENT_CONSOLE
	if(gd->flags & GD_FLG_SILENT){
		/* Restore serial console */
		console_assign(stdout, "serial");
		console_assign(stderr, "serial");
	}
#endif

	if(bootdelay > 0){
#ifdef CONFIG_MENUPROMPT
		printf(CONFIG_MENUPROMPT, bootdelay);
#else
		printf("Hit any key to stop autoboot: %d ", bootdelay);
#endif

		while((bootdelay > 0) && (!abort)){
			int i;

			--bootdelay;

			/* delay 100 * 10ms */
			for(i = 0; !abort && i < 100; ++i){
				/* we got a key press	*/
				if(tstc()){
					stopc = getc();
#ifdef CONFIG_AUTOBOOT_STOP_CHAR
					if (stopc == CONFIG_AUTOBOOT_STOP_CHAR) {
#else
					if (stopc != 0) {
#endif
						abort = 1;
						bootdelay = 0;

						break;
					}
				}
				udelay(10000);
			}

			printf("\b\b%d ", bootdelay);
		}

		printf("\n\n");
	}

#ifdef CONFIG_SILENT_CONSOLE
	if(abort){
		/* permanently enable normal console output */
		gd->flags &= ~(GD_FLG_SILENT);
	} else if(gd->flags & GD_FLG_SILENT){
		/* Restore silent console */
		console_assign(stdout, "nulldev");
		console_assign(stderr, "nulldev");
	}
#endif

	return(abort);
}
#endif	/* CONFIG_BOOTDELAY >= 0  */

/****************************************************************************/

void main_loop(void){
#ifndef CFG_HUSH_PARSER
	static char lastcommand[CFG_CBSIZE] = { 0, };
	int len;
	int rc = 1;
	int flag;
#endif
	int counter = 0;

#if defined(CONFIG_BOOTDELAY) && (CONFIG_BOOTDELAY >= 0)
	char *s;
	int bootdelay;
#endif /* defined(CONFIG_BOOTDELAY) && (CONFIG_BOOTDELAY >= 0) */

#ifdef CFG_HUSH_PARSER
	u_boot_hush_start();
#endif

#if defined(CONFIG_BOOTDELAY) && (CONFIG_BOOTDELAY >= 0)
	// get boot delay (seconds)
	s = getenv("bootdelay");
	bootdelay = s ? (int)simple_strtol(s, NULL, 10) : CONFIG_BOOTDELAY;

	// get boot command
	s = getenv("bootcmd");

#if !defined(CONFIG_BOOTCOMMAND)
#error "CONFIG_BOOTCOMMAND not defined!"
#endif

	if(!s){
		setenv("bootcmd", CONFIG_BOOTCOMMAND);
	}

	s = getenv("bootcmd");

	// are we going to run web failsafe mode, U-Boot console, U-Boot netconsole or just boot command?
	if(reset_button_status()){

#ifdef CONFIG_SILENT_CONSOLE
		if(gd->flags & GD_FLG_SILENT){
			/* Restore serial console */
			console_assign(stdout, "serial");
			console_assign(stderr, "serial");
		}

		/* enable normal console output */
		gd->flags &= ~(GD_FLG_SILENT);
#endif

		// wait 0,5s
		milisecdelay(500);

		printf("Press reset button for at least:\n- %d sec. to run web failsafe mode\n- %d sec. to run U-Boot console\n- %d sec. to run U-Boot netconsole\n\n",
				CONFIG_DELAY_TO_AUTORUN_HTTPD,
				CONFIG_DELAY_TO_AUTORUN_CONSOLE,
				CONFIG_DELAY_TO_AUTORUN_NETCONSOLE);

		printf("Reset button is pressed for: %2d ", counter);

		while(reset_button_status()){

			// LED ON and wait 0,15s
			all_led_on();
			milisecdelay(150);

			// LED OFF and wait 0,85s
			all_led_off();
			milisecdelay(850);

			counter++;

			// how long the button is pressed?
			printf("\b\b\b%2d ", counter);

			if(!reset_button_status()){
				break;
			}

			if(counter >= CONFIG_MAX_BUTTON_PRESSING){
				break;
			}
		}

		all_led_off();

		if(counter > 0){

			// run web failsafe mode
			if(counter >= CONFIG_DELAY_TO_AUTORUN_HTTPD && counter < CONFIG_DELAY_TO_AUTORUN_CONSOLE){
				printf("\n\nButton was pressed for %d sec...\nHTTP server is starting for firmware update...\n\n", counter);
				NetLoopHttpd();
				bootdelay = -1;
			} else if(counter >= CONFIG_DELAY_TO_AUTORUN_CONSOLE && counter < CONFIG_DELAY_TO_AUTORUN_NETCONSOLE){
				printf("\n\nButton was pressed for %d sec...\nStarting U-Boot console...\n\n", counter);
				bootdelay = -1;
			} else if(counter >= CONFIG_DELAY_TO_AUTORUN_NETCONSOLE){
				printf("\n\nButton was pressed for %d sec...\nStarting U-Boot netconsole...\n\n", counter);
				bootdelay = -1;
				run_command("startnc", 0);
			} else {
				printf("\n\n## Error: button wasn't pressed long enough!\nContinuing normal boot...\n\n");
			}

		} else {
			printf("\n\n## Error: button wasn't pressed long enough!\nContinuing normal boot...\n\n");
		}

	}

	if(bootdelay >= 0 && s && !abortboot(bootdelay)){

		// try to boot
#ifndef CFG_HUSH_PARSER
			run_command(s, 0);
#else
			parse_string_outer(s, FLAG_PARSE_SEMICOLON | FLAG_EXIT_FROM_LOOP);
#endif

		// something goes wrong!
		printf("\n## Error: failed to execute 'bootcmd'!\nHTTP server is starting for firmware update...\n\n");
		NetLoopHttpd();
	}
#endif	/* CONFIG_BOOTDELAY */

	/*
	 * Main Loop for Monitor Command Processing
	 */
#ifdef CFG_HUSH_PARSER
	parse_file_outer();
	/* This point is never reached */
	for (;;);
#else
	for(;;){
		len = readline(CFG_PROMPT);

		flag = 0; /* assume no special flags for now */
		if(len > 0){
			strcpy(lastcommand, console_buffer);
		} else if(len == 0){
			flag |= CMD_FLAG_REPEAT;
		}

		if(len == -1){
			puts("<INTERRUPT>\n");
		} else {
			rc = run_command(lastcommand, flag);
		}

		if(rc <= 0){
			/* invalid command or not repeatable, forget it */
			lastcommand[0] = 0;
		}
	}
#endif /* CFG_HUSH_PARSER */
}

/****************************************************************************/

/*
 * Prompt for input and read a line.
 * If  CONFIG_BOOT_RETRY_TIME is defined and retry_time >= 0,
 * time out when time goes past endtime (timebase time in ticks).
 * Return:	number of read characters
 *		-1 if break
 *		-2 if timed out
 */
int readline(const char * const prompt){
	char *p = console_buffer;
	int n = 0; /* buffer index		*/
	int plen = 0; /* prompt length	*/
	int col; /* output column cnt	*/
	char c;

	/* print prompt */
	if(prompt){
		plen = strlen(prompt);
		puts(prompt);
	}
	col = plen;

	for(;;){
		c = getc();

		/*
		 * Special character handling
		 */
		switch(c){
			case '\r': /* Enter		*/
			case '\n':
				*p = '\0';
				puts("\r\n");
				return(p - console_buffer);

			case '\0': /* nul			*/
				continue;

			case 0x03: /* ^C - break		*/
				console_buffer[0] = '\0'; /* discard input */
				return(-1);

			case 0x15: /* ^U - erase line	*/
				while(col > plen){
					puts(erase_seq);
					--col;
				}
				p = console_buffer;
				n = 0;
				continue;

			case 0x17: /* ^W - erase word 	*/
				p = delete_char(console_buffer, p, &col, &n, plen);
				while((n > 0) && (*p != ' ')){
					p = delete_char(console_buffer, p, &col, &n, plen);
				}
				continue;

			case 0x08: /* ^H  - backspace	*/
			case 0x7F: /* DEL - backspace	*/
				p = delete_char(console_buffer, p, &col, &n, plen);
				continue;

			default:
				/*
				 * Must be a normal character then
				 */
				if(n < CFG_CBSIZE - 2){
					if(c == '\t'){ /* expand TABs		*/
						puts(tab_seq + (col & 07));
						col += 8 - (col & 07);
					} else {
						++col; /* echo input		*/
						putc(c);
					}
					*p++ = c;
					++n;
				} else { /* Buffer full		*/
					putc('\a');
				}
		}
	}
}