示例#1
0
static void
newdata(void)
{
	u16_t len;
	u8_t c;
	char *dataptr;


	len = uip_datalen();
	dataptr = (char *)uip_appdata;

	while (len > 0 && s.bufptr < sizeof(s.buf)) {
		c = *dataptr;
		++dataptr;
		--len;
		switch (s.state) {
		case STATE_IAC:
			if (c == TELNET_IAC) {
				get_char(c);
				s.state = STATE_NORMAL;
			} else {
				switch (c) {
				case TELNET_WILL:
					s.state = STATE_WILL;
					break;
				case TELNET_WONT:
					s.state = STATE_WONT;
					break;
				case TELNET_DO:
					s.state = STATE_DO;
					break;
				case TELNET_DONT:
					s.state = STATE_DONT;
					break;
				default:
					s.state = STATE_NORMAL;
					break;
				}
			}
			break;
		case STATE_WILL:
			/* Reply with a DONT */
			sendopt(TELNET_DONT, c);
			s.state = STATE_NORMAL;
			break;

		case STATE_WONT:
			/* Reply with a DONT */
			sendopt(TELNET_DONT, c);
			s.state = STATE_NORMAL;
			break;
		case STATE_DO:
			/* Reply with a WONT */
			sendopt(TELNET_WONT, c);
			s.state = STATE_NORMAL;
			break;
		case STATE_DONT:
			/* Reply with a WONT */
			sendopt(TELNET_WONT, c);
			s.state = STATE_NORMAL;
			break;
		case STATE_NORMAL:
			if (c == TELNET_IAC)
				s.state = STATE_IAC;
			else
				get_char(c);
			break;
		}


	}

}
示例#2
0
bool lex_stream_t::implementation_t::skip_space(char& c)
{
    skip_white_space();

    return get_char(c);
}
示例#3
0
int main (int argc, char* args[]) {

	//SDL Window setup
	if (init(SCREEN_WIDTH, SCREEN_HEIGHT) == 1) {
		
		return 0;
	}

	char msg[] = "this is a test string";

	SDL_Rect src, dest;

	int sleep = 0;
	int quit = 0;
	Uint32 next_game_tick = SDL_GetTicks();
	
	int i = 0;
	float sin_t[360];
	
	for (i = 0; i < 360; i++) {
		
		sin_t[i] =  sin(i * M_PI / 180);
	}
	
	int c_offset = 0;
	int d = 1;

	//render loop
	while(quit == 0) {
	
		//check for new events every frame
		SDL_PumpEvents();

		const Uint8 *state = SDL_GetKeyboardState(NULL);
		
		if (state[SDL_SCANCODE_ESCAPE]) {
		
			quit = 1;
		}
		
		SDL_RenderClear(renderer);
		
		for (i = 0; i < strlen(msg); i++) {
			
			struct vector3d v = get_char(msg[i]);
			
			if (msg[i] == ' ') {
				
				c_offset += CHAR_WIDTH;
				continue;
			}

			src.x = v.x;
			src.y = v.y;
			src.w = CHAR_WIDTH;
			src.h = CHAR_WIDTH;
	
			dest.x = c_offset;
			dest.y = SCREEN_HEIGHT / 2 + sin_t[(int) fabs(c_offset) % 360] * 25;
			dest.w = CHAR_WIDTH;
			dest.h = CHAR_HEIGHT;
			
			SDL_RenderCopy(renderer, c_map, &src, &dest);
			
			c_offset += CHAR_WIDTH;
		}

		if (d > strlen(msg) * CHAR_WIDTH + SCREEN_WIDTH) {
			
			d = 0;
		}

		c_offset = SCREEN_WIDTH - d;
		d += 5;

		//draw to the screen
		SDL_RenderPresent(renderer);
				
		//time it takes to render 1 frame in milliseconds
		next_game_tick += 1000 / 60;
		sleep = next_game_tick - SDL_GetTicks();
	
		if( sleep >= 0 ) {
            				
			SDL_Delay(sleep);
		}
	}

	//free the source image
	SDL_FreeSurface(char_map);
	
	//Destroy window 
	SDL_DestroyWindow(window);

	//Quit SDL subsystems 
	SDL_Quit(); 
	 
	return 0;
}
示例#4
0
int 
get_token(void)
{
  int type = TOKEN_TYPE_ERR;
  int index = 0;
  int status = SCAN_STATUS_START;
  int save;

  int c;
  while (status != SCAN_STATUS_DONE) {
    c = get_char();
    save = BOOL_YES;

    switch (status) {
    case SCAN_STATUS_START:
      if (' ' == c || '\t' == c) {
        save = BOOL_NO;
      }
      else if ('\n' == c) {
        save = BOOL_NO;
        ++g_line_numer;
      }
      else if (isdigit(c)) {
        status = SCAN_STATUS_IN_CINT;
      }
      else if (isalpha(c) || '_' == c) {
        status = SCAN_STATUS_IN_ID;
      }
      else if ('.' == c) {
        status = SCAN_STATUS_IN_ACCESS;
      }
      else if ('#' == c) {
        save = BOOL_NO;
        status = SCAN_STATUE_IN_COMMENT;
      }
      else {
        status = SCAN_STATUS_DONE;
        switch (c) {
        case EOF:
          save = BOOL_NO;
          type = TOKEN_TYPE_EOF;
          break;
        case '=':
          type = TOKEN_TYPE_ASSIGN;
          break;
        case '<':
          type = TOKEN_TYPE_INHERIT;
          break;
        case '[':
          type = TOKEN_TYPE_LBRACKET;
          break;
        case ']':
          type = TOKEN_TYPE_RBRACKET;
          break;
        case '{':
          type = TOKEN_TYPE_LBRACE;
          break;
        case '}':
          type = TOKEN_TYPE_RBRACE;
          break;
        default:
          save = BOOL_NO;
          type = TOKEN_TYPE_ERR;
          break;
        }
      }
      break;
    case SCAN_STATUS_IN_ACCESS:
      if (isalpha(c) || '_' == c) {
        unget_char();
        save = BOOL_NO;
        status = SCAN_STATUS_DONE;
        type = TOKEN_TYPE_ACCESS;
      }
      else {
        fprintf(stderr, "Lexial error: [%d] after '.' ...\n", g_line_numer);
        exit(1);
      }
      break;
    case SCAN_STATUS_IN_ID:
      if (!isalnum(c) && '_' != c) {
        unget_char();
        save = BOOL_NO;
        status = SCAN_STATUS_DONE;
        type = TOKEN_TYPE_ID;
      }
      break;
    case SCAN_STATUS_IN_CINT:
      if ('.' == c) {
        status = SCAN_STATUS_IN_CREAL;
      }
      else {
        if (!isdigit(c)) {
          unget_char();
          save = BOOL_NO;
          status = SCAN_STATUS_DONE;
          type = TOKEN_TYPE_CINT;
        }
      }
      break;
    case SCAN_STATUS_IN_CREAL:
      if (!isdigit(c)) {
        unget_char();
        save = BOOL_NO;
        status = SCAN_STATUS_DONE;
        type = TOKEN_TYPE_CREAL;
      }
      break;
    case SCAN_STATUE_IN_COMMENT:
      save = BOOL_NO;
      if (EOF == c) {
        status = SCAN_STATUS_DONE;
        type = TOKEN_TYPE_EOF;
      }
      else if ('\n' == c) {
        ++g_line_numer;
        status = SCAN_STATUS_START;
      }
      break;
    case SCAN_STATUS_DONE:
    default:
      fprintf(g_scan_stream, "Scanner bug: status = %d\n", status);
      status = SCAN_STATUS_DONE;
      type = TOKEN_TYPE_ERR;
      break;
    }

    if (save && index < MAX_TOKEN)
      g_token[index++] = (char)c;

    if (SCAN_STATUS_DONE == status) {
      g_token[index] = 0;
      if (TOKEN_TYPE_ID == type)
        type = lookup_reserved(g_token);
    }
  }

  echo_scanner(g_scan_stream, g_line_numer, type, g_token);

  return type;
}
示例#5
0
void load_bin(void)
{
    unsigned char c;
    int ret;
    u32union page_addr;
    unsigned int crc, rcrc, i;

    for (i = 0; i < PAGE_SIZE; i++)
        page[i].b[3] = 0xff;


    while (1) {

        /* request page */

        /* 3 bytes - msb first */
        page_addr.b[3] = 0;
        ret = get_char((char*) &page_addr.b[2]);
        ret |= get_char((char*) &page_addr.b[1]);
        ret |= get_char((char*) &page_addr.b[0]);

        if (page_addr.l == 0x00ffffff) {
            put_char('e');
            break;
        } else {
            put_char('p');
        }

        page_addr.l &= ~((PAGE_SIZE << 1)-1);

        if ( ((page_addr.l >= BOOT_FLASH_START_ADDR) && (page_addr.l < BOOT_FLASH_END_ADDR)) 
           || (page_addr.l == DEV_CONFIG_PAGE_ADDRESS) ) {
            put_char('s');
            continue;
        } else {
            put_char('d');
        }

        /* load page to sram */
        ret = 0;
        crc = 0;
        for (i = 0; i < PAGE_SIZE; i++) {
            ret |= get_char((char*) &c);
            crc += c;
            page[i].b[2] = c;
                    
            ret |= get_char((char*) &c);
            crc += c;
            page[i].b[1] = c;

            ret |= get_char((char*) &c);
            crc += c;
            page[i].b[0] = c;
        }

        /* get crc */
        put_char('c');
        rcrc = 0;
        ret |= get_char((char*) &c);
        rcrc = c << 8;
        ret |= get_char((char*) &c);
        rcrc |= c;

        if (rcrc != crc) {
            ret = 100;
            put_char('x');
        }

        if (ret)
            break;

        erase_page(page_addr.l);
        put_char('e');

        /* protect bootloader start addr */
        if (page_addr.l == 0) {
            page[0].l = 0x040800;
            page[1].l = 0x000000;
        }

        for (i = 0; i < PAGE_SIZE/2; i++) {
            write_dword(page_addr.l + i*4, page[i*2].l, page[i*2 + 1].l);
        }

        put_char('w');

    }

    if (ret) {
        put_char('X');
        while (1);
    } else {
        put_char('K');
        goto_usercode();
    }
}
示例#6
0
int main(void)
 {
    char c;
    unsigned char idx[4] = {0, 0, 0, 0};
    unsigned char port, total_ports = 2, valid_ports = 0x3;
    volatile unsigned long i, j;
    int ret = 0;
    u32union delay;

    RCONbits.SWDTEN = 0;

    /* 70 MIPS; 140MHz */
    CLKDIVbits.PLLPRE = 0;
    PLLFBDbits.PLLDIV = 74;
    CLKDIVbits.PLLPOST = 0;

    /* switch clock to FRC oscillator with PLL */
    __builtin_write_OSCCONH(1);
    __builtin_write_OSCCONL(OSCCON | 1);

    /* wait for clock switch to complete */
    while (OSCCONbits.OSWEN == 1);
    /* wait for PLL lock */
    while (OSCCONbits.LOCK != 1);

    ANSELA = 0;
    ANSELB = 0;
    ANSELC = 0;

    TRIS_LED = 0;
    LED = 0;

    /* detect hw revision */
    /* set RB1 internal pull down */
    _TRISB1 = 1;
    _CNPDB1 = 1;
    
    /* hw 0v5 has RB1 connected to RB4 */
    _TRISB4 = 0;
    _LATB4 = 0;
    for (i = 0; i < 100000; i++);
    j = (_RB1 & 1);
    _LATB4 = 1;
    for (i = 0; i < 100000; i++);
    j |= ((_RB1 & 1) << 1);
    
    if (j == 0b10) {
        hw_rev = 0x05;
    } else {
        /* set RB9 internal pull down */
        _TRISB9 = 1;
        _CNPDB9 = 1;

        /* set RA9 internal pull down */
        _TRISA9 = 1;
        _CNPDA9 = 1;

        ANSELBbits.ANSB1 = 1;
        AD1CON3bits.ADCS = 16;
        AD1CON2bits.CHPS = 2;
        AD1CON1bits.ADON = 1;
        AD1CHS0bits.CH0SA = 3;
        AD1CON1bits.SAMP = 1;
        for (i = 0; i < 1000; i++);
        AD1CON1bits.SAMP = 0;
        for (i = 0; i < 10000; i++);

        if (ADC1BUF0 > 400)
            /* hw 0v4 has 1.25V vref on AN3 */
            hw_rev = 0x04;
        else if (_RB9 == 1)
            /* hw 0v3 has external pull-up on RB9 */
            hw_rev = 0x03;
        else if (_RA9 == 1)
            /* hw 0v2 has RB9 floating and RA9 pull-up */
            hw_rev = 0x02;
        else
            /* hw 0v1 has RA9 and RB9 floating */
            hw_rev = 0x01;
        _CNPDB9 = 0;
        _CNPDA9 = 0;
        AD1CON1bits.ADON = 0;
    }
    _CNPDB1 = 0;
    _TRISB4 = 1;
    hw_rev = 0x05;
    
    /* weak pull up on serial port rx pins */
    if (hw_rev >= 0x05) {
        _CNPUB12 = 1;
        _CNPUB15 = 1;
        _CNPUC7 = 1;
        _CNPUB7 = 1;
    } else if (hw_rev >= 0x03) {
        _CNPUB11 = 1;
        _CNPUB6 = 1;
        _CNPUB2 = 1;
        _CNPUB13 = 1;
    } else {
        _CNPUB6 = 1;
        _CNPUA4 = 1;
    }

    if (hw_rev >= 0x03) {
        total_ports = 4;
        valid_ports = 0xf;
    }
    
    /* get devid */
    read_flash(0xff0000, &devid);
    
    delay.l = BOOT_DELAY;

    if (delay.b[0] == 0)
        goto_usercode();

    /* Timer setup */
    /* increments every instruction cycle */
    T2CONbits.T32 = 1;
    /* clear timer3 IF */
    IFS0bits.T3IF = 0;
    /* disable timer3 isr */
    IEC0bits.T3IE = 0; 
    /* Convert seconds into timer count value */
    delay.l = ((unsigned long) (FCY)) * ((unsigned long) (delay.b[0]));
    PR3 = delay.w[1];
    PR2 = delay.w[0];
    TMR3HLD = 0x0000;
    TMR2 = 0x0000;
    T2CONbits.TON = 1;

    uart_init();

    while (1) {
        for (port = 0; port < total_ports; port++) {
            if (valid_ports & (1 << port)) {
                used_port = port;
                if (get_char(&c)) {
                    if (c != magic_word_bin[idx[port]])
                        valid_ports &= ~(1 << port);
                    else
                        idx[port]++;

                    if (idx[port] == (sizeof(magic_word_bin)-1)) {
                        ret = 1;
                        break;
                    }
                }
            }
        }

        if (valid_ports == 0)
            ret = 0xff;
        if (_T3IF == 1) {
            ret = 0xff;
        }
        if (ret)
            break;
    }
    T2CONbits.TON = 0;

    LED = 1;
    
    if (ret == 0xff) {
        put_char('*');
        goto_usercode();
    }
    
    put_str((char*) msg);
    put_str((char*) msg_bin);
    load_bin();
    return 0;
}
示例#7
0
/* ARGSUSED */
static int
isearch(int f GCC_UNUSED, int n)
{
    static TBUFF *pat_save = 0;	/* Saved copy of the old pattern str */

    int status;			/* Search status */
    register int cpos;		/* character number in search string */
    register int c;		/* current input character */
    MARK curpos, curp;		/* Current point on entry */
    int init_direction;		/* The initial search direction */

    /* Initialize starting conditions */

    cmd_reexecute = -1;		/* We're not re-executing (yet?) */
    itb_init(&cmd_buff, EOS);	/* Init the command buffer */
    /* Save the old pattern string */
    (void) tb_copy(&pat_save, searchpat);
    curpos = DOT;		/* Save the current pointer */
    init_direction = n;		/* Save the initial search direction */

    ignorecase = window_b_val(curwp, MDIGNCASE);

    scanboundry(FALSE, DOT, FORWARD);	/* keep scanner() finite */

    /* This is a good place to start a re-execution: */

  start_over:

    /* ask the user for the text of a pattern */
    promptpattern("ISearch: ");

    status = TRUE;		/* Assume everything's cool */

    /*
     * Get the first character in the pattern.  If we get an initial
     * Control-S or Control-R, re-use the old search string and find the
     * first occurrence
     */

    c = kcod2key(get_char());	/* Get the first character */
    if ((c == IS_FORWARD) ||
	(c == IS_REVERSE)) {	/* Reuse old search string? */
	for (cpos = 0; cpos < (int) tb_length(searchpat); ++cpos)
	    echochar(tb_values(searchpat)[cpos]);	/* and re-echo the string */
	curp = DOT;
	if (c == IS_REVERSE) {	/* forward search? */
	    n = -1;		/* No, search in reverse */
	    last_srch_direc = REVERSE;
	    backchar(TRUE, 1);	/* Be defensive about EOB */
	} else {
	    n = 1;		/* Yes, search forward */
	    last_srch_direc = FORWARD;
	    forwchar(TRUE, 1);
	}
	unget_char();
	status = scanmore(searchpat, n);	/* Do the search */
	if (status != TRUE)
	    DOT = curp;
	c = kcod2key(get_char());	/* Get another character */
    } else {
	tb_init(&searchpat, EOS);
    }
    /* Top of the per character loop */

    for_ever {			/* ISearch per character loop */
	/* Check for special characters, since they might change the
	 * search to be done
	 */

	if (ABORTED(c) || c == '\r')	/* search aborted? */
	    return (TRUE);	/* end the search */

	if (isbackspace(c))
	    c = '\b';

	if (c == quotec)	/* quote character? */
	    c = kcod2key(get_char());	/* Get the next char */

	switch (c) {		/* dispatch on the input char */
	case IS_REVERSE:	/* If backward search */
	case IS_FORWARD:	/* If forward search */
	    curp = DOT;
	    if (c == IS_REVERSE) {	/* forward search? */
		last_srch_direc = REVERSE;
		n = -1;		/* No, search in reverse */
		backchar(TRUE, 1);	/* Be defensive about
					 * EOB */
	    } else {
		n = 1;		/* Yes, search forward */
		last_srch_direc = FORWARD;
		forwchar(TRUE, 1);
	    }
	    status = scanmore(searchpat, n);	/* Do the search */
	    if (status != TRUE)
		DOT = curp;
	    c = kcod2key(get_char());	/* Get the next char */
	    continue;		/* Go continue with the search */

	case '\t':		/* Generically allowed */
	case '\n':		/* controlled characters */
	    break;		/* Make sure we use it */

	case '\b':		/* or if a Rubout: */
	    if (itb_length(cmd_buff) <= 1)	/* Anything to delete? */
		return (TRUE);	/* No, just exit */
	    unget_char();
	    DOT = curpos;	/* Reset the pointer */
	    n = init_direction;	/* Reset the search direction */
	    (void) tb_copy(&searchpat, pat_save);
	    /* Restore the old search str */
	    cmd_reexecute = 0;	/* Start the whole mess over */
	    goto start_over;	/* Let it take care of itself */

	    /* Presumably a quasi-normal character comes here */

	default:		/* All other chars */
	    if (!isPrint(c)) {	/* Is it printable? */
		/* Nope. */
		unkeystroke(c);	/* Re-eat the char */
		return (TRUE);	/* And return the last status */
	    }
	}			/* Switch */

	/* I guess we got something to search for, so search for it */

	tb_append(&searchpat, c);	/* put the char in the buffer */
	echochar(c);		/* Echo the character */
	if (!status) {		/* If we lost last time */
	    kbd_alarm();	/* Feep again */
	} else			/* Otherwise, we must have won */
	    status = scanmore(searchpat, n);	/* or find the next
						   * match */
	c = kcod2key(get_char());	/* Get the next char */
    }				/* for_ever */
}
示例#8
0
文件: shell.c 项目: bkolobara/Benu-pi
int shell ( char *args[] )
{
	char cmd[MAXCMDLEN + 1];
	int i, key, rv;
	timespec_t t;
	int argnum;
	char *argval[MAXARGS + 1];
	pthread_t thr;

	printf ( "\n*** Simple shell interpreter ***\n\n" );
	help ();

	t.tv_sec = 0;
	t.tv_nsec = 100000000; /* 100 ms */

	while (1)
	{
		new_cmd:
		printf ( "\n> " );

		i = 0;
		memset ( cmd, 0, MAXCMDLEN );

		/* get command - get chars until new line is received */
		while ( i < MAXCMDLEN )
		{
			key = get_char ();

			if ( !key )
			{
				nanosleep ( &t, NULL );
				continue;
			}

			if ( key == '\n' || key == '\r')
			{
				if ( i > 0 )
					break;
				else
					goto new_cmd;
			}

			switch ( key )
			{
			case '\b':
				if ( i > 0 )
				{
					cmd[--i] = 0;
					printf ( "%c", key );
				}
				break;

			default:
				printf ( "%c", key );
				cmd[i++] = (char) key;
				break;
			}
		}
		printf ( "\n" );

		/* parse command line */
		argnum = 0;
		for(i = 0; i < MAXCMDLEN && cmd[i]!=0 && argnum < MAXARGS; i++)
		{
			if ( cmd[i] == ' ' || cmd[i] == '\t')
				continue;

			argval[argnum++] = &cmd[i];
			while ( cmd[i] && cmd[i] != ' ' && cmd[i] != '\t'
				&& i < MAXCMDLEN )
				i++;

			cmd[i] = 0;
		}
		argval[argnum] = NULL;

		/* match command to shell command */
		for ( i = 0; sh_cmd[i].func != NULL; i++ )
		{
			if ( strcmp ( argval[0], sh_cmd[i].name ) == 0 )
			{
				if ( sh_cmd[i].func ( argval ) )
					printf ( "\nProgram returned error!\n" );

				goto new_cmd;
			}
		}

		/* not shell command; start given program by calling kernel */
		rv = posix_spawn ( &thr, argval[0], NULL, NULL, argval, NULL );
		if ( !rv )
		{
			if ( argnum < 2 || argval[argnum-1][0] != '&' )
				pthread_join ( thr, NULL );

			goto new_cmd;
		}

		if ( strcmp ( argval[0], "quit" ) == 0 ||
			strcmp ( argval[0], "exit" ) == 0 )
			break;

		/* not program kernel or shell knows about it - report error! */
		printf ( "Invalid command!" );
	}

	printf ( "Exiting from shell\n" );

	return 0;
}
示例#9
0
// main function
extern void main(void) {
    unsigned char flag, numb_pages;
    unsigned i, write_size, read_size,
             temp_six_vector, six_vector, errors, write_offset;
    unsigned boot_args[AT45_PAGE_SIZE / 4];
    // calculate temp six vector
    numb_pages = 0;
    i = AT45_PAGE_NUMB;
    while(i >>= 1)
        numb_pages++;
    temp_six_vector = (numb_pages << 13)  + (AT45_PAGE_SIZE << 17);

    // setup SYS interrupt
    aic_configure_irq(AT91C_ID_SYS, AT91C_AIC_PRIOR_LOWEST,
                      AT91C_AIC_SRCTYPE_INT_LEVEL_SENSITIVE, aic_asm_sys_handler);
    // enable SYS interrupt
    aic_enable_irq(AT91C_ID_SYS);
    // setup rtt - 1Hz clock
    AT91C_BASE_ST->ST_RTMR = 0x4000;

    upoint_r = pt_mem_area, upoint_w = (pt_mem_area + AT45DB642D_SIZE);
    put_string("Init AT45DB642D and get device information\n");

    if (!at45_init())
        put_string("Device inited and ready\n");
    else
        put_string("Error!\n");

    put_string("Press any key to load boot menu\n: ");
    // setup rtt interrupt flag
    AT91C_BASE_ST->ST_IER = AT91C_ST_RTTINC;
    // enable RXRDY interrupt in DBGU
    AT91C_BASE_DBGU->DBGU_IER |= AT91C_US_RXRDY;
    wait_status = 1;
    get_char();

    while (flag != 'q') {
        put_string("\nload (l), write(w), run kernel(r), quit(q), erase(e): ");
        flag = get_char();
        switch(flag) {
        // loading data to sdram
        case 'l':
            put_string("Please trasfer the boot file:\n");
            transfer_size = 0;
            // setup rtt interrupt flag
            AT91C_BASE_ST->ST_IER = AT91C_ST_RTTINC;
            // enable RXRDY interrupt in DBGU
            AT91C_BASE_DBGU->DBGU_IER |= AT91C_US_RXRDY;
            while(!transfer_size);
            delay(100000);
            if (transfer_size > 0) {
                put_string("Transfer complete\n");
                util_printf("Byte's sended: %x\n", transfer_size);
            }
            break;
        // writing bytes from data flash
        case 'w':
            if (transfer_size == 0) {
                put_string("Please transfer begin, write end\n");
                break;
            }
            else if (transfer_size > (AT45DB642D_SIZE)) {
                put_string("Trasfer is larger than flash size\n");
                break;
            }
            else {
                if ((unsigned)transfer_size % AT45_PAGE_SIZE)
                    write_size = ((unsigned)transfer_size / AT45_PAGE_SIZE + 1) * AT45_PAGE_SIZE;
                else
                    write_size = transfer_size;
                put_string("Write boot(b) or linux kernel(n): ");
                flag = get_char();
                util_printf("%c\n", flag);
                if (flag == 'b') {
                    write_offset = BOOT_OFFSET;
                    put_string("\nModification of Arm Interrupt Vector #6\n");
                    six_vector = (write_size / 512) + 1 + temp_six_vector;
                    util_printf("Six vector is 0x%x\n", six_vector);
                    upoint_w[5] = six_vector;
                }
                else {
                    write_offset = LINUX_OFFSET;
                    put_string("Writing args\n");

                    boot_args[0] = write_size;
                    if (!at45_write(BOOT_2_ARGS_OFFSET, boot_args, AT45_PAGE_SIZE))
                        put_string("Write success\n");
                    else
                        put_string("Error!\n");
                }
                util_printf("Write 0x%x bytes\n", write_size);

                if (!at45_write(write_offset, upoint_w, write_size))
                    put_string("Write success\n");
                else
                    put_string("Error!\n");
                if (!at45_read(write_offset, upoint_r, write_size)) {
                    put_string("Read success\nStart verification\n");
                    six_vector = upoint_r[5];
                    if (write_offset == BOOT_OFFSET) {
                        if ((six_vector & 0xfffff000) - temp_six_vector) {
                            util_printf("Six vector is damage, current 0x%x, original 0x%x\n",
                                        six_vector, temp_six_vector);
                            break;
                        }
                        else {
                            put_string("Six vector is correct\nStart code verification\n");
                        }
                    }
                    errors = 0;
                    for (i = 0; i < write_size / 4; i++) {
                        if (upoint_r[i] != upoint_w[i]) {
                            errors++;
                            util_printf("Addr - %x, write - %x, read - %x\n", i, upoint_w[i], upoint_r[i]);
                        }
                    }
                    put_string("Stop code verification\n");
                    if (errors)
                        put_string("Verification failed!\n");
                    else
                        put_string("Verification success!\n");
                }
            }
            break;
        // erase first page
        case 'e':
            if (!at45_read(0x0, upoint_r, 0x20)) {
                six_vector = upoint_r[5];
                read_size = (six_vector & 0xff) * 512;
                for (i = 0; i <= read_size; i += AT45_PAGE_SIZE) {
                    if (!at45_page_erase(i))
                        put_string("Erase success\n");
                    else
                        put_string("Error!\n");
                }
            }
            break;
        // run 2boot code
        case 'r':
            run_kernel();
            break;
        // exit of loop
        case 'q':
            put_string("\nQuit & Reset\n");
            AT91C_BASE_ST->ST_WDMR = 256 | AT91C_ST_RSTEN;
            AT91C_BASE_ST->ST_CR = AT91C_ST_WDRST;
            break;
        // undef
        default:
            put_string("\nUndefined command\n");
            break;
        }
    }
    // Infinity loop
    while (1) {
        // Disable pck for idle cpu mode
        AT91C_BASE_PMC->PMC_SCDR = AT91C_PMC_PCK;
    }
}
示例#10
0
文件: edit.c 项目: vigna/ne
static int to_something(buffer *b, int (to_first)(int), int (to_rest)(int)) {
	assert_buffer(b);

	/* If we are after the end of the line, just return ERROR. */

	if (b->cur_line == b->num_lines -1 && b->cur_pos >= b->cur_line_desc->line_len) return ERROR;

	int64_t pos = b->cur_pos;
	int c;
	/* First of all, we search for the word start, if we're not over it. */
	if (pos >= b->cur_line_desc->line_len || !ne_isword(c = get_char(&b->cur_line_desc->line[pos], b->encoding), b->encoding))
		if (search_word(b, 1) != OK)
			return ERROR;

	bool changed = false;
	int64_t new_len = 0;
	pos = b->cur_pos;
	const int64_t cur_char = b->cur_char;
	const int cur_x = b->cur_x;
	/* Then, we compute the word position extremes, length of the result (which
		may change because of casing). */
	while (pos < b->cur_line_desc->line_len && ne_isword(c = get_char(&b->cur_line_desc->line[pos], b->encoding), b->encoding)) {
		const int new_c = new_len ? to_rest(c) : to_first(c);
		changed |= (c != new_c);

		if (b->encoding == ENC_UTF8) new_len += utf8seqlen(new_c);
		else new_len++;

		pos = next_pos(b->cur_line_desc->line, pos, b->encoding);
	}

	const int64_t len = pos - b->cur_pos;
	if (!len) {
		char_right(b);
		return OK;
	}

	if (changed) {
		/* We actually perform changes only if some character was case folded. */
		char * word = malloc(new_len * sizeof *word);
		if (!word) return OUT_OF_MEMORY;

		pos = b->cur_pos;
		new_len = 0;
		/* Second pass: we actually build the transformed word. */
		while (pos < b->cur_line_desc->line_len && ne_isword(c = get_char(&b->cur_line_desc->line[pos], b->encoding), b->encoding)) {
			if (b->encoding == ENC_UTF8) new_len += utf8str(new_len ? to_rest(c) : to_first(c), word + new_len);
			else {
				word[new_len] = new_len ? to_rest(c) : to_first(c);
				new_len++;
			}

			pos = next_pos(b->cur_line_desc->line, pos, b->encoding);
		}

		start_undo_chain(b);

		delete_stream(b, b->cur_line_desc, b->cur_line, b->cur_pos, len);
		if (new_len) insert_stream(b, b->cur_line_desc, b->cur_line, b->cur_pos, word, new_len);

		free(word);

		end_undo_chain(b);

		if (cur_char < b->attr_len) b->attr_len = cur_char;
		update_line(b, b->cur_line_desc, b->cur_y, cur_x, false);
		need_attr_update = true;
	}

	return search_word(b, 1);
}
示例#11
0
Token* get_token()
{
        char ch; //This can be the current character you are examining during scanning.
	static char token_string[MAX_TOKEN_STRING_LENGTH]; //Store your token here as you build it.
	char *token_ptr = token_string; //write some code to point this to the beginning of token_string
	int loop = FALSE;
	int symbol_code;
	Token* token = (Token*)malloc(sizeof(Token)); //allocate memory for struct


	CharCode code;


	//get_char will set global ptr src_ptr to the source_buffer line
	//get_char will also set ch to the first character in source_buffer, if the end of line has been reached,
	//otherwise will set ch to what GLOBAL src_ptr is currently looking at.
	//other methods will set ch to the next char in the source_buffer after they have tokenized
	token->next = NULL;
	get_char(token_string);


	ch = *src_ptr;
	//if get_char shows us that we have a blank space or the beginning of a comment we need to skip over all spaces and comments
	//until we come to a token
	if(ch == ' ' || ch == '\n' || ch == '{' || ch == '\r' || ch == '\t')
	{
		loop = TRUE; // Execute the loop for skipping spaces, skipping comments, and getting a new line
	}
	while(loop)
	{


		//check to see what the current ch is
		if(ch == ' ' || ch == '\t')
		{
			//call function skip_blanks which returns a pointer to the first non-blank character				// if it reaches null terminator it will set ch to '\0' and come back here


			skip_blanks(&ch);


			//now call get_char again to get a new line if ch is a null terminator
			if(ch == '\n' || ch == '\r')
			{


				//call get_char to get a new source line
				get_char(token_string);
				ch = *src_ptr;
			}
			//after this there may be more spaces or comments, need to continue to evaluae loop
			loop = TRUE;
		}
		//now check to see if there is a comment and skip over this as well
		else if(ch == '{')
		{
			loop = TRUE;
			//skip_comment will return the character following the ending bracket
			//src_ptr will also be pointing here
			//ch will contin current value of src_ptr
			skip_comment(&ch, token_string);


		}
		else if(ch == '\n' || ch == '\r')
		{
			get_char(token_string);
			ch = *src_ptr;
			loop = TRUE;
		}
		else
		{
			//if no matches then we are looking at a valid character
			loop = FALSE;
			//make sure to update ch to what src_ptr is looking at
			ch = *src_ptr;
		}


	}

    //position 'ch' in char_table will return a CharCode corresponding to Letter, Digit, Quote, etc...
	code = char_table[ch];
	//check to see if code for ch is a LETTER
	if(code == LETTER)
	{
		//pass in the token_string array to point to, and the current Token struct.
		//get_word will set the tokens values appropriately so it can be returned
		//to main
		get_word( token);
	}
	//check to see if it is a digit
	else if(code == DIGIT)
	{
		get_number(token); //The parameter has to be same as get_word because we need to build a character array to be converted to integers or real numbers
	}
	//check to see if it is a quote
	else if(code == QUOTE)
	{
		get_string(token);
	}
	else
	{
		//in the get_special function the token code will be set
		symbol_code = get_special();
		//set token code to the symbol code
		token->code = (TokenCode)symbol_code;
		//the literal type for the token will be a str_lit and the char ptr will point to the token_string array where
		//the characters are stored
		token->literal.str_lit = token_string;
		//type of token will be set to string_lit
		token->type = STRING_LIT;


	}
    //3.  Call the appropriate function to deal with the cases in 2.


   return token; //What should be returned here?
}
示例#12
0
文件: chat.c 项目: coyizumi/cs111
/*
 *	'Wait for' this string to appear on this file descriptor.
 */
int
get_string(char *string)
{
    char temp[STR_LEN];
    int c, printed = 0;
    size_t len, minlen;
    char *s = temp, *end = s + STR_LEN;
    char *logged = temp;

    fail_reason = (char *)0;

    if (strlen(string) > STR_LEN) {
	chat_logf("expect string is too long");
	exit_code = 1;
	return 0;
    }

    string = clean(string, 0);
    len = strlen(string);
    minlen = (len > sizeof(fail_buffer)? len: sizeof(fail_buffer)) - 1;

    if (verbose)
	chat_logf("expect (%v)", string);

    if (len == 0) {
	if (verbose)
	    chat_logf("got it");
	return (1);
    }

    alarm(timeout);
    alarmed = 0;

    while ( ! alarmed && (c = get_char()) >= 0) {
	int n, abort_len, report_len;

	if (echo)
	    echo_stderr(c);
	if (verbose && c == '\n') {
	    if (s == logged)
		chat_logf("");	/* blank line */
	    else
		chat_logf("%0.*v", s - logged, logged);
	    logged = s + 1;
	}

	*s++ = c;

	if (verbose && s >= logged + 80) {
	    chat_logf("%0.*v", s - logged, logged);
	    logged = s;
	}

	if (Verbose) {
	   if (c == '\n')
	       fputc( '\n', stderr );
	   else if (c != '\r')
	       fprintf( stderr, "%s", character(c) );
	}

	if (!report_gathering) {
	    for (n = 0; n < n_reports; ++n) {
		if ((report_string[n] != (char*) NULL) &&
		    s - temp >= (report_len = strlen(report_string[n])) &&
		    strncmp(s - report_len, report_string[n], report_len) == 0) {
		    time_t time_now   = time ((time_t*) NULL);
		    struct tm* tm_now = localtime (&time_now);

		    strftime (report_buffer, 20, "%b %d %H:%M:%S ", tm_now);
		    strcat (report_buffer, report_string[n]);

		    report_string[n] = (char *) NULL;
		    report_gathering = 1;
		    break;
		}
	    }
	}
	else {
	    if (!iscntrl (c)) {
		int rep_len = strlen (report_buffer);
		report_buffer[rep_len]     = c;
		report_buffer[rep_len + 1] = '\0';
	    }
	    else {
		report_gathering = 0;
		fprintf (report_fp, "chat:  %s\n", report_buffer);
	    }
	}

	if ((size_t)(s - temp) >= len &&
	    c == string[len - 1] &&
	    strncmp(s - len, string, len) == 0) {
	    if (verbose) {
		if (s > logged)
		    chat_logf("%0.*v", s - logged, logged);
		chat_logf(" -- got it\n");
	    }

	    alarm(0);
	    alarmed = 0;
	    return (1);
	}

	for (n = 0; n < n_aborts; ++n) {
	    if (s - temp >= (abort_len = strlen(abort_string[n])) &&
		strncmp(s - abort_len, abort_string[n], abort_len) == 0) {
		if (verbose) {
		    if (s > logged)
			chat_logf("%0.*v", s - logged, logged);
		    chat_logf(" -- failed");
		}

		alarm(0);
		alarmed = 0;
		exit_code = n + 4;
		strcpy(fail_reason = fail_buffer, abort_string[n]);
		return (0);
	    }
	}

	if (s >= end) {
	    if (logged < s - minlen) {
		chat_logf("%0.*v", s - logged, logged);
		logged = s;
	    }
	    s -= minlen;
	    memmove(temp, s, minlen);
	    logged = temp + (logged - s);
	    s = temp + minlen;
	}

	if (alarmed && verbose)
	    chat_logf("warning: alarm synchronization problem");
    }

    alarm(0);
    
    if (verbose && printed) {
	if (alarmed)
	    chat_logf(" -- read timed out");
	else
	    chat_logf(" -- read failed: %m");
    }

    exit_code = 3;
    alarmed   = 0;
    return (0);
}
示例#13
0
void main(void) {
	unsigned long delay;
	char exit = 'o';
	
  /* Initialization code */
    clock_init(BUS_CLK);
    sci_init(9600, BUS_CLK, SCI0);
    LIN_PHY_ENABLE;
    sci_init(9600, BUS_CLK, SCI1);
    gpio_init();
    LS_Module_Init();
    HS_Module_Init();
    HS0_On();
    PWM_init();
    ADC_init(BUS_CLK);
    
    /* Test serial communication */
    send_string("\n\rSerial Test, press any key\n\r", SCI1);
    echo(SCI1);
    send_string("\n\rTest successful\n\r",SCI1);

	/* Test Relay */
	send_string("\n\rPress u to activate the relay up and d to activate it down\n\r", SCI1);
	send_string("\n\rPres e to exit relay test\n\r", SCI1);
	
	while(exit != 'e'){
		exit = get_char(SCI1);
		put_char(exit, SCI1);
		if(exit == 'u'){
			send_string("\r\nRelay Low side driver 0 active\r\n", SCI1);
			LS0_On();
			for(delay = 0; delay < 30000; ++delay);
			send_string("\r\nRelay Low side driver 0 inactive\r\n", SCI1);
			LS0_Off();
			exit = 'a';	
		} else if (exit == 'd') {
			send_string("\r\nRelay Low side driver 1 active\r\n", SCI1);
			LS1_On();
			for(delay = 0; delay < 30000; ++delay);
			send_string("\r\nRelay Low side driver 1 inactive\r\n", SCI1);
			LS1_Off();
			exit = 'a';
		}		
	}
	
	put_char('\n', SCI1);
	EnableInterrupts;


  for(;;) {
    _FEED_COP(); /* feeds the dog */
    if(read_sw2){
    	LS0_On();
    	send_string("\r\nSwitch 2 pressed\r\n", SCI1);	
    } else {
    	LS0_Off();
    }
    if(read_sw3){
    	LS1_On();
    	send_string("\r\nSwitch 3 pressed\r\n", SCI1);	
    } else {
    	LS1_Off();
    }
    for(delay = 0; delay < 30000; ++delay);
    send_string("\rADC value:   ", SCI1);
    send_string("\b\b\b", SCI1);
    DisplayInt((unsigned char) ADC_read(POT), SCI1);
    put_char(0x55,SCI0);	/* Send stuff through LIN */
  } /* loop forever */
  /* please make sure that you never leave main */
}
示例#14
0
static int proc_tag()
{
    char ch;
    int tag, index = 0;
    char *s, *o;
    
    if (check_left_char('*', "/") != 0)
        return 0;
    if (check_left_char('<', "/*") != 0)
        return 0;
    if (check_left_char('$', "/*<") != 0)
        return 0;
    // we are here because input string is "/,*,<,$"
 
    if (get_char(&ch) < 0)
        return -1;
    if ((ch == 'H') || (ch == 'E') || (ch == 'K') || (ch == '*')) {
        switch (ch) {
          case 'H' : if (put_header() < 0)
                         return -1;
                     Mode = S_KOREAN;
                     break;
          case 'E' : Mode = S_ENGLISH; break;
          case 'K' : Mode = S_KOREAN; break;
          case '*' : Mode = S_DONE; break;
        }
        goto end_tags;
    }
    switch (ch) {
      case 'F' : s = _filename;     break;
      case 'A' : s = _author;       break;
      case 'V' : s = _version;      break;
      case 'T' : s = _translator;   break;
      case 'D' : s = _date;         break;
      case 'L' : s = _last_update;  break;
      case 'R' : 
        _reviewer[num_reviewer] = (char *)malloc(MAX_LENGTH);
        if (_reviewer[num_reviewer] == NULL) {
            fprintf(stderr, "\nLine %d: malloc failure\n", line);
            return -1;
        }        
        s = _reviewer[num_reviewer++]; 
        break;
      default :
        fprintf(stderr, "\nLine %d: Unknown Tag '%c'\n", line, ch);
        return -1;
    }
    tag = ch;
    o = s;
    if (check_right_char('=') < 0)
        return -1;
    if (check_right_char('"') < 0)
        return -1;
    while (1) {
        ch = getchar();
        #ifdef DEBUG
            putchar(ch);
        #endif
        if (ch == '"') {
            *s = 0;
            switch (tag) {
              case 'F' : 
              case 'A' : 
              case 'V' : 
              case 'T' :
              case 'D' : 
              case 'L' :
              case 'R' : 
                        break;
              default : fprintf(stderr, "\nOOOPPPPPS\n");
            }
            break;
        }
        if ((ch == '\t') || (ch == '\n') || (ch == '\r'))
            ch = ' ';
        if ((ch == ' ') && (*s == ' '))
                continue;
        *s++ = ch;
        if (index == MAX_LENGTH) {
            fprintf(stderr, "\nLine %d: string too long\n", line);
            return -1;
        }
    }
    #ifdef DEBUG
        printf("Line %d: TAG '%c' = '%s'\n", line, tag, o);
    #endif
end_tags:
    if (check_right_char('>') < 0)
        return -1;
    if (check_right_char('*') < 0)
        return -1;
    if (check_right_char('/') < 0)
        return -1;
    if (Mode != S_DONE) {
    	do
            get_char(&ch);
        while (ch != '\n');
    }
    return 0;
}
示例#15
0
文件: query.c 项目: chungy/RetroArch
static struct buffer parse_string(struct buffer buff,
      struct rmsgpack_dom_value *value, const char **error)
{
   const char * str_start = NULL;
   char terminator        = '\0';
   char c                 = '\0';
   int  is_binstr         = 0;

   (void)c;

   buff = get_char(buff, &terminator, error);

   if (*error)
      return buff;

   if (terminator == 'b')
   {
      is_binstr = 1;
      buff = get_char(buff, &terminator, error);
   }

   if (terminator != '"' && terminator != '\'')
   {
      buff.offset--;
      raise_expected_string(buff.offset, error);
   }

   str_start = buff.data + buff.offset;
   buff = get_char(buff, &c, error);

   while (!*error)
   {
      if (c == terminator)
         break;
      buff = get_char(buff, &c, error);
   }

   if (!*error)
   {
      size_t count;
      value->type = is_binstr ? RDT_BINARY : RDT_STRING;
      value->val.string.len = (buff.data + buff.offset) - str_start - 1;

      count = is_binstr ? (value->val.string.len + 1) / 2 : (value->val.string.len + 1);
      value->val.string.buff = (char*)calloc(count, sizeof(char));

      if (!value->val.string.buff)
         raise_enomem(error);
      else if (is_binstr)
      {
         unsigned i;
         const char *tok = str_start;
         unsigned      j = 0;

         for (i = 0; i < value->val.string.len; i += 2)
         {
            uint8_t hi, lo;
            char hic = tok[i];
            char loc = tok[i + 1];

            if (hic <= '9')
               hi = hic - '0';
            else
               hi = (hic - 'A') + 10;

            if (loc <= '9')
               lo = loc - '0';
            else
               lo = (loc - 'A') + 10;

            value->val.string.buff[j++] = hi * 16 + lo;
         }

         value->val.string.len = j;
      }
      else
         memcpy(value->val.string.buff, str_start, value->val.string.len);
   }
   return buff;
}
示例#16
0
static int
check_bom(int get_char(struct tok_state *),
          void unget_char(int, struct tok_state *),
          int set_readline(struct tok_state *, const char *),
          struct tok_state *tok)
{
    int ch1, ch2, ch3;
    ch1 = get_char(tok);
    tok->decoding_state = STATE_RAW;
    if (ch1 == EOF) {
        return 1;
    } else if (ch1 == 0xEF) {
        ch2 = get_char(tok);
        if (ch2 != 0xBB) {
            unget_char(ch2, tok);
            unget_char(ch1, tok);
            return 1;
        }
        ch3 = get_char(tok);
        if (ch3 != 0xBF) {
            unget_char(ch3, tok);
            unget_char(ch2, tok);
            unget_char(ch1, tok);
            return 1;
        }
#if 0
    /* Disable support for UTF-16 BOMs until a decision
       is made whether this needs to be supported.  */
    } else if (ch1 == 0xFE) {
        ch2 = get_char(tok);
        if (ch2 != 0xFF) {
            unget_char(ch2, tok);
            unget_char(ch1, tok);
            return 1;
        }
        if (!set_readline(tok, "utf-16-be"))
            return 0;
        tok->decoding_state = STATE_NORMAL;
    } else if (ch1 == 0xFF) {
        ch2 = get_char(tok);
        if (ch2 != 0xFE) {
            unget_char(ch2, tok);
            unget_char(ch1, tok);
            return 1;
        }
        if (!set_readline(tok, "utf-16-le"))
            return 0;
        tok->decoding_state = STATE_NORMAL;
#endif
    } else {
        unget_char(ch1, tok);
        return 1;
    }
    if (tok->encoding != NULL)
        PyMem_FREE(tok->encoding);
    tok->encoding = new_string("utf-8", 5, tok);
    if (!tok->encoding)
        return 0;
    /* No need to set_readline: input is already utf-8 */
    return 1;
}
示例#17
0
oop bootstrap::get_object() {
  char type = get_char();

  if (type == '0') {
    int v = get_integer();
    // if (TraceBootstrap) std->print_cr("i %d", v);
    return as_smiOop(v);
  }
  if (type == '-') { 
    int v = get_integer();
    // if (TraceBootstrap) std->print_cr("i %d", -v);
    return as_smiOop(-v);
  }
  if (type == '3') {
    int v = get_integer();
    // if (TraceBootstrap) std->print_cr("r %d", v);
    return at(v);
  }

  int    size = get_integer();
  memOop m    = as_memOop(Universe::allocate_tenured(size));

  // Clear eventual padding area for byteArray, symbol, doubleByteArray.
  m->raw_at_put(size-1, smiOop_zero);

  // if (TraceBootstrap) lprintf("%c %d = 0x%lx\n", type, size, m);

  add(m);
  switch (type) {
    // Classes
    case 'A': KLASS_CASE(set_klassKlass_vtbl)
    case 'B': KLASS_CASE(set_smiKlass_vtbl)
    case 'C': KLASS_CASE(set_memOopKlass_vtbl)
    case 'D': KLASS_CASE(set_byteArrayKlass_vtbl)
    case 'E': KLASS_CASE(set_doubleByteArrayKlass_vtbl)
    case 'F': KLASS_CASE(set_objArrayKlass_vtbl)
    case 'G': KLASS_CASE(set_symbolKlass_vtbl)
    case 'H': KLASS_CASE(set_doubleKlass_vtbl)
    case 'I': KLASS_CASE(set_associationKlass_vtbl)
    case 'J': KLASS_CASE(set_methodKlass_vtbl)
    case 'K': KLASS_CASE(set_blockClosureKlass_vtbl)
    case 'L': KLASS_CASE(set_contextKlass_vtbl)
    case 'M': KLASS_CASE(set_proxyKlass_vtbl)
    case 'N': KLASS_CASE(set_mixinKlass_vtbl)
    case 'O': KLASS_CASE(set_weakArrayKlass_vtbl)
    case 'P': KLASS_CASE(set_processKlass_vtbl)
    case 'Q': KLASS_CASE(set_doubleValueArrayKlass_vtbl)
    case 'R': KLASS_CASE(set_vframeKlass_vtbl)
              // Objects
    case 'a': OBJECT_ERROR("klass")
    case 'b': OBJECT_ERROR("smi")
    case 'c': OBJECT_CASE(memOop);
    case 'd': OBJECT_CASE(byteArrayOop);
    case 'e': OBJECT_CASE(doubleByteArrayOop);
    case 'f': OBJECT_CASE(objArrayOop)
    case 'g': SYMBOL_CASE(symbolOop);
    case 'h': OBJECT_CASE(doubleOop);
    case 'i': OBJECT_CASE(associationOop);
    case 'j': OBJECT_CASE(methodOop);
    case 'k': OBJECT_ERROR("blockClosure")
    case 'l': OBJECT_ERROR("context")
    case 'm': OBJECT_ERROR("proxy")
    case 'n': OBJECT_CASE(mixinOop)
    case 'o': OBJECT_ERROR("weakArrayOop")
    case 'p': OBJECT_CASE(processOop)
    default: fatal("unknown object type");
  }

  return m;
}
示例#18
0
static int linenoiseEdit(struct current *current) {
    int history_index = 0;

    /* The latest history entry is always our current buffer, that
     * initially is just an empty string. */
    linenoiseHistoryAdd("");

    set_current(current, "");
    refreshLine(current->prompt, current);

    while(1) {
        int dir = -1;
        int c = fd_read(current);

#ifndef NO_COMPLETION
        /* Completion is forbidden for hidden input mode.
         * Only autocomplete when the callback is set. It returns < 0 when
         * there was an error reading from fd. Otherwise it will return the
         * character that should be handled next. */
        if (c == '\t' &&
            !is_hidden &&
            current->pos == current->chars &&
            completionCallback != NULL) {
            c = completeLine(current);
            /* Return on errors */
            if (c < 0) return current->len;
            /* Read next character when 0 */
            if (c == 0) continue;
        }
#endif

process_char:
        if (c == -1) return current->len;
#ifdef USE_TERMIOS
        if (c == 27) {   /* escape sequence */
            c = check_special(current->fd);
        }
#endif
        switch(c) {
        case '\r':    /* enter */
            history_len--;
            free(history[history_len]);
            return current->len;
        case ctrl('C'):     /* ctrl-c */
            errno = EAGAIN;
            return -1;
        case 127:   /* backspace */
        case ctrl('H'):
            if (remove_char(current, current->pos - 1) == 1) {
                refreshLine(current->prompt, current);
            }
            break;
        case ctrl('D'):     /* ctrl-d */
            if (current->len == 0) {
                /* Empty line, so EOF */
                history_len--;
                free(history[history_len]);
                return -1;
            }
            /* Otherwise fall through to delete char to right of cursor */
        case SPECIAL_DELETE:
            if (remove_char(current, current->pos) == 1) {
                refreshLine(current->prompt, current);
            }
            break;
        case SPECIAL_INSERT:
            /* Ignore. Expansion Hook.
             * Future possibility: Toggle Insert/Overwrite Modes
             */
            break;
        case ctrl('W'):    /* ctrl-w, delete word at left. save deleted chars */
            /* eat any spaces on the left */
            {
                int pos = current->pos;
                while (pos > 0 && get_char(current, pos - 1) == ' ') {
                    pos--;
                }

                /* now eat any non-spaces on the left */
                while (pos > 0 && get_char(current, pos - 1) != ' ') {
                    pos--;
                }

                if (remove_chars(current, pos, current->pos - pos)) {
                    refreshLine(current->prompt, current);
                }
            }
            break;
        case ctrl('R'):    /* ctrl-r */
            /* Hidden input mode disables use of the history */
            if (!is_hidden) {
                /* Display the reverse-i-search prompt and process chars */
                char rbuf[50];
                char rprompt[80];
                int rchars = 0;
                int rlen = 0;
                int searchpos = history_len - 1;

                rbuf[0] = 0;
                while (1) {
                    int n = 0;
                    const char *p = NULL;
                    int skipsame = 0;
                    int searchdir = -1;

                    snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
                    refreshLine(rprompt, current);
                    c = fd_read(current);
                    if (c == ctrl('H') || c == 127) {
                        if (rchars) {
                            int p = utf8_index(rbuf, --rchars);
                            rbuf[p] = 0;
                            rlen = strlen(rbuf);
                        }
                        continue;
                    }
#ifdef USE_TERMIOS
                    if (c == 27) {
                        c = check_special(current->fd);
                    }
#endif
                    if (c == ctrl('P') || c == SPECIAL_UP) {
                        /* Search for the previous (earlier) match */
                        if (searchpos > 0) {
                            searchpos--;
                        }
                        skipsame = 1;
                    }
                    else if (c == ctrl('N') || c == SPECIAL_DOWN) {
                        /* Search for the next (later) match */
                        if (searchpos < history_len) {
                            searchpos++;
                        }
                        searchdir = 1;
                        skipsame = 1;
                    }
                    else if (c >= ' ') {
                        if (rlen >= (int)sizeof(rbuf) + 3) {
                            continue;
                        }

                        n = utf8_getchars(rbuf + rlen, c);
                        rlen += n;
                        rchars++;
                        rbuf[rlen] = 0;

                        /* Adding a new char resets the search location */
                        searchpos = history_len - 1;
                    }
                    else {
                        /* Exit from incremental search mode */
                        break;
                    }

                    /* Now search through the history for a match */
                    for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
                        p = strstr(history[searchpos], rbuf);
                        if (p) {
                            /* Found a match */
                            if (skipsame && strcmp(history[searchpos], current->buf) == 0) {
                                /* But it is identical, so skip it */
                                continue;
                            }
                            /* Copy the matching line and set the cursor position */
                            set_current(current,history[searchpos]);
                            current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
                            break;
                        }
                    }
                    if (!p && n) {
                        /* No match, so don't add it */
                        rchars--;
                        rlen -= n;
                        rbuf[rlen] = 0;
                    }
                }
                if (c == ctrl('G') || c == ctrl('C')) {
                    /* ctrl-g terminates the search with no effect */
                    set_current(current, "");
                    c = 0;
                }
                else if (c == ctrl('J')) {
                    /* ctrl-j terminates the search leaving the buffer in place */
                    c = 0;
                }
                /* Go process the char normally */
                refreshLine(current->prompt, current);
                goto process_char;
            }
            break;
        case ctrl('T'):    /* ctrl-t */
            if (current->pos > 0 && current->pos <= current->chars) {
                /* If cursor is at end, transpose the previous two chars */
                int fixer = (current->pos == current->chars);
                c = get_char(current, current->pos - fixer);
                remove_char(current, current->pos - fixer);
                insert_char(current, current->pos - 1, c);
                refreshLine(current->prompt, current);
            }
            break;
        case ctrl('V'):    /* ctrl-v */
            if (has_room(current, 3)) {
                /* Insert the ^V first */
                if (insert_char(current, current->pos, c)) {
                    refreshLine(current->prompt, current);
                    /* Now wait for the next char. Can insert anything except \0 */
                    c = fd_read(current);

                    /* Remove the ^V first */
                    remove_char(current, current->pos - 1);
                    if (c != -1) {
                        /* Insert the actual char */
                        insert_char(current, current->pos, c);
                    }
                    refreshLine(current->prompt, current);
                }
            }
            break;
        case ctrl('B'):
        case SPECIAL_LEFT:
            if (current->pos > 0) {
                current->pos--;
                refreshLine(current->prompt, current);
            }
            break;
        case ctrl('F'):
        case SPECIAL_RIGHT:
            if (current->pos < current->chars) {
                current->pos++;
                refreshLine(current->prompt, current);
            }
            break;
        case SPECIAL_PAGE_UP:
          dir = history_len - history_index - 1; /* move to start of history */
          goto history_navigation;
        case SPECIAL_PAGE_DOWN:
          dir = -history_index; /* move to 0 == end of history, i.e. current */
          goto history_navigation;
        case ctrl('P'):
        case SPECIAL_UP:
            dir = 1;
          goto history_navigation;
        case ctrl('N'):
        case SPECIAL_DOWN:
history_navigation:
            /* Hidden input mode disables use of the history */
            if (!is_hidden && history_len > 1) {
                /* Update the current history entry before to
                 * overwrite it with tne next one. */
                free(history[history_len - 1 - history_index]);
                history[history_len - 1 - history_index] = strdup(current->buf);
                /* Show the new entry */
                history_index += dir;
                if (history_index < 0) {
                    history_index = 0;
                    break;
                } else if (history_index >= history_len) {
                    history_index = history_len - 1;
                    break;
                }
                set_current(current, history[history_len - 1 - history_index]);
                refreshLine(current->prompt, current);
            }
            break;
        case ctrl('A'): /* Ctrl+a, go to the start of the line */
        case SPECIAL_HOME:
            current->pos = 0;
            refreshLine(current->prompt, current);
            break;
        case ctrl('E'): /* ctrl+e, go to the end of the line */
        case SPECIAL_END:
            current->pos = current->chars;
            refreshLine(current->prompt, current);
            break;
        case ctrl('U'): /* Ctrl+u, delete to beginning of line, save deleted chars. */
            if (remove_chars(current, 0, current->pos)) {
                refreshLine(current->prompt, current);
            }
            break;
        case ctrl('K'): /* Ctrl+k, delete from current to end of line, save deleted chars. */
            if (remove_chars(current, current->pos, current->chars - current->pos)) {
                refreshLine(current->prompt, current);
            }
            break;
        case ctrl('Y'): /* Ctrl+y, insert saved chars at current position */
            if (current->capture && insert_chars(current, current->pos, current->capture)) {
                refreshLine(current->prompt, current);
            }
            break;
        case ctrl('L'): /* Ctrl+L, clear screen */
            clearScreen(current);
            /* Force recalc of window size for serial terminals */
            current->cols = 0;
            refreshLine(current->prompt, current);
            break;
        default:
            /* Only tab is allowed without ^V */
            if (c == '\t' || c >= ' ') {
                if (insert_char(current, current->pos, c) == 1) {
                    refreshLine(current->prompt, current);
                }
            }
            break;
        }
    }
    return current->len;
}
示例#19
0
文件: isearch.c 项目: Bootz/OpenFW
isearch(f, n)
{
    int			status;		/* Search status */
    int			col;		/* prompt column */
    register int	cpos;		/* character number in search string  */
    register int	c;		/* current input character */
    char		pat_save[NPAT];	/* Saved copy of the old pattern str  */
    LINE		*curline;	/* Current line on entry	      */
    int			curoff;		/* Current offset on entry	      */
    int			init_direction;	/* The initial search direction	      */

    /* Initialize starting conditions */

    cmd_reexecute = -1;		/* We're not re-executing (yet?)      */
    cmd_offset = 0;			/* Start at the beginning of the buff */
    cmd_buff[0] = '\0';		/* Init the command buffer	      */
    strncpy (pat_save, pat, NPAT);	/* Save the old pattern string	      */
    curline = curwp->w_dotp;		/* Save the current line pointer      */
    curoff  = curwp->w_doto;		/* Save the current offset	      */
    init_direction = n;			/* Save the initial search direction  */

    /* This is a good place to start a re-execution: */

start_over:

    /* ask the user for the text of a pattern */
    col = promptpattern("ISearch: ");		/* Prompt, remember the col   */

    cpos = 0;					/* Start afresh		      */
    status = TRUE;				/* Assume everything's cool   */

    /*
       Get the first character in the pattern.  If we get an initial Control-S
       or Control-R, re-use the old search string and find the first occurrence
     */

    c = get_char();				/* Get the first character    */
    if ((c == IS_FORWARD) ||
        (c == IS_REVERSE) ||
        (c == IS_VMSFORW))			/* Reuse old search string?   */
    {
    	for (cpos = 0; pat[cpos] != 0; cpos++)	/* Yup, find the length	      */
    	    col = echochar(pat[cpos],col);	/*  and re-echo the string    */
	if (c == IS_REVERSE) {			/* forward search?	      */
	    n = -1;				/* No, search in reverse      */
	    backchar (TRUE, 1);			/* Be defensive about EOB     */
	} else
	    n = 1;				/* Yes, search forward	      */
	status = scanmore(pat,n,status);	/* Do the search	      */
	c = get_char ();			/* Get another character      */
    }

    /* Top of the per character loop */
        	
    for (;;)					/* ISearch per character loop */
    {
	/* Check for magic characters first: */
	/* Most cases here change the search */

	switch (c)				/* dispatch on the input char */
	{
	  case IS_ABORT:			/* If abort search request    */
	    return(FALSE);			/* Quit searching again	      */

	  case IS_REVERSE:			/* If backward search	      */
	  case IS_FORWARD:			/* If forward search	      */
	  case IS_VMSFORW:			/*  of either flavor	      */
	    if (c == IS_REVERSE)		/* If reverse search	      */
		n = -1;				/* Set the reverse direction  */
	    else				/* Otherwise, 		      */
		n = 1;				/*  go forward		      */
	    status = scanmore(pat,n,TRUE);	/* Start the search again     */
	    c = get_char ();			/* Get the next char	      */
	    continue;				/* Go continue with the search*/

	  case IS_QUIT:				/* Want to quit searching?    */
	    return (TRUE);			/* Quit searching now	      */

	  case IS_NEWLINE:			/* Carriage return	      */
	    c = '\n';				/* Make it a new line	      */
	    break;				/* Make sure we use it	      */

	  case IS_QUOTE:			/* Quote character	      */
	  case IS_VMSQUOTE:			/*  of either variety	      */
	    c = get_char ();			/* Get the next char	      */

	  case IS_TAB:				/* Generically allowed	      */
	  case '\n':				/*  controlled characters     */
	    break;				/* Make sure we use it	      */

	  case IS_BACKSP:			/* If a backspace:            */
	  case IS_RUBOUT:			/*  or if a Rubout:	      */
	    if (cmd_offset <= 1)		/* Anything to delete?	      */
		return (TRUE);			/* No, just exit	      */
	    --cmd_offset;			/* Back up over the Rubout    */
	    cmd_buff[--cmd_offset] = '\0'; /* Yes, delete last char   */
	    curwp->w_dotp = curline;		/* Reset the line pointer     */
	    curwp->w_doto = curoff;		/*  and the offset	      */
	    n = init_direction;			/* Reset the search direction */
	    strncpy (pat, pat_save, NPAT);	/* Restore the old search str */
	    cmd_reexecute = 0;		/* Start the whole mess over  */
	    goto start_over;			/* Let it take care of itself */

	  /* Presumably a quasi-normal character comes here */

	  default:				/* All other chars    	      */
	    if (c < ' ')			/* Is it printable?	      */
	    {					/* Nope.		      */
		reeat (c);			/* Re-eat the char	      */
		return (TRUE);			/* And return the last status */
	    }
	}  /* Switch */

	/* I guess we got something to search for, so search for it	      */

	pat[cpos++] = c;			/* put the char in the buffer */
	if (cpos >= NPAT)			/* too many chars in string?  */
	{					/* Yup.  Complain about it    */
	    mlwrite("? Search string too long");
	    return(TRUE);			/* Return an error	      */
	}
	pat[cpos] = 0;				/* null terminate the buffer  */
	col = echochar(c,col);			/* Echo the character	      */
	if (!status) {				/* If we lost last time	      */
	    (*term.t_putchar)(BELL);		/* Feep again		      */
	    (*term.t_flush)();			/* see that the feep feeps    */
	} else					/* Otherwise, we must have won*/
	    if (!(status = checknext(c,pat,n,status))) /* See if match	      */
		status = scanmore(pat,n,TRUE);	/*  or find the next match    */
	c = get_char ();			/* Get the next char	      */
    } /* for {;;} */
}