示例#1
0
文件: iv3text.cpp 项目: PNCG/neuron
void Text::keystroke(const Event& event) {
  if (readOnly_) {
    return;
  }
  char buffer[8]; // needs to be dynamically adjusted
  int count = event.mapkey(buffer, 8);
  if (count <= 0) {
    return;
  }

  // return causes a newline
  if (buffer[0] == '\r') {
    buffer[0] = '\n';
  }
	context_key(buffer[0]);

	 if (buffer[0] == 2) // control-b
    {
        if (insertion_.column_ > 0)
        {
            --insertion_.column_;
            damage(insertion_);
            repair();
        }else if (insertion_.line_ > 0) {
        	damage(insertion_);
        	--insertion_.line_;
        	// now just like a control-e
        	int index = text_->LineIndex(insertion_.line_);
        	int end = text_->EndOfLine(index);
        	insertion_.column_ = end - index;
       	 	damage(insertion_);
       	 	repair();
       	}
        return;
    }
	 else if (buffer[0] == 1) // control-a
    {
        insertion_.column_ = 0;
        damage(insertion_);
        repair();
        return;
    }
	 else if (buffer[0] == 6) // control-f
    {
        int index = text_->LineIndex(insertion_.line_);
        int end = text_->EndOfLine(index);
        if (insertion_.column_ < end - index)
        {
            ++insertion_.column_;
            damage(insertion_);
            repair();
        }else if (insertion_.line_ < text_->Height()-1) {
        	damage(insertion_);
        	++insertion_.line_;
        	// now just like control-a
        	insertion_.column_ = 0;
        	damage(insertion_);
        	repair();
        }
        return;
    }
    else if (buffer[0] == 5) // control-e
    {
        int index = text_->LineIndex(insertion_.line_);
        int end = text_->EndOfLine(index);
        insertion_.column_ = end - index;
        damage(insertion_);
        repair();
        return;
    }
    else if (buffer[0] == 16) { // control-p
    	if (insertion_.line_ > 0) {
    		damage(insertion_);
    		--insertion_.line_;
		insertion_.column_ = ctl_pn_col_;
    		int index = text_->LineIndex(insertion_.line_);
        	int col = text_->EndOfLine(index) - index;
        	if (col < insertion_.column_){
        		insertion_.column_ = col;
        	}
        	damage(insertion_);
        	repair();
        }
		return;
    }else if (buffer[0] == 14) { // control-n
    	if (insertion_.line_ < text_->Height()-1) {
    		damage(insertion_);
    		++insertion_.line_;
		insertion_.column_ = ctl_pn_col_;
    		int index = text_->LineIndex(insertion_.line_);
        	int col = text_->EndOfLine(index) - index;
        	if (col < insertion_.column_){
        		insertion_.column_ = col;
        	}
        	damage(insertion_);
        	repair();
        }
		return;
    }else if (escape_ == 1) { // escaped chars
	if (buffer[0] == '>') { // to end of buffer
		damage(insertion_);
		if (text_->Height() >0) {
			insertion_.line_ = text_->Height()-1;
		} else {
			insertion_.line_ = 0;
		}
		int index = text_->LineIndex(text_->EndOfText());
		insertion_.column_ = text_->EndOfText()-index;
		damage(insertion_);
		repair();
	}else if (buffer[0] == '<') {// to beginning of buffer
		damage(insertion_);
		insertion_.line_ = 0;
		insertion_.column_ = 0;
		damage(insertion_);
		repair();
	}
	return;
    }else if (buffer[0] == 033) { // ignore the escape itself
	return;
    }
    else if (buffer[0] == 4) // ctrl-d
    {
      if (!delete_selection()) {
    	// like a ctrl-f then backspace
        int index = text_->LineIndex(insertion_.line_);
        int end = text_->EndOfLine(index);
        if (insertion_.column_ < end - index)
        {
            ++insertion_.column_;
            backspace();
        }else if (insertion_.line_ < text_->Height()-1) {
        	++insertion_.line_;
        	// now just like control-a
        	insertion_.column_ = 0;
        	backspace();
        }
      }
    }

  else if (buffer[0] == 21) {
    // control u
    eraseLine();
  }
  else if ((buffer[0] == '\b') || (buffer[0] == 127)) {
    // backspace and delete
  	if (!delete_selection()) {
	 	backspace();
	}
  }
  else {
  	delete_selection();
	 insertChars(buffer, count);
  }

  dirty(true);
}
示例#2
0
文件: console.c 项目: geek-li/flinux
static size_t console_read(struct file *f, char *buf, size_t count)
{
	struct console_file *console_file = (struct console_file *)f;

	console_lock();
	console_retrieve_state();

	size_t bytes_read = 0;
	while (console->input_buffer_head != console->input_buffer_tail && count > 0)
	{
		count--;
		buf[bytes_read++] = console->input_buffer[console->input_buffer_tail];
		console->input_buffer_tail = (console->input_buffer_tail + 1) % MAX_INPUT;
	}
	if (console->termios.c_lflag & ICANON)
	{
		char line[MAX_CANON + 1]; /* One more for storing CR or LF */
		size_t len = 0;
		while (count > 0)
		{
			INPUT_RECORD ir;
			DWORD read;
			ReadConsoleInputA(console->in, &ir, 1, &read);
			if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
			{
				switch (ir.Event.KeyEvent.wVirtualKeyCode)
				{
				case VK_RETURN:
				{
					if (!(console->termios.c_iflag & IGNCR))
						line[len++] = console->termios.c_iflag & ICRNL ? '\n' : '\r';
					size_t r = min(count, len);
					memcpy(buf + bytes_read, line, r);
					bytes_read += r;
					count -= r;
					if (r < len)
					{
						/* Some bytes not fit, add to input buffer */
						console_add_input(line + r, len - r);
					}
					if (console->termios.c_lflag & ECHO)
						crnl();
					goto read_done;
				}

				case VK_BACK:
				{
					if (len > 0)
					{
						len--;
						if (console->termios.c_lflag & ECHO)
							backspace(TRUE);
					}
				}
				default:
				{
					char ch = ir.Event.KeyEvent.uChar.AsciiChar;
					if (ch >= 0x20)
					{
						if (len < MAX_CANON)
						{
							line[len++] = ch;
							if (console->termios.c_lflag & ECHO)
								write_normal(&ch, 1);
						}
					}
				}
				}
			}
		}
	}
	else /* Non canonical mode */
	{
		int vtime = console->termios.c_cc[VTIME];
		int vmin = console->termios.c_cc[VMIN];
		while (count > 0)
		{
			if (bytes_read > 0 && bytes_read >= vmin)
				break;
			/* If vmin > 0 and vtime == 0, it is a blocking read, otherwise we need to poll first */
			if (vtime > 0 || (vmin == 0 && vtime == 0))
			{
				if (WaitForSingleObject(console->in, vtime * 100) == WAIT_TIMEOUT)
					break;
			}
			INPUT_RECORD ir;
			DWORD read;
			ReadConsoleInputA(console->in, &ir, 1, &read);
			if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
			{
				switch (ir.Event.KeyEvent.wVirtualKeyCode)
				{
				case VK_UP:
					console_buffer_add_string(buf, &bytes_read, &count, console->cursor_key_mode ? "\x1BOA" : "\x1B[A", 3);
					break;

				case VK_DOWN:
					console_buffer_add_string(buf, &bytes_read, &count, console->cursor_key_mode ? "\x1BOB" : "\x1B[B", 3);
					break;

				case VK_RIGHT:
					console_buffer_add_string(buf, &bytes_read, &count, console->cursor_key_mode ? "\x1BOC" : "\x1B[C", 3);
					break;

				case VK_LEFT:
					console_buffer_add_string(buf, &bytes_read, &count, console->cursor_key_mode ? "\x1BOD" : "\x1B[D", 3);
					break;

				case VK_HOME:
					console_buffer_add_string(buf, &bytes_read, &count, console->cursor_key_mode ? "\x1BOH" : "\x1B[H", 3);
					break;

				case VK_END:
					console_buffer_add_string(buf, &bytes_read, &count, console->cursor_key_mode ? "\x1BOF" : "\x1B[F", 3);
					break;

				case VK_INSERT: console_buffer_add_string(buf, &bytes_read, &count, "\x1B[2~", 4); break;
				case VK_DELETE: console_buffer_add_string(buf, &bytes_read, &count, "\x1B[3~", 4); break;
				case VK_PRIOR: console_buffer_add_string(buf, &bytes_read, &count, "\x1B[5~", 4); break;
				case VK_NEXT: console_buffer_add_string(buf, &bytes_read, &count, "\x1B[6~", 4); break;

				case VK_F1: console_buffer_add_string(buf, &bytes_read, &count, "\x1BOP", 3); break;
				case VK_F2: console_buffer_add_string(buf, &bytes_read, &count, "\x1BOQ", 3); break;
				case VK_F3: console_buffer_add_string(buf, &bytes_read, &count, "\x1BOR", 3); break;
				case VK_F4: console_buffer_add_string(buf, &bytes_read, &count, "\x1BOS", 3); break;
				case VK_F5: console_buffer_add_string(buf, &bytes_read, &count, "\x1B[15~", 5); break;
				case VK_F6: console_buffer_add_string(buf, &bytes_read, &count, "\x1B[17~", 5); break;
				case VK_F7: console_buffer_add_string(buf, &bytes_read, &count, "\x1B[18~", 5); break;
				case VK_F8: console_buffer_add_string(buf, &bytes_read, &count, "\x1B[19~", 5); break;
				case VK_F9: console_buffer_add_string(buf, &bytes_read, &count, "\x1B[20~", 5); break;
				case VK_F10: console_buffer_add_string(buf, &bytes_read, &count, "\x1B[21~", 5); break;
				case VK_F11: console_buffer_add_string(buf, &bytes_read, &count, "\x1B[23~", 5); break;
				case VK_F12: console_buffer_add_string(buf, &bytes_read, &count, "\x1B[24~", 5); break;
				case VK_F13: console_buffer_add_string(buf, &bytes_read, &count, "\x1B[25~", 5); break;
				case VK_F14: console_buffer_add_string(buf, &bytes_read, &count, "\x1B[26~", 5); break;
				case VK_F15: console_buffer_add_string(buf, &bytes_read, &count, "\x1B[28~", 5); break;
				case VK_F16: console_buffer_add_string(buf, &bytes_read, &count, "\x1B[29~", 5); break;
				case VK_F17: console_buffer_add_string(buf, &bytes_read, &count, "\x1B[31~", 5); break;
				case VK_F18: console_buffer_add_string(buf, &bytes_read, &count, "\x1B[32~", 5); break;
				case VK_F19: console_buffer_add_string(buf, &bytes_read, &count, "\x1B[33~", 5); break;
				case VK_F20: console_buffer_add_string(buf, &bytes_read, &count, "\x1B[34~", 5); break;

				default:
				{
					char ch = ir.Event.KeyEvent.uChar.AsciiChar;
					if (ch == '\r' && console->termios.c_iflag & IGNCR)
						break;
					if (ch == '\r' && console->termios.c_iflag & ICRNL)
						ch = '\n';
					else if (ch == '\n' && console->termios.c_iflag & ICRNL)
						ch = '\r';
					if (ch > 0)
					{
						count--;
						buf[bytes_read++] = ch;
						if (console->termios.c_lflag & ECHO)
							write_normal(&ch, 1);
					}
				}
				}
			}
			else
			{
				/* TODO: Other types of input */
			}
		}
	}
read_done:
	/* This will make the caret immediately visible */
	set_pos(console->x, console->y);
	console_unlock();
	return bytes_read;
}
int
main(int argc, char *argv[])
{

    int index;                  /* index of last key we pushed in the bitmap font */
    SDL_Window *window;
    SDL_Event event;            /* last event received */
    SDLMod mod;                 /* key modifiers of last key we pushed */
    SDL_scancode scancode;      /* scancode of last key we pushed */

    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        printf("Error initializing SDL: %s", SDL_GetError());
    }
    /* create window */
    window = SDL_CreateWindow("iPhone keyboard test", 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, 0);
    /* create renderer */
    SDL_CreateRenderer(window, 0, 0);

    /* load up our font */
    loadFont();

    /* draw the background, we'll just paint over it */
    SDL_SetRenderDrawColor(bg_color.r, bg_color.g, bg_color.b,
                           bg_color.unused);
    SDL_RenderFill(NULL);
    SDL_RenderPresent();

    int done = 0;
    /* loop till we get SDL_Quit */
    while (SDL_WaitEvent(&event)) {
        switch (event.type) {
        case SDL_QUIT:
            done = 1;
            break;
        case SDL_KEYDOWN:
            index = keyToIndex(event.key.keysym);
            scancode = event.key.keysym.scancode;
            mod = event.key.keysym.mod;
            if (scancode == SDL_SCANCODE_DELETE) {
                /* if user hit delete, delete the last character */
                backspace();
                lastCharWasColon = 0;
            } else if (lastCharWasColon && scancode == SDL_SCANCODE_0
                       && (mod & KMOD_SHIFT)) {
                /* if our last key was a colon and this one is a close paren, the make a hoppy face */
                backspace();
                drawIndex(32);  /* index for happy face */
                numChars++;
                drawCursor();
                lastCharWasColon = 0;
            } else if (index != -1) {
                /* if we aren't doing a happy face, then just draw the normal character */
                drawIndex(index);
                numChars++;
                drawCursor();
                lastCharWasColon =
                    (event.key.keysym.scancode == SDL_SCANCODE_SEMICOLON
                     && (event.key.keysym.mod & KMOD_SHIFT));
            }
            /* check if the key was a colon */
            /* draw our updates to the screen */
            SDL_RenderPresent();
            break;
#ifdef __IPHONEOS__
        case SDL_MOUSEBUTTONUP:
            /*      mouse up toggles onscreen keyboard visibility
               this function is available ONLY on iPhone OS
             */
            SDL_iPhoneKeyboardToggle(window);
            break;
#endif
        }
    }
    cleanup();
    return 0;
}
static void TermCompletionOnFiles(char **dictionaryFiles, int sizedictionaryFiles,
                                  char *lineBeforeCaret, char *lineAfterCaret, char *filePattern, char *defaultPattern,
                                  char **wk_buf, unsigned int *cursor, unsigned int *cursor_max)
{
    if (dictionaryFiles)
    {
        if (sizedictionaryFiles == 1)
        {
            char *new_line = completeLine(lineBeforeCaret, dictionaryFiles[0], filePattern, defaultPattern, TRUE, lineAfterCaret);

            if (new_line)
            {
                char buflinetmp[WK_BUF_SIZE + 1];

                strcpy(buflinetmp, new_line);
                FREE(new_line);

                backspace(*cursor);
                erase_nchar(*cursor_max);
                *cursor = *cursor_max = 0;

                CopyLineAtPrompt(wk_buf, buflinetmp, cursor, cursor_max);
                return;
            }
        }
        else
        {
            char *common = getCommonPart(dictionaryFiles, sizedictionaryFiles);

            displayCompletionDictionary(dictionaryFiles, sizedictionaryFiles, gettext("File or Directory"));

            printf("\n");

            backspace(*cursor);
            erase_nchar(*cursor_max);
            *cursor = *cursor_max = 0;

            printPrompt(WRITE_PROMPT);

            if (defaultPattern[0] == 0)
            {
                int lennewline = (int)strlen(lineBeforeCaret) + (int)strlen(lineAfterCaret);

                char *new_line = (char *)MALLOC(sizeof(char) * (lennewline + 1));

                if (new_line)
                {
                    strcpy(new_line, lineBeforeCaret);
                    strcat(new_line, lineAfterCaret);

                    CopyLineAtPrompt(wk_buf, new_line, cursor, cursor_max);
                    FREE(new_line);
                    new_line = NULL;
                }
            }
            else if (common)
            {
                char *new_line = completeLine(lineBeforeCaret, common, filePattern, defaultPattern, TRUE, lineAfterCaret);

                if (new_line)
                {
                    char buflinetmp[WK_BUF_SIZE + 1];

                    strcpy(buflinetmp, new_line);
                    FREE(new_line);

                    CopyLineAtPrompt(wk_buf, buflinetmp, cursor, cursor_max);
                }
                else
                {
                    int lennewline = (int)strlen(lineBeforeCaret) + (int)strlen(lineAfterCaret);

                    new_line = (char *)MALLOC(sizeof(char) * (lennewline + 1));

                    if (new_line)
                    {
                        strcpy(new_line, lineBeforeCaret);
                        strcat(new_line, lineAfterCaret);

                        CopyLineAtPrompt(wk_buf, new_line, cursor, cursor_max);
                        FREE(new_line);
                        new_line = NULL;
                    }
                }
            }
            if (common)
            {
                FREE(common);
                common = NULL;
            }
        }
    }
}
示例#5
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;
	    }
	}
    }
}
示例#6
0
static void backup(char *buffer, int pos) 
{
backspace(xstrlen(&buffer[pos]));
}
示例#7
0
int
get_token()
{
	long		number;
	int		type = UNDEF;
	register int	ch;
	static char	buffer[1024];
	register char	*ptr;
	int		dot_flag = FALSE;

	while ((ch = next_char()) == '\n' || (isascii(ch) && iswhite(ch)));

	if (ch == EOF)
	    type = EOF;
	else {
	    if (ch == '.') {
		dot_flag = TRUE;

		while ((ch = next_char()) == ' ' || ch == '\t');
	    }

	    if (! isascii(ch) || ! isalnum(ch)) {
		warning("Illegal character - '%c'", ch);
		panic_mode(',');
	    }

	    ptr = buffer;
	    if (ch != '\n') *(ptr++) = ch;

	    if (first_column) {
		while ((ch = next_char()) != ',' && ch != '\n' && ch != EOF)
		    *(ptr++) = ch;

		if (ch == EOF)
		    err_abort("Premature EOF");
		else if (ch == '\n') {
		    warning("Newline in middle of terminal name");
		    panic_mode(',');
		}

		*ptr = '\0';
		curr_token.tk_name = buffer;
		type = NAMES;
	    } else {
		ch = next_char();
		while (isascii(ch) && isalnum(ch)) {
		    *(ptr++) = ch;
		    ch = next_char();
		}

		*ptr++ = '\0';
		switch (ch) {
		    case ',':
			curr_token.tk_name = buffer;
			type = BOOLEAN;
			break;

		    case '@':
			if (next_char() != ',')
			    warning("Missing comma");
			curr_token.tk_name = buffer;
			type = CANCEL;
			break;

		    case '#':
			number = 0;
			if ((ch = next_char()) == ',')
				warning("Missing numeric value");
			backspace();
			if ((ch = next_char()) == '0') {
			    if ((ch = next_char()) == 'x' || ch == 'X') {
				while (isascii(ch = next_char()) &&
				    isxdigit(ch)) {
				    number *= 16;
				    if (isdigit(ch))
					number += ch - '0';
				    else if (ch >= 'a' && ch <= 'f')
					number += 10 + ch - 'a';
				    else
					number += 10 + ch - 'A';
				}
			    } else {
				backspace();
				while ((ch = next_char()) >= '0' &&
				    ch <= '7')
				    number = number * 8 + ch - '0';
				}
			    } else {
				    backspace();
				    while (isascii(ch = next_char()) &&
					isdigit(ch))
					number = number * 10 + ch - '0';
			    }
			if (ch != ',')
			    warning("Missing comma");
			curr_token.tk_name = buffer;
			curr_token.tk_valnumber = number;
			type = NUMBER;
			break;

		    case '=':
			ch = trans_string(ptr);
			if (ch != NULL && ch != ',')
			    warning("Missing comma");
			if (ch == NULL)
				warning("NULL string value");
			curr_token.tk_name = buffer;
			curr_token.tk_valstring = ptr;
			type = STRING;
			break;

		    default:
			warning("Illegal character - '%c'", ch);
		}
	    } /* end else (first_column == FALSE) */
	} /* end else (ch != EOF) */

	if (dot_flag == TRUE)
	    DEBUG(8, "Commented out ", "");

	if (debug_level >= 8) {
	    fprintf(stderr, "Token: ");
	    switch (type) {
		case BOOLEAN:
			fprintf(stderr, "Boolean;  name='%s'\n",
			    curr_token.tk_name);
			break;

		case NUMBER:
			fprintf(stderr, "Number; name = '%s', value = %d\n",
			    curr_token.tk_name, curr_token.tk_valnumber);
			break;

		case STRING:
			fprintf(stderr, "String; name = '%s', value = '%s'\n",
			    curr_token.tk_name, curr_token.tk_valstring);
			break;

		case CANCEL:
			fprintf(stderr, "Cancel; name = '%s'\n",
			    curr_token.tk_name);
		    break;

		case NAMES:
			fprintf(stderr, "Names; value = '%s'\n",
			    curr_token.tk_name);
			break;

		case EOF:
			fprintf(stderr, "End of file\n");
			break;

		default:
			warning("Bad token type");
	    }
	}

	if (dot_flag == TRUE)	/* if commented out, use the next one */
	    type = get_token();

	return (type);
}
示例#8
0
void get_current()
{
  int c,lc,i=0;

  raw();
  noecho();
  keypad(stdscr, TRUE);

  while ((c=getch()))
  {
    if (c == '\t')                                // Tab
    {
      if (showing)  tab_hits_down();
      else {
        clrtobot();
        if (current_length > 1) {
          hunt_current();
          show_hits();
          tab_hits_down();
        }
      }
    }
    else if (c == '\n' && lc == '\n') break;      // two-returns to quit
    else if (c == 27) { exiting=1;break;break; }            // ESC quit
    else if (c == 'J' || c == 258)                // J | d-arrow down hit list
      tab_hits_down();
    else if (c == 'K' || c == 353 || c == 259)    // K | <shift-TAB> | u-arrow up hit list
      tab_hits_up(); 
    else if (c == 32)                             // SPACE to reset search
    {
      memset(current,'\0',MAX_LINE);
      current_length = 0;
      clear_matches();
      setup_screen();
      mvprintw(LINES - 2, 0, "!: %s", items);
      move(cursor_row,cursor_col+3);
      refresh();
      i=0;
    }
    else if (c == 127 || c == 8)                  // DELETE or BACKSPACE
    {
      if (current_length > 0 )
      {
        i--;
        current_length--;
        current[i] = '\0';
        clrtobot();
        mvprintw(LINES - 2, 0, "!: %s", items);
        backspace();
        move(cursor_row,cursor_col);
        getsyx(cursor_row,cursor_col);
        if (showing && current_length > 1) {
          hunt_current();
          show_hits();
          tab_hits_down();
        }
      }
    }
    else if (c=='\n')                             // SELECT hightlighted hit or typed word
    {
      if (showing && sel_match>-1) strcat(items,tags[matches[sel_match].index]);
      else strcat(items,current);
      memset(current,'\0',MAX_LINE);
      current_length=i=0;
      setup_screen();
      showing=FALSE;
      strcat(items," ");
      mvprintw(LINES - 2, 0, "!: %s", items);
      move(cursor_row,cursor_col+3);
      refresh();
    }
    else                                          // regular key-typed
    {
      addch(c);
      current[i]=c;
      ++i;
      ++current_length;
      refresh();
      getsyx(cursor_row,cursor_col);
      if (showing && (current_length > 1)) {
        noraw();
        delch();
        raw();
        refresh();
        hunt_current();
        show_hits();
        tab_hits_down();
      }
      else showing=FALSE;
    }
    lc = c;
    if (diags) diag(c);
  }
  current[i] = '\0';
}
示例#9
0
/*
 * Filter an entire file, writing the result to the standard output.
 */
static void
ManFilter(FILE *ifp)
{
	int	c;
	int	level = 0;
	int	ident = CS_NORMAL;
	int	esc_mode = ATR_NORMAL;

	while ((c = fgetc(ifp)) != EOF) {
		switch (c) {
		case '\b':
			backspace();
			break;

		case '\r':
			if (cur_line != 0)
				cur_line->l_this = 0;
			break;

		case '\n':
			next_line();
			cur_line->l_this = 0;
			break;

		case '\t':
			do {
				put_cell(SPACE, level, ident);
			} while (cur_line->l_this & 7);
			break;

		case '\v':
			prev_line();
			break;

		case SHIFT_IN:
			ident = CS_NORMAL;
			break;

		case SHIFT_OUT:
			ident = CS_ALTERNATE;
			break;

		case ESCAPE:
			switch (fgetc(ifp)) {
			case '[':
				esc_mode = ansi_escape(ifp, ident, level);
				break;
			case '\007':
			case '7':
				prev_line();
				break;
			case '\010':
			case '8':
				level = half_up(level);
				break;
			case '\011':
			case '9':
				level = half_down(level);
				break;
			default: /* ignore everything else */
				break;
			}
			break;

		default: /* ignore other nonprinting characters */
			if (isprint(c)) {
				put_cell(c, level, ident);
				if (c != SPACE) {
					if (esc_mode & ATR_BOLD) {
						backspace();
						put_cell(c, level, ident);
					}
					if (esc_mode & ATR_UNDER) {
						backspace();
						put_cell('_', level, ident);
					}
				}
			}
			break;
		}
	}

	while (all_lines != 0)
		flush_line();

	total_lines = 0;
}
示例#10
0
/* lineeditor():
 * This is a simpler version of lineeditor() (as found in lineedit.c).
 * It does not have the capability of the vi-like version; however, for
 * those not familiar with ksh, this one is probably a lot more intuitive.
 *
 * The line is modified in place so, if successful, the function
 * returns the same pointer but with its contents modified based
 * on the editor commands executed.
 * If failure, the function returns (char *)0.
 */
static char *
lineeditor(char *line_to_edit,int type)
{
	int	state;

	if (type == EDITCMDLINE) {
		if (getchar() != OPEN_BRACKET) {
			putchar('\n');
			*line_to_edit = 0;
			return((char *)0);
		}
	}

	startOfLine = line_to_edit;
	curPos = line_to_edit;
	while(*curPos != ESC) 
		curPos++;

	*curPos = 0;	/* Remove the escape character from the line */
	lineLen = (ulong)curPos - (ulong)startOfLine;
	if (lineLen > 0) {
		curPos--;
		putstr(" \b\b");
	}
	else
		putstr(" \b");

	state = GOT_BRACKET;
	lastsize = 0;
	shwidx = stridx;
	srchidx = stridx;
	while(1) {
		curChar = getchar();
		switch(curChar) {
			case CTLC:
				putchar('\n');
				*line_to_edit = 0;
				return((char *)0);
			case VT100_UP:
				if (state == GOT_BRACKET) {
					if (type == EDITCMDLINE) 
						showprev();
					state = GOT_NUTTIN;
				}
				else {
					newchar(curChar);
				}
				break;
			case VT100_DOWN:
				if (state == GOT_BRACKET) {
					if (type == EDITCMDLINE) 
						shownext();
					state = GOT_NUTTIN;
				}
				else {
					newchar(curChar);
				}
				break;
			case VT100_RIGHT:
				if (state == GOT_BRACKET) {
					if (curPos < startOfLine+lineLen) {
						putchar(*curPos);
						curPos++;
					}
					state = GOT_NUTTIN;
				}
				else {
					newchar(curChar);
				}
				break;
			case VT100_LEFT:
				if (state == GOT_BRACKET) {
					if (curPos > startOfLine) {
						putchar('\b');
						curPos--;
					}
					state = GOT_NUTTIN;
				}
				else {
					newchar(curChar);
				}
				break;
			case OPEN_BRACKET:
				if (state == GOT_ESCAPE) {
					state = GOT_BRACKET;
				}
				else {
					newchar(curChar);
				}
				break;
			case ESC:
				state = GOT_ESCAPE;
				break;
			case VT100_DEL:
				if (curPos != (startOfLine + lineLen))
					ldelete();
				break;
			case '\b':
				if (curPos > startOfLine)
					backspace();
				break;
			case '\n':
			case '\r':
				putchar('\n');
				if (lineLen == 0) 
					return((char *)0);
				*(char *)(startOfLine + lineLen) = '\0';
				return(startOfLine);
			default:
				newchar(curChar);
				break;
		}
	}
	return((char *)0);
}
示例#11
0
	void eHealthDisplayClass::printAirFlowScreen(void)
	{
		int j = 0;

		for (j=0; j<45; j++)
		{
			pixel(8, j, 0);
		}

		delay(10);

		//Lung picture
		if (millis()-timePreviousMeassure > 10000) {
			countsPerMinute = 6*count;
			timePreviousMeassure = millis();
			//Apnea signal OFF

			apneaAdvise(0);

			coordinates(94, 52);	backspace();
			coordinates(99, 52);	backspace();
			coordinates(104, 52);	backspace();
			coordinates(109, 52);	backspace();
			coordinates(114, 52);	backspace();
			coordinates(119, 52);	backspace();
			coordinates(124, 52);	backspace();
			delay(10);

			if(count ==0 ){
				//Apnea sinal ON
				apneaAdvise(1);

				coordinates(94, 52);
				writeLCD("Apnea");
				delay(5);
			}

			count = 0;
			//Clear the space
			coordinates(53, 52);	backspace();
			coordinates(50, 52);	backspace();
			coordinates(45, 52);	backspace();
			coordinates(40, 52);	backspace();

			writeLcdDec(countsPerMinute);
			delay(20);
		}

			//Lung ON
			printLung(1);

			// Input 1
			valRead = analogRead(1);

			valRead   = map(valRead, 0, 1023, 5, 45);
			delay(100);
			pixel (x, valRead, 1);

			if(x>8){
				line(x-1, prevRead, x, valRead, 1);
			}

			if(valRead> 7)	waveState=1;


			if(waveState==1)
			{
				if(valRead<6)
				{
					//Lung OFF
					printLung(0);
					count=count+1;
					waveState=0;
					delay(100);
				}
			}

			//Wave refresh
			for (j = 5; j < 40 ; j++)
			{
				pixel(x+1,j,0);
			}

			prevRead = valRead;

		x++;

		if (x == 120) x = 8;
	}
示例#12
0
/*struct txtfld
{
	int x;
	int y;
	int r;
	char *feild_name;
};
struct txtfld t1;*/
void draw_txtbox(int leftx,int lefty,int rightx,char *fname)
{
	 int pos=0,insflg=0,tempflg=0;
	 int i=-1,row,j=0,temp,col,maxsize;
	 char c[1];


	 ch[0]=(char*)calloc(sizeof(char),20);

	 row=lefty+7;
	 col=leftx+5;

	 maxsize=(rightx-leftx)/8 - 2;

	 settextstyle(0,0,1);
	 setcolor(15);
//	 outtextxy(leftx,lefty-10,fname);
	 showbox(leftx,lefty,rightx,fname);

	 do
	 {

		i=i+1;

		cursor(ch[j],col,row,pos);

		ch[j][i]=temp=bioskey(0);
//		printf("%c",ch[j][i]);
		ch[j][i+1]='\0';
		if(temp == HOME||temp == END||temp ==LEFT||temp ==RIGHT||temp ==DEL||temp ==INSERT)
		{
			 specialkey(ch[j],col,row,temp,&pos,&i,&insflg);
			 continue;
		}

		if(ch[j][i]=='\x1B' || ch[j][i]=='\x0D')          //escape
		{
			 ch[j][i]='\0';
//			 hidebox(leftx,lefty,rightx);
 //			 hidebox(leftx,lefty,rightx,fname);
			 break;
		}

		if(ch[j][i]!='\t' && ch[j][i]!='\x1B' && ch[j][i]!='\b')
		{
			 if(i==maxsize)
			 {
				ch[j][i]='\0';
				i=i-1;
				continue;
			 }
			 keycheck(ch[j],&i,5,&tempflg);
			 if(tempflg==1)
			 {
				tempflg=0;
				continue;
			 }

		}
		if(ch[j][i]=='.')        //.(full stop)
		{
			 ch[j][i]='.';
		}

		setcolor(15);
		outtextxy((strlen(ch[j])-1)*8+col,row+2,"_");
		setcolor(0);

		if(ch[j][i]=='\b')        //backspace
		{
			 backspace(ch[j],&i,pos,row,col);
			 continue;
		}

		if(insflg%2==1)
		{
			 insert(ch[j],&i,pos,row,col);
			 continue;
		}
//		if(ch[j][i]!='\b')
//		{
			 if(pos>0)
			 {
				setfillstyle(1,15);
				bar(strlen(ch[j])*8+col-pos*8-8,row,strlen(ch[j])*8+col-pos*8-1,row+7);
				ch[j][i-pos]=ch[j][i];
				ch[j][i]='\x0';
				sprintf(c,"%c",ch[j][i-pos]);
				setcolor(0);
				outtextxy(strlen(ch[j])*8+col-pos*8,row,c);
				pos=pos-1;
				i=i-1;
			 }
			 else
			 {
				sprintf(c,"%c",ch[j][i]);
				setcolor(0);
				outtextxy(strlen(ch[j])*8+col-8-pos*8,row,c);
			 }
  //		}
	 }while(ch[j][i]!='\x1B' || ch[j][i]!='\x0D');
}
示例#13
0
int main(int argc, char *argv[], char *envp[])
{
	read_config(); //read the config file
	char c; //reading one letter at time here
	
	//building a command line which will eventually get parsed
	line = (char *)malloc(sizeof(char) * 100); 
	memset(line,0,100);
	char *cmd = (char *)malloc(sizeof(char) * 100); //the program (command w/o args)
	char *printBuff = (char *)malloc(sizeof(char)*100); //a printing buffer (for use with raw tty)
	
	//holder for history if stuff is typed, then history is used to go back to typed stuff
	char *historyHold = (char *)malloc(sizeof(char)*100); 
	path = (char*)malloc(sizeof(char)*100);
	fullPath = (char*)malloc(sizeof(char)*100);
	memset(printBuff,0,100);
	memset(historyHold,0,100);
	memset(cmd,0,100);
	signal(SIGINT, handle_sig); //register interrupt signal (for CTRL+C)
	int promptLen; //making sure we dont backspace the prompt
	int fromHistory = 0; //a type of check to see if our line is from history (not user typed)
	
	if(fork() == 0) {
		execve("/usr/bin/clear", argv, envp); //simply clear the screen
		exit(1);
	}
	else {
		wait(NULL); //wait to clear screen
	}
	get_path(); //gets the 2dir path for prompt
	tty_raw_mode();//set terminal into raw mode	
	sprintf(printBuff,"%s:%s",path,PROMPT); //build print buff
	promptLen = strlen(printBuff);
	curPos = promptLen; //leave a space
	write(1,printBuff,promptLen); //print initial prompt
	memset(printBuff,0,100); //clear printBuff
	clear_args(); //just get any initial crap out
	
	/* MAIN LOOP */
	while(1) {
		read(0,&c,1); //read 1 character from stdin
		if(((c >= 32) && c!=127) || c == 10) { 
			//here, we only want to process characters that are
			//"readable" (or enter). special characters will be
			//handled differently
			tabPressNo = 0; //they didnt press tab
			write(1,&c,1); //write char (echo is off for raw mode)
			++curPos;
			switch(c) {
				case '\n': //end of the line (enter was pressed after input)
					if(line[0] == '\0') { 
						//they didnt type anything
						sprintf(printBuff,"%s:%s",path,PROMPT);
						write(1,printBuff,promptLen); 
					} 
					else if(strcmp(line,"exit")==0) {
						printf("\n"); //for niceness
						quit_raw_mode(); //play nice and restore term state
						return 0; //quit if they type "exit"
					}
					else { //prepare to actually process						
						strncat(line,"\0",1);
						if(line[0] != '!') {
							add_history(line); //add command to history
						}	
						int pipe = 0;
						int separ = check_separ(line);
						if(!separ){
							pipe = check_pipe(line);					
						}
						if(!separ && !pipe){ //try to execute the command if there werent pipes or semicolons
							parse_args(line); //build array of arguments
							strcpy(cmd, args[0]); //cmd = program to run
							execute(cmd);
							clear_args(); //resets all arg array strings
						}
						c = '\0';
						memset(cmd, 0, 100); //clear the cmd array
						//reprint prompt
						sprintf(printBuff,"%s:%s",path,PROMPT);
						promptLen = strlen(printBuff);
						curPos = promptLen;
						write(1,printBuff,promptLen);						
					}
					memset(line,0,100); //clear line array
					memset(historyHold,0,100);//clear history hold
					break;
				default: strncat(line, &c, 1);//build the line
					break;
			}
		}
		else if(c == 8) {
			//backspace pressed
			if(curPos > promptLen) {
				backspace(); //backspace until we reach prompt
				line[strlen(line)-1] = 0; //thank god this finally works
				--curPos;
			}
		}
		else if(c == 27) {
			//the user pressed some sort of
			//escape sequence
			char c1;
			char c2;
			read(0,&c1,1);
			read(0,&c2,1);
			
			//ok, we have the two parts of the 
			//escape sequence in c1 and c2
			if(c1 == 91 && c2 == 65) {
				//this is the escape for the up arrow
				//which we want to use for history 
				//browsing
				char *tmpLine;
				tmpLine = prev_history();
				if(tmpLine != 0) {
					if(line[0] != '\0' && fromHistory==0) {
						//store what user currently has typed (if anything)
						memset(historyHold,0,100);
						strncpy(historyHold,line,strlen(line)); 
					}
					clear_line(strlen(line)); //clears whatever is at the prompt
					memset(line,0,100);
					strncpy(line,tmpLine,strlen(tmpLine)); //copy this command
					free(tmpLine); //play nice
					write(1,line,strlen(line)); //write old command
					fromHistory = 1; //current line has been replaced by history
					curPos = strlen(line) + promptLen; //so we know where are
				}
			}
			else if(c1 == 91 && c2 == 66) {
				//this is the escape for the down arrow
				//which should make us go "forward"
				//in history (if we are back in it)
				char *tmpLine;
				tmpLine = next_history(); //get the next history
				if(tmpLine != 0) {
					//next_history gave us a line
					clear_line(strlen(line)); //clear old line from screen
					memset(line,0,100); //clear old line in mem
					strncpy(line,tmpLine,strlen(tmpLine)); //copy new line to old line
					write(1,line,strlen(line)); //write new line to screen
					curPos = strlen(line) + promptLen; //update pos
					free(tmpLine);
				}
				else if(historyHold[0] != '\0') {
					//if we dont have a next_line, lets see if
					//we had some buffer before browsing history
					clear_line(strlen(line));
					memset(line,0,100);					
					strncpy(line,historyHold,strlen(historyHold));
					write(1,line,strlen(line));
					curPos = strlen(line) +promptLen;
					fromHistory = 0; //back to user typed
				}
				else {
					//it was blank before history was browsed
					clear_line(strlen(line));
					memset(line,0,100);
					curPos = promptLen;
				}
			}
		}
		else if(c == '\t') {
			//tab press. should i dare try to do tab
			//completion? i guess...
			
			//if this is the 2nd time in a row pressing tab
			//they want a listing of everything that can be
			//completed
			if(tabPressNo) {
				//print everything in tabHold
				tabPressNo = 0;
				if(tabCompHold[0] != NULL) {
					int i = 1;
					char *x = tabCompHold[0];
					char *tmp = (char*)malloc(sizeof(char)*100);
					memset(tmp,0,100);
					write(1,"\n",1);
					while(x != NULL) {
						sprintf(tmp,"%s\t",x);
						write(1,tmp,strlen(tmp));
						memset(tmp,0,100);
						x = tabCompHold[i];
						++i;
					}
					write(1,"\n",1);
					//reprint prompt
					sprintf(printBuff,"%s:%s",path,PROMPT);
					promptLen = strlen(printBuff);
					curPos = promptLen + strlen(line);
					write(1,printBuff,promptLen);
					//write the line again
					write(1,line,strlen(line));
					clear_tab_hold();
				}
			} else {
				//otherwise just let tab_complete
				//print a single completion
				char *tabcomp;
				tabcomp = tab_complete(line);
				if(tabcomp != NULL) {
					//tab comp found a single thing, so
					//lets just complete it
					int i = 1;
					char c = tabcomp[0];
					while(c!='\0') {
						write(1,&c,1);
						strncat(line,&c,1);
						c = tabcomp[i];
						++i;
					}
					curPos += strlen(tabcomp); //set our new position
					free(tabcomp);
				}
				++tabPressNo;
			}
		}
		else if(c == '\177') {
			//other form of backspace
			if(curPos > promptLen) {
			backspace(); //backspace until we reach prompt
			line[strlen(line)-1] = 0; //thank god this finally works
			--curPos;
			}			
		}
		memset(printBuff,0,100); //clear printing buffer
	}
	printf("\n"); //for niceness
	quit_raw_mode(); //so we dont get stuck in it
	return 0; //goodbye
}
示例#14
0
void RtKeyboard::setupFuncKey(void)
{  
    QPoint FuncPoints[__FUN_NUMS__] = {
        QPoint(91,97),QPoint(7,67),QPoint(210,67),QPoint(8,97),QPoint(196,97),
        QPoint(58,97),QPoint(163,97)
    };

    // Func #0 -> Space Key
    QString strSpace = " ";
    QRect rectBtnText = QRect(0,0,0,0);
    m_pFuncButton[__FUN_KEY_0__] = new RtKeyButton(this,__FUN_KEY_0__);
    m_pFuncButton[__FUN_KEY_0__]->SetImages(&m_Key4[0],&m_Key4[0]);
    m_pFuncButton[__FUN_KEY_0__]->setGeometry(FuncPoints[__FUN_KEY_0__].x(),FuncPoints[__FUN_KEY_0__].y(),m_Key4[0].width(),m_Key4[0].height());
    m_pFuncButton[__FUN_KEY_0__]->setButtonText(strSpace,rectBtnText);
    connect(m_pFuncButton[__FUN_KEY_0__], SIGNAL(clicked()), signalMapper, SLOT(map()));
    signalMapper->setMapping(m_pFuncButton[__FUN_KEY_0__], strSpace);

    // Func #1 -> Switch ABC to abc Key
    m_pFuncButton[__FUN_KEY_1__] = new RtKeyButton(this,__FUN_KEY_1__);
    m_pFuncButton[__FUN_KEY_1__]->SetImages(&m_Key_Switch[0],&m_Key_Switch[0]);
    m_pFuncButton[__FUN_KEY_1__]->setGeometry(FuncPoints[__FUN_KEY_1__].x(),FuncPoints[__FUN_KEY_1__].y(),m_Key_Switch[0].width(),m_Key_Switch[0].height());
    connect(m_pFuncButton[__FUN_KEY_1__], SIGNAL(clicked()), this, SLOT(switchUpperLower()));

    // Func #2 -> Delete Key
    m_pFuncButton[__FUN_KEY_2__] = new RtKeyButton(this,__FUN_KEY_2__);
    m_pFuncButton[__FUN_KEY_2__]->SetImages(&m_Key_Del[0],&m_Key_Del[0]);
    m_pFuncButton[__FUN_KEY_2__]->setGeometry(FuncPoints[__FUN_KEY_2__].x(),FuncPoints[__FUN_KEY_2__].y(),m_Key_Del[0].width(),m_Key_Del[0].height());
    connect(m_pFuncButton[__FUN_KEY_2__], SIGNAL(clicked()), this, SIGNAL(backspace()));

    // Func #3 -> Switch between ABC and 123 Key
    QString strFun3 = "?123";
    QRect rectFun3 = QRect(8,6,35,16);

    m_pFuncButton[__FUN_KEY_3__] = new RtKeyButton(this,__FUN_KEY_3__);
    m_pFuncButton[__FUN_KEY_3__]->SetImages(&m_Key7[0],&m_Key7[0]);
    m_pFuncButton[__FUN_KEY_3__]->setGeometry(FuncPoints[__FUN_KEY_3__].x(),FuncPoints[__FUN_KEY_3__].y(),m_Key7[0].width(),m_Key7[0].height());
    m_pFuncButton[__FUN_KEY_3__]->setButtonText(strFun3,rectFun3);
    connect(m_pFuncButton[__FUN_KEY_3__], SIGNAL(clicked()), this, SLOT(switchAZ09()));

    // Func #4 -> Enter Key
    m_pFuncButton[__FUN_KEY_4__] = new RtKeyButton(this,__FUN_KEY_4__);
    m_pFuncButton[__FUN_KEY_4__]->SetImages(&m_Key_Enter[0],&m_Key_Enter[0]);
    m_pFuncButton[__FUN_KEY_4__]->setGeometry(FuncPoints[__FUN_KEY_4__].x(),FuncPoints[__FUN_KEY_4__].y(),m_Key_Enter[0].width(),m_Key_Enter[0].height());

  // Func #5 -> "," Key
    QString strFun5 = ",";
    QRect rectFun5 = QRect(8,6,20,16);

    m_pFuncButton[__FUN_KEY_5__] = new RtKeyButton(this,__FUN_KEY_5__);
    m_pFuncButton[__FUN_KEY_5__]->SetImages(&m_Key3[0],&m_Key3[0]);
    m_pFuncButton[__FUN_KEY_5__]->setGeometry(FuncPoints[__FUN_KEY_5__].x(),FuncPoints[__FUN_KEY_5__].y(),m_Key3[0].width(),m_Key3[0].height());
    m_pFuncButton[__FUN_KEY_5__]->setButtonText(strFun5,rectFun5);
    m_pFuncButton[__FUN_KEY_5__]->show();
    connect(m_pFuncButton[__FUN_KEY_5__], SIGNAL(clicked()), signalMapper, SLOT(map()));
    signalMapper->setMapping(m_pFuncButton[__FUN_KEY_5__], strFun5);

  // Func #6 -> "." Key
    QString strFun6 = ".";
    QRect rectFun6 = QRect(8,6,20,16);

    m_pFuncButton[__FUN_KEY_6__] = new RtKeyButton(this,__FUN_KEY_6__);
    m_pFuncButton[__FUN_KEY_6__]->SetImages(&m_Key3[0],&m_Key3[0]);
    m_pFuncButton[__FUN_KEY_6__]->setGeometry(FuncPoints[__FUN_KEY_6__].x(),FuncPoints[__FUN_KEY_6__].y(),m_Key3[0].width(),m_Key3[0].height());
    m_pFuncButton[__FUN_KEY_6__]->setButtonText(strFun6,rectFun6);
    connect(m_pFuncButton[__FUN_KEY_6__], SIGNAL(clicked()), signalMapper, SLOT(map()));
    signalMapper->setMapping(m_pFuncButton[__FUN_KEY_6__], strFun6);

    for(int i=0;i<__FUN_NUMS__;i++)
    {
        m_pFuncButton[i]->show();
        connect(m_pFuncButton[i], SIGNAL(MousePress(int,int)), this, SLOT(MouseFuncPress(int,int)));
        connect(m_pFuncButton[i], SIGNAL(MouseRelease()), this, SLOT(MouseRelease()));
//        connect(m_pKeyButton[i], SIGNAL(ButtonClick(int)), this, SLOT(ButtonClick(int)));
    }
}
示例#15
0
KeyPad::KeyPad(LCDDisplay *lcd, QWidget *parent, const char *name )
    : QGrid(5, parent, name)
{
    int         i;
    QButton *btnButton;

    // save lcd at init
    display     = lcd;
    // Init variable
    dCurrent    = 0;
    iLenCurrent = 1;
    bIsDec      = false;
    dDecCurrent = 0;
    iPreviousOperator   = 0;
    dPreviousValue      = 0;

    // First line
    btnClear    = new QPushButton("CE/C", this, "Clear");
    btn7        = new QPushButton("7", this, "7");
    btn8        = new QPushButton("8", this, "8");
    btn9        = new QPushButton("9", this, "9");
    btnPlus     = new QPushButton("+", this, "+");
    // 2nd line
    btnBackspace = new QPushButton("<-",this, "Backspace");
    btn4        = new QPushButton("4", this, "4");
    btn5        = new QPushButton("5", this, "5");
    btn6        = new QPushButton("6", this, "6");
    btnMinus    = new QPushButton("-", this, "-");
    // 3rd line
    btnPercent  = new QPushButton("%", this, "percent");
    btn1        = new QPushButton("1", this, "1");
    btn2        = new QPushButton("2", this, "2");
    btn3        = new QPushButton("3", this, "3");
    btnMultiply = new QPushButton("X", this, "X");
    // 4th line
    btnAbout    = new QPushButton("?", this, "About");
    btn0        = new QPushButton("0", this, "0");
    btnDot      = new QPushButton(".", this, "dot");
    btnEqual    = new QPushButton("=", this, "equal");
    btnDivide   = new QPushButton("/", this, "divide");

    // Digit key
    grpbtnDigits = new QButtonGroup(0, "digits");
    grpbtnDigits->insert(btn0, 0);
    grpbtnDigits->insert(btn1, 1);
    grpbtnDigits->insert(btn2, 2);
    grpbtnDigits->insert(btn3, 3);
    grpbtnDigits->insert(btn4, 4);
    grpbtnDigits->insert(btn5, 5);
    grpbtnDigits->insert(btn6, 6);
    grpbtnDigits->insert(btn7, 7);
    grpbtnDigits->insert(btn8, 8);
    grpbtnDigits->insert(btn9, 9);

    // set appearance of buttons
    for(i=0; i<10; i++) {
        btnButton = grpbtnDigits->find(i);
        btnButton->setFixedSize(30,30);
    }

    // Operator key
    grpbtnOperators = new QButtonGroup(0, "operator");
    grpbtnOperators->insert(btnPlus, 1);
    grpbtnOperators->insert(btnMinus,2);
    grpbtnOperators->insert(btnMultiply,3);
    grpbtnOperators->insert(btnDivide,4);
    grpbtnOperators->insert(btnEqual,5);
    // set appearance of buttons
    for(i=1; i<6; i++) {
        btnButton = grpbtnOperators->find(i);
        btnButton->setFixedSize(30,30);
    }
    btnClear->setFixedSize(30,30);
    btnClear->setPalette(QPalette( QColor(255, 99, 71) ) );
    btnDot->setFixedSize(30,30);
    btnPercent->setFixedSize(30,30);
    btnBackspace->setFixedSize(30,30);
    btnAbout->setFixedSize(30,30);

    m_buttonKeys.insert(Key_0, btn0);
    m_buttonKeys.insert(Key_1, btn1);
    m_buttonKeys.insert(Key_2, btn2);
    m_buttonKeys.insert(Key_3, btn3);
    m_buttonKeys.insert(Key_4, btn4);
    m_buttonKeys.insert(Key_5, btn5);
    m_buttonKeys.insert(Key_6, btn6);
    m_buttonKeys.insert(Key_7, btn7);
    m_buttonKeys.insert(Key_8, btn8);
    m_buttonKeys.insert(Key_9, btn9);
    m_buttonKeys.insert(Key_Period, btnDot);
    m_buttonKeys.insert(Key_Plus, btnPlus);
    m_buttonKeys.insert(Key_Minus, btnMinus);
    m_buttonKeys.insert(Key_Equal, btnEqual);
    m_buttonKeys.insert(Key_Asterisk, btnMultiply);
    m_buttonKeys.insert(Key_Slash, btnDivide);
    m_buttonKeys.insert(Key_Percent, btnPercent);
    m_buttonKeys.insert(Key_Backspace, btnBackspace);

    // SIGNALS AND SLOTS
    connect(grpbtnDigits, SIGNAL(clicked(int) ), this, SLOT(enterDigits(int)));
    connect(grpbtnOperators, SIGNAL(clicked(int)), this, SLOT(operatorPressed(int)));
    connect(btnClear, SIGNAL(clicked()), this, SLOT(clearLCD()));
    connect(btnBackspace, SIGNAL(clicked()), this, SLOT(backspace()));
    connect(btnAbout, SIGNAL(clicked()), this, SLOT(aboutDialog()));
    connect(btnDot, SIGNAL(clicked()), this, SLOT(gotoDec()));
    connect(display, SIGNAL(keyPressed(int)), SLOT(slotKeyPressed(int)));
    connect(display, SIGNAL(keyReleased(int)), SLOT(slotKeyReleased(int)));
}
示例#16
0
void iKeyboard(unsigned char key)
{
	upArrow = 0;
	downArrow=0;		//set arrow flags off

	//retrieve charactre index in terms of cursor position
	j = x/ charSpace;
	i = ((height-15-lineSpace - y)/lineSpace) + s;		


	if (glutGetModifiers() == GLUT_ACTIVE_CTRL)				//ALT key operations
	{
		if (key == 1)							//select all
		{
			selectAll();
		}
		else if (key == 3 )				//copy
		{
			copy();
		}
		else if (key==15)			//file open	
		{
			fOpen =1;
			subTemp = (char *)calloc(60,sizeof(char));
			x = (width-15)/2-135;
			y = (height-19)/2+61;
			menuflag = 0;
		}
		else if (key==16)			//file save as
		{
			save();
			char tempfile[80];
			strcpy(tempfile, syspath);
			strcat(tempfile, ":\\Program Files\\Rword\\saved_files\\");
			strcat(tempfile, filename);
			ShellExecute(NULL, "print", tempfile, NULL, NULL, NULL);		//print document
			menuflag = 0;
		}
		else if (key==19)			//file save
		{
			save();
			menuflag = 0;
		}
		else if (copyFlag &&  key==22)		//paste
		{
			paste();
		}
		else if (key == 24 )			//cut
		{
			cut();
		}
	}
	else if(key >31 && key <127)		//character input
	{
		
		if (fOpen || fsave)
		{
			subCharacter(key);				//for popups
		}
		else
		{
			if (selflag)
				seldel();
			character(key);							// main character input
		}
	}
	else if (key == '\b')				//backspace
	{
		
		if (fOpen || fsave)				//popup
		{
			if (strlen(subTemp))
			{
				subTemp[strlen(subTemp)-1] = '\0';
				if (strlen(subTemp)>33)
					r--;
				else
					x -= 8;
			}
		}
		else
		{
			if (selflag)
				seldel();
			else
				backspace();				//main
		}
	}	
	else if (key == 127)			//del
	{
		if (selflag)
			seldel();
		else
			del();
	}
	else if (key == '\r')			//enter operations
	{	
		if (fOpen)					
		{
			if (selflag)
				seldel();

			open();
		}
		else if (fsave)
		{
			saveas();				//popups
		}
		else
		{
			if (selflag)
				seldel();
			else
				enter();				//main
		}
	}
	else if (key == '\t')			//incomplete
	{
		selflag = 0;
		tab();
	}
}
示例#17
0
bool TextField::handle(Event& e) {

	static bool shiftDown = false;

	KeyEvent* ke = dynamic_cast<KeyEvent*>(&e);
	if (ke) {
		if (ke->info.key == "KEY_SHIFT_L") {
			shiftDown = ke->info.pressed;
		}

		if (ke->info.pressed) {

			if (ke->info.key == "KEY_BACKSPACE") {
				backspace(ke->info);

			} else if (ke->info.key == "KEY_ARROW_LEFT") {
				cursorMoveStrategy->moveCursor(this, CursorDirection::LEFT, ke->info);

			} else if (ke->info.key == "KEY_ARROW_RIGHT") {
				cursorMoveStrategy->moveCursor(this, CursorDirection::RIGHT, ke->info);

			} else if (ke->info.key == "KEY_A" && ke->info.ctrl) {
				marker = 0;
				cursor = text.length();
				markFor(COMPONENT_REQUIREMENT_PAINT);

			} else {
				char c = g_keyboard::charForKey(ke->info);

				if (c != -1) {
					std::stringstream s;
					s << c;
					insert(s.str());
				}
			}
		}
		return true;
	}

	FocusEvent* fe = dynamic_cast<FocusEvent*>(&e);
	if (fe) {
		if (fe->type == FOCUS_EVENT_GAINED) {
			focused = true;
		} else {
			focused = false;
		}
		markFor(COMPONENT_REQUIREMENT_PAINT);
		return true;
	}

	MouseEvent* me = dynamic_cast<MouseEvent*>(&e);
	if (me) {
		if (me->type == MOUSE_EVENT_ENTER) {
			visualStatus = TextFieldVisualStatus::HOVERED;
			markFor(COMPONENT_REQUIREMENT_PAINT);
			Cursor::set("text");

		} else if (me->type == MOUSE_EVENT_LEAVE) {
			visualStatus = TextFieldVisualStatus::NORMAL;
			markFor(COMPONENT_REQUIREMENT_PAINT);
			Cursor::set("default");

		} else if (me->type == MOUSE_EVENT_PRESS) {

			g_point p = me->position;
			int clickCursor = viewToPosition(p);

			if (me->clickCount > 2) {
				marker = 0;
				cursor = text.length();

			} else if (me->clickCount == 2) {
				marker = cursorMoveStrategy->calculateSkip(text, clickCursor, CursorDirection::LEFT);
				cursor = cursorMoveStrategy->calculateSkip(text, clickCursor, CursorDirection::RIGHT);

			} else {
				cursor = clickCursor;
				if (!shiftDown) {
					marker = cursor;
				}
			}

			markFor(COMPONENT_REQUIREMENT_PAINT);

		} else if (me->type == MOUSE_EVENT_DRAG) {
			g_point p = me->position;
			cursor = viewToPosition(p);
			markFor(COMPONENT_REQUIREMENT_PAINT);
		}

		return true;
	}

	return false;
}
示例#18
0
文件: label.cpp 项目: atondwal/Core
bool UILabel::keyPress(SDL_KeyboardEvent *e, char c) {

    if(!c) return false;

    if(!editable) {

        switch(c) {
            case SDLK_RETURN:
                if(submit()) return true;
                break;
        }

        return false;
    }

    // copy / paste clipboard
    if(e->keysym.sym == SDLK_v || e->keysym.sym == SDLK_c) {

        Uint8* keystate = SDL_GetKeyState(0);

        if(keystate[SDLK_LCTRL]) {

            if(e->keysym.sym == SDLK_c) {

                if(!this->text.empty()) {
                    SDLApp::setClipboardText(this->text);
                    return true;
                }

            } else if(e->keysym.sym == SDLK_v) {

                std::string text;
                if(SDLApp::getClipboardText(text)) {
                    setText(this->text + text);
                    return true;
                }
            }

            return false;
        }
    }

    switch(c) {
#ifdef __APPLE__
        case SDLK_DELETE:
#else
	case SDLK_BACKSPACE:
#endif
            backspace();
            break;
        case SDLK_TAB:
            tab();
            break;
        case SDLK_RETURN:
            submit();
            break;
        default:
            text += c;
            break;
    }

    text_changed = true;

    return true;
}
示例#19
0
文件: input.c 项目: pollyzoid/psh
bool read_input(input_state* inp, char* buf) {
	char c = 0;
	int len, cursor;
	int i;
	int hislen;
	int hispos = 0;

	cursor = inp->cursor;
	len = strlen(buf);

	while (true) {
		if (!read(0, &c, 1)) {
			inp->cursor = cursor;
			return false;
		}

		switch(c) {
		case '\n':
			return true;
		case '\b':
		case DEL:
			backspace(buf, &cursor, &len);
			break;
		case ESC: /* escape char */
			if (!read(0, &c, 1)) {
				inp->cursor = cursor;
				return false;
			}

			if (c == '[') {
				if (!read(0, &c, 1)) {
					inp->cursor = cursor;
					return false;
				}
				switch(c) {
				case 'A': /* up */
					hislen = history_travel(inp, buf, cursor, hispos, false);
					if (hislen) {
						++hispos;
						cursor = len = hislen;
					}
					break;
				case 'B': /* down */
					hislen = history_travel(inp, buf, cursor, hispos, true);
					if (hislen) {
						--hispos;
						cursor = len = hislen;
					}
					break;
				case 'C': /* right */
					if (cursor < len) {
						++cursor;
						fputs("\033[C", stdout);
						fflush(stdout);
					}
					break;
				case 'D': /* left */
					if (cursor > 0) {
						--cursor;
						fputs("\033[D", stdout);
						fflush(stdout);
					}
					break;
				case '1': /* Ctrl-A */
					break;
				case '4': /* Ctrl-E */
					break;
				}
			}
			break;
		default:
			if (!isprint(c)) /* skip non-printables */
				break;

			/* leave room for null terminator */
			if (len >= (BUFFER_MAX_LENGTH - 1))
				break;

			if (cursor == len) { /* EOL, append */
				buf[cursor] = c;
			} else { /* insert */
				memmove(&buf[cursor + 1], &buf[cursor], len - cursor);

				buf[cursor] = c;

				/* write the changed rest of the line */
				for (i = cursor; i <= len; ++i)
					putc(buf[i], stdout);
				for (; i > cursor; --i) /* move cursor back to original pos */
					fputs("\033[D", stdout);
			}

			++cursor;
			++len;

			putc(c, stdout);
			fflush(stdout);
			break;
		}
	}
}
示例#20
0
/* keyboard_handler()
   An Interrupt Handler that is Called When 
   Key is Pressed on Keyboard
   Input : i -- interrupt vector
   Output : None
   Side Effect : Handle keypress functions
   				 Prints keys Pressed to Screen accordingly
                 Issue EOI(End Of Interrupt) to unmask keyboard interrupt 
*/
void keyboard_handler(int i)
{
	/* Grab Key Pressed*/
	uint8_t keycode;
	keycode = kbd_read_input();

	/* Indicate a key has been pressed */
	key_press = 1;
	int32_t display_terminal= get_displayed_terminal();

	/* Print Only Keys Pressed, NOT Key Release 
	 * No Print for CTRL/SHIFT/Backspace/Caps
	 * Carries out Functionality Instead */
	if(keycode <= KEY_RELEASE_VALUE){
		/* Condition Key Press */
		if (keycode == ALT)
			alt_press += 1;
		else if(keycode == L_SHIFT || keycode == R_SHIFT)	
			shift_press += 1;
		else if (keycode == CTRL)
			ctrl_press += 1;
		else if (keycode == CAPS_LOCK)
			caps_on = !caps_on;

		/* CTRL-L Clear Screen */
		else if(keycode == L && ctrl_press > 0)
			reset_screen();

		/* Backspace */
		else if (keycode == BACKSPACE){
			/* Don't backspace when reading and at start of buffer*/
			if(read_on[display_terminal] == 0 || (index[display_terminal] != 0 && read_on[display_terminal] == 1))
				backspace();
			update_terminal_buf(BACK,keycode);
		}

		/* Return Press During Read */
		else if (read_on[display_terminal] == 1 && keycode == RETURN){
			printf("\n"); 		// New Line for Return Press
			read_return[display_terminal] = 1;
			update_terminal_buf(KEYS,keycode);
		}
		
		/* ALT-Function Press */
		else if(alt_press > 0 && (keycode == F1 || keycode == F2 || keycode == F3)){
			switch(keycode){
				case F1:
					change_terminal(TERMINAL_1);
					break;
				case F2:
					change_terminal(TERMINAL_2);
					break;
				case F3:
					change_terminal(TERMINAL_3);
				default:
					break;
			}
		}

		/* Caps On */
		else if (caps_on == 1){
			caps_on_handler(keycode);
		}

		/* Shift Press */
		else if (shift_press > 0){
			printf("%c", shift_keys[keycode - 1]);
			update_terminal_buf(SHIFT_KEYS, keycode);
		}

		/* Normal Press */
		else{
			printf("%c", keys[keycode - 1]);
			update_terminal_buf(KEYS, keycode);
		}

	}

	/* Condition Key Releases */
	else if (keycode == (ALT + KEY_RELEASE_VALUE))
		alt_press -= 1;
	else if(keycode == (L_SHIFT + KEY_RELEASE_VALUE) || keycode == (R_SHIFT + KEY_RELEASE_VALUE))
		shift_press -= 1;
	else if (keycode == (CTRL + KEY_RELEASE_VALUE))
		ctrl_press -= 1;

	/* Key Press Serviced */
	key_press = 0;
	send_eoi(KEYBOARD_IRQ);
}
示例#21
0
int
trans_string(char *ptr)
{
	register int	count = 0;
	int		number;
	register int	i;
	register int	ch;

	while ((ch = next_char()) != ',' && ch != EOF && !first_column) {
	    if (ch == '^') {
		ch = next_char();
		if (ch == EOF)
		    err_abort("Premature EOF");

		if (!isascii(ch) || ! isprint(ch)) {
		    warning("Illegal ^ character - '%c'", ch);
		}

		if (ch == '@')
		    *(ptr++) = 0200;
		else
		    *(ptr++) = ch & 037;
	    } else if (ch == '\\') {
		ch = next_char();
		if (ch == EOF)
		    err_abort("Premature EOF");

		if (ch >= '0' && ch <= '7') {
		    number = ch - '0';
		    for (i = 0; i < 2; i++) {
			ch = next_char();
			if (ch == EOF)
			    err_abort("Premature EOF");

			if (ch < '0' || ch > '7') {
			    backspace();
			    break;
			}

			number = number * 8 + ch - '0';
		    }

		    if (number == 0)
			number = 0200;
		    *(ptr++) = (char)number;
		} else {
		    switch (ch) {
			case 'E':
			case 'e':	*(ptr++) = '\033';	break;

			case 'l':
			case 'n':	*(ptr++) = '\n';	break;

			case 'r':	*(ptr++) = '\r';	break;

			case 'b':	*(ptr++) = '\010';	break;

			case 's':	*(ptr++) = ' ';		break;

			case 'f':	*(ptr++) = '\014';	break;

			case 't':	*(ptr++) = '\t';	break;

			case '\\':	*(ptr++) = '\\';	break;

			case '^':	*(ptr++) = '^';		break;

			case ',':	*(ptr++) = ',';		break;

			case ':':	*(ptr++) = ':';		break;

			default:
			    warning("Illegal character in \\ sequence - '%c'",
				ch);
			    *(ptr++) = ch;
		    } /* endswitch (ch) */
		} /* endelse (ch < '0' ||  ch > '7') */
	    } /* end else if (ch == '\\') */
	    else {
		if (ch != '\n') *(ptr++) = ch;
	    }

	    count ++;

	    if (count > 1000)
		warning("Very long string found.  Missing comma?");
	} /* end while */

	if (ch == EOF)
	    warning("Premature EOF - missing comma?");
	/* start of new description */
	else if (first_column) {
	    backspace();
	    warning("Missing comma?");
	    /* pretend we did get a comma */
	    ch = ',';
	}

	*ptr = '\0';

	if (count == 0)
		return (NULL);
	return (ch);
}
示例#22
0
/**
 * checks if the key is a valid command
 * @return true if a command was completed and executed, false otherwise
 */
bool KateViReplaceMode::handleKeypress( const QKeyEvent *e )
{
  // backspace should work even if the shift key is down
  if (e->modifiers() != Qt::ControlModifier && e->key() == Qt::Key_Backspace ) {
    backspace();
    return true;
  }

  KTextEditor::Cursor c( m_view->cursorPosition() );

  if ( e->modifiers() == Qt::NoModifier ) {
    switch ( e->key() ) {
    case Qt::Key_Escape:
      m_overwritten.clear();
      startNormalMode();
      return true;
      break;
    case Qt::Key_Left:
      m_overwritten.clear();
      m_view->cursorLeft();
      return true;
    case Qt::Key_Right:
      m_overwritten.clear();
      m_view->cursorRight();
      return true;
    case Qt::Key_Up:
      m_overwritten.clear();
      m_view->up();
      return true;
    case Qt::Key_Down:
      m_overwritten.clear();
      m_view->down();
      return true;
    case Qt::Key_Home:
      m_overwritten.clear();
      m_view->home();
      return true;
    case Qt::Key_End:
      m_overwritten.clear();
      m_view->end();
      return true;
    case Qt::Key_PageUp:
      m_overwritten.clear();
      m_view->pageUp();
      return true;
    case Qt::Key_PageDown:
      m_overwritten.clear();
      m_view->pageDown();
      return true;
    case Qt::Key_Delete:
      m_view->keyDelete();
      return true;
    case Qt::Key_Insert:
      startInsertMode();
      return true;
    default:
      return false;
      break;
    }
  } else if ( e->modifiers() == Qt::ControlModifier ) {
    switch( e->key() ) {
    case Qt::Key_BracketLeft:
    case Qt::Key_C:
      startNormalMode();
      return true;
      break;
    case Qt::Key_E:
      commandInsertFromLine( 1 );
      return true;
      break;
    case Qt::Key_Y:
      commandInsertFromLine( -1 );
      return true;
      break;
    case Qt::Key_Left:
      m_overwritten.clear();
      commandMoveOneWordLeft();
      return true;
      break;
    case Qt::Key_Right:
      m_overwritten.clear();
      commandMoveOneWordRight();
      return true;
      break;
    default:
      return false;
    }
  }

  return false;
}
示例#23
0
static void TermCompletionOnAll(char *lineBeforeCaret, char *lineAfterCaret, char *defaultPattern, char **wk_buf, unsigned int *cursor,
                                unsigned int *cursor_max)
{
    if (defaultPattern)
    {
        int numberWordFound = 0;

        char **completionDictionaryFunctions = NULL;

        int sizecompletionDictionaryFunctions = 0;

        char **completionDictionaryCommandWords = NULL;

        int sizecompletionDictionaryCommandWords = 0;

        char **completionDictionaryMacros = NULL;

        int sizecompletionDictionaryMacros = 0;

        char **completionDictionaryVariables = NULL;

        int sizecompletionDictionaryVariables = 0;

        char **completionDictionaryHandleGraphicsProperties = NULL;

        int sizecompletionDictionaryHandleGraphicsProperties = 0;

        char **completionDictionaryFields = NULL;

        int sizecompletionDictionaryFields = 0;

        completionDictionaryFields = completionOnFields(lineBeforeCaret, defaultPattern, &sizecompletionDictionaryFields);

        if (!completionDictionaryFields && strcmp(defaultPattern, ""))
        {
            completionDictionaryFunctions = completionOnFunctions(defaultPattern, &sizecompletionDictionaryFunctions);
            completionDictionaryCommandWords = completionOnCommandWords(defaultPattern, &sizecompletionDictionaryCommandWords);
            completionDictionaryMacros = completionOnMacros(defaultPattern, &sizecompletionDictionaryMacros);
            completionDictionaryVariables = completionOnVariablesWithoutMacros(defaultPattern, &sizecompletionDictionaryVariables);
            completionDictionaryHandleGraphicsProperties =
                completionOnHandleGraphicsProperties(defaultPattern, &sizecompletionDictionaryHandleGraphicsProperties);
        }

        numberWordFound = sizecompletionDictionaryFunctions + sizecompletionDictionaryCommandWords +
                          sizecompletionDictionaryMacros + sizecompletionDictionaryVariables +
                          sizecompletionDictionaryHandleGraphicsProperties + sizecompletionDictionaryFields;

        if (numberWordFound > 0)
        {
            if (numberWordFound == 1)
            {
                char **completionDictionary = NULL;

                char *new_line = NULL;

                if (completionDictionaryFields)
                {
                    completionDictionary = completionDictionaryFields;
                }
                if (completionDictionaryFunctions)
                {
                    completionDictionary = completionDictionaryFunctions;
                }
                if (completionDictionaryCommandWords)
                {
                    completionDictionary = completionDictionaryCommandWords;
                }
                if (completionDictionaryMacros)
                {
                    completionDictionary = completionDictionaryMacros;
                }
                if (completionDictionaryVariables)
                {
                    completionDictionary = completionDictionaryVariables;
                }
                if (completionDictionaryHandleGraphicsProperties)
                {
                    completionDictionary = completionDictionaryHandleGraphicsProperties;
                }

                new_line = completeLine(lineBeforeCaret, completionDictionary[0], NULL, defaultPattern, FALSE, lineAfterCaret);
                if (new_line)
                {
                    char buflinetmp[WK_BUF_SIZE + 1];

                    strcpy(buflinetmp, new_line);
                    FREE(new_line);

                    backspace(*cursor);
                    erase_nchar(*cursor_max);
                    *cursor = *cursor_max = 0;

                    CopyLineAtPrompt(wk_buf, buflinetmp, cursor, cursor_max);
                }

                freeArrayOfString(completionDictionary, 1);
            }
            else
            {
                char *commonAll = NULL;

                if (completionDictionaryFields)
                {
                    commonAll = getCommonPart(completionDictionaryFields, sizecompletionDictionaryFields);
                    displayCompletionDictionary(completionDictionaryFields, sizecompletionDictionaryFields, (char *)_("Scilab Fields"));
                    freeArrayOfString(completionDictionaryFields, sizecompletionDictionaryFields);
                }
                else
                {
                    char *commonFunctions = getCommonPart(completionDictionaryFunctions, sizecompletionDictionaryFunctions);

                    char *commonCommandWords = getCommonPart(completionDictionaryCommandWords, sizecompletionDictionaryCommandWords);

                    char *commonMacros = getCommonPart(completionDictionaryMacros, sizecompletionDictionaryMacros);

                    char *commonVariables = getCommonPart(completionDictionaryVariables, sizecompletionDictionaryVariables);

                    char *commonHandleGraphicsProperties =
                        getCommonPart(completionDictionaryHandleGraphicsProperties, sizecompletionDictionaryHandleGraphicsProperties);

                    int sizecommonsDictionary = 0;

                    char **commonsDictionary = concatenateStrings(&sizecommonsDictionary, commonFunctions,
                                               commonMacros, commonCommandWords, commonVariables, commonHandleGraphicsProperties);

                    if (sizecommonsDictionary > 0)
                    {
                        if (sizecommonsDictionary == 1)
                        {
                            commonAll = strdup(commonsDictionary[0]);
                        }
                        else
                        {
                            commonAll = getCommonPart(commonsDictionary, sizecommonsDictionary);
                        }
                        freeArrayOfString(commonsDictionary, sizecommonsDictionary);
                    }

                    displayCompletionDictionary(completionDictionaryFunctions, sizecompletionDictionaryFunctions, (char *)_("Scilab Function"));
                    displayCompletionDictionary(completionDictionaryCommandWords, sizecompletionDictionaryCommandWords, (char *)_("Scilab Command"));
                    displayCompletionDictionary(completionDictionaryMacros, sizecompletionDictionaryMacros, (char *)_("Scilab Macro"));
                    displayCompletionDictionary(completionDictionaryVariables, sizecompletionDictionaryVariables, (char *)_("Scilab Variable"));
                    displayCompletionDictionary(completionDictionaryHandleGraphicsProperties, sizecompletionDictionaryHandleGraphicsProperties,
                                                (char *)_("Graphics handle field"));
                    freeArrayOfString(completionDictionaryFunctions, sizecompletionDictionaryFunctions);
                    freeArrayOfString(completionDictionaryCommandWords, sizecompletionDictionaryCommandWords);
                    freeArrayOfString(completionDictionaryMacros, sizecompletionDictionaryMacros);
                    freeArrayOfString(completionDictionaryVariables, sizecompletionDictionaryVariables);
                    freeArrayOfString(completionDictionaryHandleGraphicsProperties, sizecompletionDictionaryHandleGraphicsProperties);
                }

                printf("\n");

                backspace(*cursor);
                erase_nchar(*cursor_max);
                *cursor = *cursor_max = 0;

                printPrompt(WRITE_PROMPT);

                if (commonAll)
                {
                    char *new_line = NULL;

                    new_line = completeLine(lineBeforeCaret, commonAll, NULL, defaultPattern, FALSE, lineAfterCaret);
                    if (new_line)
                    {
                        char buflinetmp[WK_BUF_SIZE + 1];

                        strcpy(buflinetmp, new_line);
                        FREE(new_line);

                        CopyLineAtPrompt(wk_buf, buflinetmp, cursor, cursor_max);
                    }

                    FREE(commonAll);
                    commonAll = NULL;
                }
            }
        }
    }
}
示例#24
0
void check_char(char* feed)
{
	int i;
	char* output;
	
	switch (feed[0])
	{
		case 1:
		//	my_str("Ctrl+A pressed.\n");
			ctrlA();
			break;
		case 3: 
		//	my_str("Ctrl+C pressed.\n");
			ctrlC();
			break;
		case 5: 
		//	my_str("Ctrl+E pressed.\n"); 
			ctrlE(); 
			break;
		case 11:
		//	my_str("Ctrl+K pressed.\n");
			ctrlK();
			break;
		case 12:
		//	my_str("Ctrl+L pressed.\n");
			ctrlL();
			break;
		case 25:
		//	my_str("Ctrl+Y pressed.\n");
			ctrlY();
			break;
		case 27:
			switch (feed[2])
			{
				case 'B':
				//	my_str("Down arrow pressed.\n");
					down();
					break;
                        	case 'A':
				//	my_str("Up arrow pressed.\n");
					up();
					break;
                        	case 'D':
				//	my_str("Left arrow pressed.\n");
					left();
					break;
                        	case 'C':
				//	my_str("Right arrow pressed.\n");
					right();
					break;
			} break;
		case 8:
		//	my_str("Backspace pressed.\n");
			backspace();
			break;
		case 10:
		//	my_str("Enter pressed.\n");
			enter();
			break;
		case 127:
		//	my_str("Delete pressed.\n");
			backspace();
			break;
		default:
			my_char(feed[0]);
			gl_env.cmd[gl_env.cmdlength++] = feed[0];	
			gl_env.x++;
			break;
	}
}
    int main(int argc, char *argv[])
    {
    int c,x,y;
    FILE *fp;
        // If file name is not given close the program
        if(argc!=2)
        {
            printf("file name missing \n");
            exit(1);
        }
        // Start curses mode
		if (initscr() == NULL)
		{
                	fprintf(stderr, "Could not initialize screen\n");
                	exit(EXIT_FAILURE);
    	    	}
    	    	keypad(stdscr, TRUE);       // raw mode ON
    	    	noecho();                   // echo mode OFF
		        cbreak();                   //Line buffering disabled, every character enabled
    	    	scrollok(stdscr, TRUE);     // scrolling mode ON
		        refresh();
                fp=fopen(argv[1],"r+");
        if(!fp)//if the file does not exist, create it
        {
            fp=fopen(argv[1],"w+");
            if(fp==NULL)
            {
            printw("Error opening file");
            refresh();
            exit(1);
		    endwin();
            }
        }
        else
        {
            long map;
            long end;
		    read_file(fp);
            /*map and end coincides when we read the file*/
            map=ftell(fp);
            end=ftell(fp);
            while((c=getch())!= KEY_ESC)
	      {
		    switch(c)
              	{
                case KEY_F(1):      //undo insert tab
                    break;
                case KEY_F(2):
                break;
                case KEY_F(3):
                    break;
                case KEY_F(4):
                    break;
                case KEY_F(5):
                break;
                case KEY_F(6):
                    break;
                case KEY_F(7):
                    break;
                case KEY_F(8):
                break;
                case KEY_F(9):
                    break;
                case KEY_F(10):
                    break;
                case KEY_EOS:
                fp=fopen(argv[1],"w+");
		        read_file(fp);
                break;
                case KEY_HOME://It will bring to the beginning of the file
		            nocbreak();
		            noecho();
		            getyx(stdscr,y,x);
		            move(y,0);
		            cbreak();
		            refresh();
                    fseek(fp,0,SEEK_SET);
                    break;
                case KEY_UP:
		        nocbreak();
		        noecho();
		        getyx(stdscr,y,x);
		        move(y-1,x);
		        cbreak();
		        refresh();
                break;
                case KEY_PPAGE:
                    break;
                case KEY_IC:
                   overtype_mode=true;
                    break;
                case KEY_EIC:
                    overtype_mode=false;
                    map=0;
                    break;
                case KEY_LEFT:
                refresh();
		           nocbreak();
		           noecho();
		           getyx(stdscr,y,x);
		           move(y,x-1);
		           cbreak();
		           refresh();
                   fseek(fp,-1,SEEK_CUR);
                   map=ftell(fp);
                   break;
                case KEY_RIGHT:
                   nocbreak();
		    	   noecho();
		    	   getyx(stdscr,y,x);
		    	   move(y,x+1);
		    	   cbreak();
		           refresh();
                   fseek(fp,+1,SEEK_CUR);
                   map=ftell(fp);
                  	break;
                case KEY_DOWN:
                    nocbreak();
 	            	noecho();
 		            getyx(stdscr,y,x);
 		            move(y+1,x);
                	cbreak();
                	refresh();
 		            break;
                case KEY_NPAGE:
                    getbegyx(stdscr,y,x);
                    move(y+1,x);
                    erase();
                    refresh();
                    read_file(fp);
                    erase();
                    printw("wordcount: %d \t",ftell(fp));
                    refresh();
                    break;
                case KEY_BACKSPACE:  //backspace function implemented instead
		    	    fseek(fp,0,SEEK_CUR);
                    map=ftell(fp);
		    	    fseek(fp,0,SEEK_END);
                    end=ftell(fp);
                    backspace(fp,argv[1],map,end);
		    	    fseek(fp,map-1,SEEK_SET);
                    break;
                default: // write to the file
		    	    fseek(fp,0,SEEK_CUR);
                    map=ftell(fp);
		    	    fseek(fp,0,SEEK_END);
                    end=ftell(fp);
                    write_file(fp,overtype_mode,c,map,end);
                }
	      }
		  refresh();
		  fclose(fp);
          fp=NULL;
		  endwin();
	}
        return 0;
    }
示例#26
0
static void
my_homegrown_redisplay(int hide_passwords)
{
  static int line_start = 0;    /* at which position of prompt_plus_line does the printed line start? */
  static int line_extends_right = 0;
  static int line_extends_left = 0;
  static char *previous_line = NULL;
  
  
  int width = winsize.ws_col;
  int skip = max(1, min(width / 5, 10));        /* jumpscroll this many positions when cursor reaches edge of terminal */
  
  char *prompt_without_ignore_markers;
  int colourless_promptlen = colourless_strlen(rl_prompt, &prompt_without_ignore_markers);
  int promptlen = strlen(prompt_without_ignore_markers);
  int invisible_chars_in_prompt = promptlen - colourless_promptlen;
  char *prompt_plus_line = add2strings(prompt_without_ignore_markers, rl_line_buffer);
  char *new_line;
  int total_length = strlen(prompt_plus_line);
  int curpos = promptlen + rl_point; /* cursor position within prompt_plus_line */
  int i, printed_length,
    new_curpos,                    /* cursor position on screen */
    keep_old_line, vlinestart, printwidth, last_column;
  DPRINTF3(DEBUG_AD_HOC,"rl_prompt: <%s>, prompt_without_ignore_markers: <%s>,  prompt_plus_line: <%s>", rl_prompt, prompt_without_ignore_markers, prompt_plus_line);   

  /* In order to handle prompt with colour we either print the whole prompt, or start past it:
     starting in the middle is too difficult (i.e. I am too lazy) to get it right.
     We use a "virtual line start" vlinestart, which is the number of invisible chars in prompt in the former case, or
     linestart in the latter (which then must be >= strlen(prompt))

     At all times (before redisplay and after) the following is true:
     - the cursor is at column (curpos - vlinestart) (may be < 0 or > width)
     - the character under the cursor is prompt_plus_line[curpos]
     - the character at column 0 is prompt_plus_line[linestart]
     - the last column is at <number of printed visible or invisible chars> - vlinestart
     
     the goal of this function is to display (part of) prompt_plus_line such
     that the cursor is visible again */
     
  
  if (hide_passwords)
    for (i = promptlen; i < total_length; i++)
      prompt_plus_line[i] = '*';        /* hide a pasword by making user input unreadable  */


  if (rl_point == 0)            /* (re)set  at program start and after accept_line (where rl_point is zeroed) */
    line_start = 0;
  assert(line_start == 0 || line_start >= promptlen); /* the line *never* starts in the middle of the prompt (too complicated to handle)*/
  vlinestart = (line_start > promptlen ? line_start : invisible_chars_in_prompt); 
  

  if (curpos - vlinestart > width - line_extends_right) /* cursor falls off right edge ?   */
    vlinestart = (curpos - width + line_extends_right) + skip;  /* jumpscroll left                 */

  else if (curpos < vlinestart + line_extends_left) {   /* cursor falls off left edge ?    */
    if (curpos == total_length) /* .. but still at end of line?    */
      vlinestart = max(0, total_length - width);        /* .. try to display entire line   */
    else                        /* in not at end of line ..        */
      vlinestart = curpos - line_extends_left - skip; /* ... jumpscroll right ..         */
  }     
  if (vlinestart <= invisible_chars_in_prompt) {
    line_start = 0;             /* ... but not past start of line! */
    vlinestart = invisible_chars_in_prompt;
  } else if (vlinestart > invisible_chars_in_prompt && vlinestart <= promptlen) {
    line_start = vlinestart = promptlen;
  } else {
    line_start = vlinestart;
  }

  printwidth = (line_start > 0 ? width : width + invisible_chars_in_prompt);
  printed_length = min(printwidth, total_length - line_start);  /* never print more than width     */
  last_column = printed_length - vlinestart;


  /* some invariants :     0 <= line_start <= curpos <= line_start + printed_length <= total_length */
  /* these are interesting:   ^                                                      ^              */

  assert(0 <= line_start);
  assert(line_start <= curpos);
  assert(curpos <= line_start + printed_length);        /* <=, rather than <, as cursor may be past eol   */
  assert(line_start + printed_length <= total_length);


  new_line = prompt_plus_line + line_start;
  new_line[printed_length] = '\0';
  new_curpos = curpos - vlinestart;

  /* indicate whether line extends past right or left edge  (i.e. whether the "interesting
     inequalities marked ^ above are really unequal) */

  line_extends_left = (line_start > 0 ? 1 : 0);
  line_extends_right = (total_length - vlinestart > width ? 1 : 0);
  if (line_extends_left)
    new_line[0] = '<';
  if (line_extends_right)
    new_line[printwidth - 1] = '>';

  DPRINTF0(DEBUG_AD_HOC, "In the middle...");

  keep_old_line = FALSE;
  if (term_cursor_hpos) {
    if (previous_line && strcmp(new_line, previous_line) == 0) {
      keep_old_line = TRUE;
    } else {
      if (previous_line)
        free(previous_line);
      previous_line = mysavestring(new_line);
    }
  }


  if (!keep_old_line) {
    clear_line();
    cr();
    write_patiently(STDOUT_FILENO, new_line, printed_length, "to stdout");
  }
  
  assert(term_cursor_hpos || !keep_old_line);   /* if we cannot position cursor, we must have reprinted ... */

  if (term_cursor_hpos)
    cursor_hpos(new_curpos);
  else                          /* ... so we know we're 1 past last position on line */
    backspace(last_column - new_curpos);
  free(prompt_plus_line);
  free(prompt_without_ignore_markers);
}
示例#27
0
文件: console.c 项目: geek-li/flinux
static size_t console_write(struct file *f, const char *buf, size_t count)
{
	struct console_file *console_file = (struct console_file *)f;

	console_lock();
	console_retrieve_state();
	#define OUTPUT() \
		if (last != -1) \
		{ \
			write_normal(buf + last, i - last); \
			last = -1; \
		}
	size_t last = -1;
	size_t i;
	for (i = 0; i < count; i++)
	{
		char ch = buf[i];
		if (ch == 0x1B) /* Escape */
		{
			OUTPUT();
			console->processor = control_escape;
		}
		else if (ch == '\t')
		{
			OUTPUT();
			int x = (console->x + 8) & ~7;
			if (x < console->width)
				set_pos(x, console->y);
			else
				set_pos(console->width - 1, console->y);
		}
		else if (ch == '\b')
		{
			OUTPUT();
			backspace(FALSE);
		}
		else if (ch == '\r')
		{
			OUTPUT();
			if (console->termios.c_oflag & OCRNL)
				nl();
			else
				cr();
		}
		else if (ch == '\n' || ch == '\v' || ch == '\f')
		{
			OUTPUT();
			if (console->termios.c_oflag & ONLCR)
				crnl();
			else
				nl();
		}
		else if (ch == 0x0E || ch == 0x0F)
		{
			/* Shift In and Shift Out */
			OUTPUT();
		}
		else if (console->processor)
			console->processor(ch);
		else if (ch < 0x20)
		{
			OUTPUT();
			log_error("Unhandled control character '\\x%x'\n", ch);
		}
		else if (last == -1)
			last = i;
	}
	OUTPUT();
	/* This will make the caret immediately visible */
	set_pos(console->x, console->y);
	console_unlock();
#if 0
	char str[4096];
	memcpy(str, buf, count);
	str[count] = '\n';
	str[count + 1] = 0;
	log_debug(str);
#endif
	return count;
}
示例#28
0
void KLineEdit::keyPressEvent( QKeyEvent *e )
{
    KKey key( e );

    if ( KStdAccel::copy().contains( key ) )
    {
        copy();
        return;
    }
    else if ( KStdAccel::paste().contains( key ) )
    {
        paste();
        return;
    }
    else if ( KStdAccel::pasteSelection().contains( key ) )
    {
        QString text = QApplication::clipboard()->text( QClipboard::Selection);
        insert( text );
        deselect();
        return;
    }

    else if ( KStdAccel::cut().contains( key ) )
    {
        cut();
        return;
    }
    else if ( KStdAccel::undo().contains( key ) )
    {
        undo();
        return;
    }
    else if ( KStdAccel::redo().contains( key ) )
    {
        redo();
        return;
    }
    else if ( KStdAccel::deleteWordBack().contains( key ) )
    {
        cursorWordBackward(true);
        if ( hasSelectedText() )
            del();

        e->accept();
        return;
    }
    else if ( KStdAccel::deleteWordForward().contains( key ) )
    {
        // Workaround for QT bug where
        cursorWordForward(true);
        if ( hasSelectedText() )
            del();

        e->accept();
        return;
    }
    else if ( KStdAccel::backwardWord().contains( key ) )
    {
      cursorWordBackward(false);
      e->accept();
      return;
    }
    else if ( KStdAccel::forwardWord().contains( key ) )
    {
      cursorWordForward(false);
      e->accept();
      return;
    }
    else if ( KStdAccel::beginningOfLine().contains( key ) )
    {
      home(false);
      e->accept();
      return;
    }
    else if ( KStdAccel::endOfLine().contains( key ) )
    {
      end(false);
      e->accept();
      return;
    }


    // Filter key-events if EchoMode is normal and
    // completion mode is not set to CompletionNone
    if ( echoMode() == QLineEdit::Normal &&
         completionMode() != KGlobalSettings::CompletionNone )
    {
        KeyBindingMap keys = getKeyBindings();
        KGlobalSettings::Completion mode = completionMode();
        bool noModifier = (e->state() == NoButton ||
                           e->state() == ShiftButton ||
                           e->state() == Keypad);

        if ( (mode == KGlobalSettings::CompletionAuto ||
              mode == KGlobalSettings::CompletionPopupAuto ||
              mode == KGlobalSettings::CompletionMan) && noModifier )
        {
            if ( !d->userSelection && hasSelectedText() &&
                 ( e->key() == Key_Right || e->key() == Key_Left ) &&
                 e->state()==NoButton )
            {
                QString old_txt = text();
                d->disableRestoreSelection = true;
                int start,end;
                getSelection(&start, &end);

                deselect();
                QLineEdit::keyPressEvent ( e );
                int cPosition=cursorPosition();
                if (e->key() ==Key_Right && cPosition > start )
                    validateAndSet(old_txt, cPosition, cPosition, old_txt.length());
                else
                    validateAndSet(old_txt, cPosition, start, old_txt.length());

                d->disableRestoreSelection = false;
                return;
            }

            if ( e->key() == Key_Escape )
            {
                if (hasSelectedText() && !d->userSelection )
                {
                    del();
                    setUserSelection(true);
                }

                // Don't swallow the Escape press event for the case
                // of dialogs, which have Escape associated to Cancel
                e->ignore();
                return;
            }

        }

        if ( (mode == KGlobalSettings::CompletionAuto ||
              mode == KGlobalSettings::CompletionMan) && noModifier )
        {
            QString keycode = e->text();
            if ( !keycode.isEmpty() && (keycode.unicode()->isPrint() ||
                e->key() == Key_Backspace || e->key() == Key_Delete ) )
            {
                bool hasUserSelection=d->userSelection;
                bool hadSelection=hasSelectedText();

                bool cursorNotAtEnd=false;

                int start,end;
                getSelection(&start, &end);
                int cPos = cursorPosition();

                // When moving the cursor, we want to keep the autocompletion as an
                // autocompletion, so we want to process events at the cursor position
                // as if there was no selection. After processing the key event, we
                // can set the new autocompletion again.
                if ( hadSelection && !hasUserSelection && start>cPos )
                {
                    del();
                    setCursorPosition(cPos);
                    cursorNotAtEnd=true;
                }

                d->disableRestoreSelection = true;
                QLineEdit::keyPressEvent ( e );
                d->disableRestoreSelection = false;

                QString txt = text();
                int len = txt.length();
                if ( !hasSelectedText() && len /*&& cursorPosition() == len */)
                {
                    if ( e->key() == Key_Backspace )
                    {
                        if ( hadSelection && !hasUserSelection && !cursorNotAtEnd )
                        {
                            backspace();
                            txt = text();
                            len = txt.length();
                        }

                        if ( !d->backspacePerformsCompletion || !len )
                            d->autoSuggest = false;
                    }

                    if (e->key() == Key_Delete )
                        d->autoSuggest=false;

                    if ( emitSignals() )
                        emit completion( txt );

                    if ( handleSignals() )
                        makeCompletion( txt );

                    if(  (e->key() == Key_Backspace || e->key() == Key_Delete) )
                        d->autoSuggest=true;

                    e->accept();
                }

                return;
            }

        }

        else if (( mode == KGlobalSettings::CompletionPopup ||
                   mode == KGlobalSettings::CompletionPopupAuto ) &&
                   noModifier && !e->text().isEmpty() )
        {
            QString old_txt = text();
            bool hasUserSelection=d->userSelection;
            bool hadSelection=hasSelectedText();
            bool cursorNotAtEnd=false;

            int start,end;
            getSelection(&start, &end);
            int cPos = cursorPosition();
            QString keycode = e->text();

            // When moving the cursor, we want to keep the autocompletion as an
            // autocompletion, so we want to process events at the cursor position
            // as if there was no selection. After processing the key event, we
            // can set the new autocompletion again.
            if (hadSelection && !hasUserSelection && start>cPos &&
               ( (!keycode.isEmpty() && keycode.unicode()->isPrint()) ||
                 e->key() == Key_Backspace || e->key() == Key_Delete ) )
            {
                del();
                setCursorPosition(cPos);
                cursorNotAtEnd=true;
            }

            uint selectedLength=selectedText().length();

            d->disableRestoreSelection = true;
            QLineEdit::keyPressEvent ( e );
            d->disableRestoreSelection = false;

            if (( selectedLength != selectedText().length() ) && !hasUserSelection )
                slotRestoreSelectionColors(); // and set userSelection to true

            QString txt = text();
            int len = txt.length();

            if ( txt != old_txt && len/* && ( cursorPosition() == len || force )*/ &&
                 ( (!keycode.isEmpty() && keycode.unicode()->isPrint()) ||
                   e->key() == Key_Backspace || e->key() == Key_Delete) )
            {
                if ( e->key() == Key_Backspace )
                {
                    if ( hadSelection && !hasUserSelection && !cursorNotAtEnd )
                    {
                        backspace();
                        txt = text();
                        len = txt.length();
                    }

                    if ( !d->backspacePerformsCompletion )
                        d->autoSuggest = false;
                }

                if (e->key() == Key_Delete )
                    d->autoSuggest=false;

                if ( d->completionBox )
                  d->completionBox->setCancelledText( txt );
	
                if ( emitSignals() )
                  emit completion( txt ); // emit when requested...

                if ( handleSignals() ) {
                  makeCompletion( txt );  // handle when requested...
                }

                if ( (e->key() == Key_Backspace || e->key() == Key_Delete ) &&
                    mode == KGlobalSettings::CompletionPopupAuto )
                  d->autoSuggest=true;

                e->accept();
            }
            else if (!len && d->completionBox && d->completionBox->isVisible())
                d->completionBox->hide();

            return;
        }

        else if ( mode == KGlobalSettings::CompletionShell )
        {
            // Handles completion.
            KShortcut cut;
            if ( keys[TextCompletion].isNull() )
                cut = KStdAccel::shortcut(KStdAccel::TextCompletion);
            else
                cut = keys[TextCompletion];

            if ( cut.contains( key ) )
            {
                // Emit completion if the completion mode is CompletionShell
                // and the cursor is at the end of the string.
                QString txt = text();
                int len = txt.length();
                if ( cursorPosition() == len && len != 0 )
                {
                    if ( emitSignals() )
                        emit completion( txt );
                    if ( handleSignals() )
                        makeCompletion( txt );
                    return;
                }
            }
            else if ( d->completionBox )
                d->completionBox->hide();
        }

        // handle rotation
        if ( mode != KGlobalSettings::CompletionNone )
        {
            // Handles previous match
            KShortcut cut;
            if ( keys[PrevCompletionMatch].isNull() )
                cut = KStdAccel::shortcut(KStdAccel::PrevCompletion);
            else
                cut = keys[PrevCompletionMatch];

            if ( cut.contains( key ) )
            {
                if ( emitSignals() )
                    emit textRotation( KCompletionBase::PrevCompletionMatch );
                if ( handleSignals() )
                    rotateText( KCompletionBase::PrevCompletionMatch );
                return;
            }

            // Handles next match
            if ( keys[NextCompletionMatch].isNull() )
                cut = KStdAccel::shortcut(KStdAccel::NextCompletion);
            else
                cut = keys[NextCompletionMatch];

            if ( cut.contains( key ) )
            {
                if ( emitSignals() )
                    emit textRotation( KCompletionBase::NextCompletionMatch );
                if ( handleSignals() )
                    rotateText( KCompletionBase::NextCompletionMatch );
                return;
            }
        }

        // substring completion
        if ( compObj() )
        {
            KShortcut cut;
            if ( keys[SubstringCompletion].isNull() )
                cut = KStdAccel::shortcut(KStdAccel::SubstringCompletion);
            else
                cut = keys[SubstringCompletion];

            if ( cut.contains( key ) )
            {
                if ( emitSignals() )
                    emit substringCompletion( text() );
                if ( handleSignals() )
                {
                    setCompletedItems( compObj()->substringCompletion(text()));
                    e->accept();
                }
                return;
            }
        }
    }

    uint selectedLength = selectedText().length();

    // Let QLineEdit handle any other keys events.
    QLineEdit::keyPressEvent ( e );

    if ( selectedLength != selectedText().length() )
        slotRestoreSelectionColors(); // and set userSelection to true
}
示例#29
0
/* 
 * Input a line with some basic editing.
 */
char * read_line() {

	// save terminal settings
	struct termios orig_attr;
	tcgetattr(0, &orig_attr);

	// Set terminal in raw mode
	tty_raw_mode();

	line_length = 0;
	line_pos = 0;

	// reset the line buffer
	int t = 0;
	for (t = 0; t < MAX_BUFFER_LINE; t++) {
		line_buffer[t] = '\0';
	}

	// Read one line until enter is typed
	while (1) {

		// init history if necessary
		if (history == NULL) {
			init_hist();
		}

		// Read one character in raw mode.
		char ch;
		read(0, &ch, 1);

		if (ch>=32 && ch < 127) {
			// It is a printable character. 

			if (line_pos == line_length) {
				// we're at the end of the line
				// Do echo
				write(1,&ch,1);

				// If max number of character reached return.
				if (line_length==MAX_BUFFER_LINE-2) break; 

				// add char to buffer.
				line_buffer[line_pos]=ch;
				line_length++;
				line_pos++;
			} else {
				// in the middle of the line somewhere
				char * temp = (char*)malloc(MAX_BUFFER_LINE * sizeof(char));
				int i;
				// copy all the characters after where we're at
				for ( i = 0; i < MAX_BUFFER_LINE; i++) {

					if (line_buffer[line_pos + i] == '\0' ) {
						// if we see the null char, we've gotten it all
						break;
					}
					temp[i] = line_buffer[line_pos + i];
				}

				// write the character we want to add
				write (1, &ch, 1);

				// If max number of character reached return.
				if (line_length==MAX_BUFFER_LINE-2) break; 
				
				// add char to buffer.
				line_buffer[line_pos]=ch;
				line_length++;
				line_pos++;

				// print all the rest of the characters afterwards
				int chars_added = 0;
				for (i = 0; i < MAX_BUFFER_LINE; i++) {
					chars_added+=1;
					write(1, &temp[i], 1);
					if (line_buffer[line_pos + i] == '\0' ) {
						// if we see the null char, we've gotten it all
						break;
					}
				}
				// go back to where we were
				backspace(chars_added);
			}
		}
		else if (ch==10) {
			// <Enter> was typed. Return line

			// add line to history linked list if it's not empty
			if ( strlen(line_buffer) != 0 ) {
				add_hist_line(line_buffer);
			}

			// Print newline
			write(1,&ch,1);

			break;
		}
		else if (ch == 31) {
			// ctrl-?
			read_line_print_usage();
			line_buffer[0]=0;
			break;
		}
		else if (ch == 127) {
			// <backspace> was typed. Remove previous character read.

			// don't do anything if we're already at the beginning 
			if (line_pos <= 0) {
				continue;
			}

			// Go back one character
			backspace(1);

			// Write a space to erase the last character read
			ch = ' ';
			write(1,&ch,1);

			// Go back one character
			backspace(1);

			// Remove one character from buffer
			line_buffer[ line_pos ] = '\0';
			line_length--;
			line_pos--;
		}
		else if (ch==27) {
			// Escape sequence. Read two chars more
			//
			// HINT: Use the program "keyboard-example" to
			// see the ascii code for the different chars typed.
			//
			char ch1; 
			char ch2;
			read(0, &ch1, 1);
			read(0, &ch2, 1);
			if (ch1==91 && ch2==65) {
				// Up arrow. Print next line in history.

				// Erase old line
				// Print backspaces
				int i = 0;
				for (i =0; i < line_length; i++) {
					ch = 8;
					write(1,&ch,1);
				}

				// Print spaces on top
				for (i =0; i < line_length; i++) {
					ch = ' ';
					write(1,&ch,1);
				}

				// Print backspaces
				for (i =0; i < line_length; i++) {
					ch = 8;
					write(1,&ch,1);
				}

				// if history is uninitialized, do nothing
				// Copy line from history
				history_index -= 1;
				if (history_index <= 0) {
					// loop back to the most recent command
					history_index = history_length - 1;
				}

				if (history[history_index] == NULL) {
					const char * empty = "";
					strcpy(line_buffer, empty);
				} else {
					strcpy(line_buffer, history[history_index]);
				}
				line_length = strlen(line_buffer);

				// echo line
				write(1, line_buffer, line_length);
			}
			else if (ch1 == 91 && ch2 == 66) {
				// down arrow. print previous line in history

				// Erase old line
				// Print backspaces
				backspace( line_length );

				// Print spaces on top
				int i = 0;
				for (i =0; i < line_length; i++) {
					ch = ' ';
					write(1,&ch,1);
				}

				// Print backspaces
				backspace( line_length );

				// increment index accordingly
				if (history_index <= 0) {
					// stay at 0
					history_index = 0;
				} else {
					history_index += 1;
					if (history_index >= history_length ) {
						history_index = 0;
					} 
				}

				// Copy line from history
				if (history[history_index] == NULL) {
					const char * empty = "";
					strcpy(line_buffer, empty);
				} else {
					strcpy(line_buffer, history[history_index]);
				}
				line_length = strlen(line_buffer);

				// echo line
				write(1, line_buffer, line_length);
			}
			else if (ch1 == 91 && ch2 == 68) {
				// left arrow
				if (line_pos > 0) {
					line_pos--;
					backspace(1);
				}
			}
			else if (ch1 == 91 && ch2 == 67) {
				// right arrow
				if (line_pos < line_length) {

					// grab current char
					char c = line_buffer[line_pos];

					// print grabbed char
					write( 1, &c, 1);

					line_pos++;
				}
			}
		}
	}

	// Add eol and null char at the end of string
	line_buffer[line_length]=10;
	line_length++;
	line_buffer[line_length]=0;

	// set the terminal back to orig settings
	tcsetattr(0, TCSANOW, &orig_attr);

	return line_buffer;
}
示例#30
0
// Processes an output message, depending on its type
void handleOutput(OutputData odMessage)
{
   char* szFile, * szTopic, * szError, * szTemp;
   bool bPartialMatch;

   // If there's a prompt on screen, remove it.
   if ( bPromptOnScreen )
      {
      backspace(nPromptLength);
      bPromptOnScreen = false;
      }

   switch ( odMessage.nType )
      {
      // Standard text output
      case OP_NORMAL:
         local(odMessage.szMessage, odMessage.nColor, 0);
         break;

      // New prompt for a hotkey
      case OP_HOTKEY_PROMPT:
         bPromptOnScreen = false;
         bCommandMode = false;
         if ( strlen(odMessage.szMessage) >= 60 )
            odMessage.szMessage[59] = '\0';
         odPromptInfo = odMessage;
         break;

      // New prompt for a command string
      case OP_COMMAND_PROMPT:
         bPromptOnScreen = false;
         bCommandMode = true;
         if ( strlen(odMessage.szMessage) >= 60 )
            odMessage.szMessage[59] = '\0';
         odPromptInfo = odMessage;
         break;

      // Pause
      case OP_FORCE_PAUSE:
         pausePrompt();
         break;

      // Exit
      case OP_EXIT_NODE:
         exitDoor(0);
         break;

      // Clear Screen
      case OP_CLEAR_SCREEN:
         clearScreen();
         break;

      // Display text, centered
      case OP_CENTER_TEXT:
         center(odMessage.szMessage, odMessage.nColor, 0);
         break;

      // Display a file (adds .ANS or .ASC as appropriate)
      case OP_DISPLAY_ANSI:
         if ( hasAnsi() )
            strcat(odMessage.szMessage, ".ans");
         else
            strcat(odMessage.szMessage, ".asc");
         showAnsi(odMessage.szMessage);
         break;

      // Display an entry in an HLP file
      case OP_DISPLAY_HLP:
         szFile = strtok(odMessage.szMessage, "&");
         szTopic = strtok(NULL, "&");
         szError = strtok(NULL, "&");
         szTemp = strtok(NULL, "");
         if ( szTemp[0] == 'y' )
            bPartialMatch = true;
         else
            bPartialMatch = false;
         displayHelp( szFile, szTopic, szError, bPartialMatch );
         break;
      }

   // If current prompt is a blank prompt, and new message is not a prompt-change,
   // update the current prompt's HP/SP/MF/etc values using data in the new message.
   if ( odMessage.nType != OP_HOTKEY_PROMPT && odMessage.nType != OP_COMMAND_PROMPT && strlen(odPromptInfo.szMessage) <= 0 )
      {
      short nOldType = odPromptInfo.nType;
      odPromptInfo = odMessage;
      odPromptInfo.nType = nOldType;
      odPromptInfo.szMessage[0] = '\0';
      }
}