Пример #1
0
/* -----------------------------------------------------------------------------
 * nextchar()
 * 
 * Returns the next character from the scanner or 0 if end of the string.
 * ----------------------------------------------------------------------------- */
static char nextchar(Scanner *s) {
  int nc;
  if (!s->str)
    return 0;
  while ((nc = Getc(s->str)) == EOF) {
    Delete(s->str);
    s->str = 0;
    Delitem(s->scanobjs, 0);
    if (Len(s->scanobjs) == 0)
      return 0;
    s->str = Getitem(s->scanobjs, 0);
    s->line = Getline(s->str);
    DohIncref(s->str);
  }
  if ((nc == '\n') && (!s->freeze_line)) 
    s->line++;
  Putc(nc,s->text);
  return (char)nc;
}
Пример #2
0
int main(void)
{
	VGA_Init();
  USART_Init();
	PS2_Init();
  ANSI_Init();

	while(1)
	{
		if(FIFO_ReadAvail((FIFO*)RxBuf))
			ANSI_FSM(Getc((FIFO*)RxBuf));

		if(FIFO_ReadAvail((FIFO*)PS2_Buf))
			PS2_Task();
		
		if(Cursor.Update)
			Cursor_Task();
		
	}
}
Пример #3
0
String *Swig_string_lccase(String *s) {
  String *ns;
  int first = 1;
  int after_underscore = 0;
  int c;
  ns = NewStringEmpty();

  Seek(s, 0, SEEK_SET);
  while ((c = Getc(s)) != EOF) {
    if (c == '_') {
      after_underscore = 1;
      continue;
    }
    if (first) {
      Putc(tolower(c), ns);
      first = 0;
    } else {
      Putc(after_underscore ? toupper(c) : c, ns);
    }
    after_underscore = 0;
  }
  return ns;
}
Пример #4
0
/* -----------------------------------------------------------------------------
 * nextchar()
 * 
 * Returns the next character from the scanner or 0 if end of the string.
 * ----------------------------------------------------------------------------- */
static char
nextchar(SwigScanner *s)
{
  char c[2] = {0,0};
  int nc;
  if (!s->str) return 0;
  while ((nc = Getc(s->str)) == EOF) {
    Delete(s->str);
    s->str = 0;
    Delitem(s->scanobjs,0);
    if (Len(s->scanobjs) == 0) return 0;
    s->str = Getitem(s->scanobjs,0);
    if (s->str) {
      s->line = Getline(s->str);
      DohIncref(s->str);
    }
  }
  if (nc == '\n') s->line++;
  c[0] = (char) nc;
  c[1] = 0;
  Append(s->text,c);
  return c[0];
}
Пример #5
0
char nextchar() {
    int c = 0;

    while (LEX_in) {
      c = Getc(LEX_in);
      if (c == EOF) {
	scanner_close();
      } else {
	break;
      }
    }
    if (!LEX_in) return 0;
    if (yylen >= YYBSIZE) {
      Printf(stderr,"** FATAL ERROR.  Buffer overflow in scanner.cxx.\nReport this to [email protected].\n");
      exit (EXIT_FAILURE);
    }
    yytext[yylen] = c;
    yylen++;
    if (c == '\n') {
      cparse_line++;
    }
    return(c);
}
Пример #6
0
String *Swig_string_typecode(String *s) {
  String *ns;
  int c;
  String *tc;
  ns = NewStringEmpty();
  while ((c = Getc(s)) != EOF) {
    if (c == '`') {
      String *str = 0;
      tc = NewStringEmpty();
      while ((c = Getc(s)) != EOF) {
	if (c == '`')
	  break;
	Putc(c, tc);
      }
      str = SwigType_str(tc, 0);
      Append(ns, str);
      Delete(str);
    } else {
      Putc(c, ns);
      if (c == '\'') {
	while ((c = Getc(s)) != EOF) {
	  Putc(c, ns);
	  if (c == '\'')
	    break;
	  if (c == '\\') {
	    c = Getc(s);
	    Putc(c, ns);
	  }
	}
      } else if (c == '\"') {
	while ((c = Getc(s)) != EOF) {
	  Putc(c, ns);
	  if (c == '\"')
	    break;
	  if (c == '\\') {
	    c = Getc(s);
	    Putc(c, ns);
	  }
	}
      }
    }
  }
  return ns;
}
Пример #7
0
String *Swig_string_typecode(String *s) {
  String *ns;
  int c;
  String *tc;
  ns = NewString("");
  while ((c = Getc(s)) != EOF) {
    if (c == '`') {
      tc = NewString("");
      while ((c = Getc(s)) != EOF) {
	if (c == '`') break;
	Putc(c,tc);
      }
      Printf(ns,"%s",SwigType_str(tc,0));
    } else {
      Putc(c,ns);
      if (c == '\'') {
	while ((c = Getc(s)) != EOF) {
	  Putc(c,ns);
	  if (c == '\'') break;
	  if (c == '\\') {
	    c = Getc(s);
	    Putc(c,ns);
	  }
	}
      } else if (c == '\"') {
	while ((c = Getc(s)) != EOF) {
	  Putc(c,ns);
	  if (c == '\"') break;
	  if (c == '\\') {
	    c = Getc(s);
	    Putc(c,ns);
	  }
	}
      }
    }
  }
  return ns;
}
Пример #8
0
/**
 * This routine gets characters from the filter's underlying file, and
 * decodes them according to the runlength scheme. It returns the number
 * of bytes placed into the filter's buffer through the ret_bytes arguments.
 * This number is negative if the EOD is found.
 * It returns FALSE if anything goes wrong. The caller is responsible for
 * setting the IOERROR condition.
 *
 * \param[in,out]  filter       Input and output streams for the filter
 * \param[out]     ret_bytes    Number of bytes placed in output buffer
 *                              (negative if EOD found)
 * \return                      Success status
 */
static Bool runlengthDecodeBuffer(FILELIST *filter, int32 *ret_bytes)
{
  int32    count, length;
  FILELIST *uflptr;
  uint8    *ptr;

  HQASSERT(filter, "NULL /RunLengthDecode filter");

  uflptr = filter->underlying_file;
  ptr = filter->buffer;

  HQASSERT(uflptr, "NULL /RunLengthDecode input buffer");
  HQASSERT(ptr, "NULL /RunLengthDecode output buffer");

  count = 0;
  for (;;)
  {
    register int32 ch = Getc(uflptr);

    if ( ch == EOF || ch == EOD )
    {
      /* found the EOD marker, or EOF on underlying file */
      count = -count;
      break;
    }
    if ( ch < 128 ) /* ch + 1 bytes to follow */
    {
      length = ch + 1;
      if ( ( count + length ) <= filter->buffersize )
      {
        count += length;
        /* If buffer is full enough avoid Getc() loop overhead */
        if ( length < uflptr->count )
        {
          HqMemCpy(ptr, uflptr->ptr, length);
          uflptr->count -= length;
          uflptr->ptr   += length;
          ptr += length;
        }
        else
        {
          while ( length-- )
          {
            if ( (ch = Getc(uflptr)) == EOF )
              return error_handler(IOERROR);
            *ptr++ = (uint8)ch;
          }
        }
      }
      else /* current run will not fit in */
      {
        UnGetc(ch, uflptr);
        break;
      }
    }
    else /* ch > 128, replicate single byte */
    {
      length = 257 - ch;
      if ( ( count + length ) <= filter->buffersize )
      {
        if (( ch = Getc( uflptr )) == EOF )
          return error_handler(IOERROR);
        count += length;
        HqMemSet8(ptr, (uint8)ch, length);
        ptr += length;
      }
      else /* current replciation will not fit into buffer */
      {
        UnGetc(ch , uflptr);
        break;
      }
    }
  }
  *ret_bytes = count;
  return TRUE;
}
Пример #9
0
int main(int argc, char **argv) {
    FILE	*f;
    char	*s;
    char	*p;
    int		ch;
    int		left;
    int		prnames = 0;
    int		initopt = 0;
    int		srchopt = 0;
    int		clearit = 0;
    int		initline = 0;
    char	initbuf[INIT_BUF];

    setlocale(LC_ALL, "");
    bindtextdomain(PACKAGE, LOCALEDIR);
    textdomain(PACKAGE);

    nfiles = argc;
    fnames = argv;
    setlocale(LC_ALL, "");
    initterm ();

    /* Auto set no scroll on when binary is called page */
    if (!(strcmp(program_invocation_short_name, "page")))
       noscroll++;

    prepare_line_buffer();

    nscroll = Lpp/2 - 1;
    if (nscroll <= 0)
	nscroll = 1;

    if ((s = getenv("MORE")) != NULL)
	    argscan(s);

    while (--nfiles > 0) {
	if ((ch = (*++fnames)[0]) == '-') {
	    argscan(*fnames+1);
	}
	else if (ch == '+') {
	    s = *fnames;
	    if (*++s == '/') {
		srchopt++;
		for (++s, p = initbuf; p < initbuf + (INIT_BUF - 1) && *s != '\0';)
		    *p++ = *s++;
		*p = '\0';
	    }
	    else {
		initopt++;
		for (initline = 0; *s != '\0'; s++)
		    if (isdigit (*s))
			initline = initline*10 + *s -'0';
		--initline;
	    }
	}
	else break;
    }
    /* allow clreol only if Home and eraseln and EodClr strings are
     *  defined, and in that case, make sure we are in noscroll mode
     */
    if (clreol) {
        if((Home == NULL) || (*Home == '\0') ||
	   (eraseln == NULL) || (*eraseln == '\0') ||
           (EodClr == NULL) || (*EodClr == '\0') )
	      clreol = 0;
	else noscroll = 1;
    }
    if (dlines == 0)
	    dlines = Lpp - 1;	/* was: Lpp - (noscroll ? 1 : 2) */
    left = dlines;
    if (nfiles > 1)
	prnames++;
    if (!no_intty && nfiles == 0)
	usage(stderr);
    else
	f = stdin;
    if (!no_tty) {
	signal(SIGQUIT, onquit);
	signal(SIGINT, end_it);
#ifdef SIGWINCH
	signal(SIGWINCH, chgwinsz);
#endif /* SIGWINCH */
	if (signal (SIGTSTP, SIG_IGN) == SIG_DFL) {
	    signal(SIGTSTP, onsusp);
	    catch_susp++;
	}
	stty (fileno(stderr), &otty);
    }
    if (no_intty) {
	if (no_tty)
	    copy_file (stdin);
	else {
	    if ((ch = Getc (f)) == '\f')
		doclear();
	    else {
		Ungetc (ch, f);
		if (noscroll && (ch != EOF)) {
		    if (clreol)
			home ();
		    else
			doclear ();
		}
	    }
	    if (srchopt)
	    {
		search (initbuf, stdin, 1);
		if (noscroll)
		    left--;
	    }
	    else if (initopt)
		skiplns (initline, stdin);
	    screen (stdin, left);
	}
	no_intty = 0;
	prnames++;
	firstf = 0;
    }

    while (fnum < nfiles) {
	if ((f = checkf (fnames[fnum], &clearit)) != NULL) {
	    context.line = context.chrctr = 0;
	    Currline = 0;
	    if (firstf) sigsetjmp (restore, 1);
	    if (firstf) {
		firstf = 0;
		if (srchopt) {
		    search (initbuf, f, 1);
		    if (noscroll)
			left--;
		}
		else if (initopt)
		    skiplns (initline, f);
	    }
	    else if (fnum < nfiles && !no_tty) {
		sigsetjmp (restore, 1);
		left = command (fnames[fnum], f);
	    }
	    if (left != 0) {
		if ((noscroll || clearit) && (file_size != LONG_MAX)) {
		    if (clreol)
			home ();
		    else
			doclear ();
		}
		if (prnames) {
		    if (bad_so)
			erasep (0);
		    if (clreol)
			cleareol ();
		    putsout("::::::::::::::");
		    if (promptlen > 14)
			erasep (14);
		    putchar('\n');
		    if(clreol) cleareol();
		    puts(fnames[fnum]);
		    if(clreol) cleareol();
		    puts("::::::::::::::");
		    if (left > Lpp - 4)
			left = Lpp - 4;
		}
		if (no_tty)
		    copy_file (f);
		else {
		    within++;
		    screen(f, left);
		    within = 0;
		}
	    }
	    sigsetjmp (restore, 1);
	    fflush(stdout);
	    fclose(f);
	    screen_start.line = screen_start.chrctr = 0L;
	    context.line = context.chrctr = 0L;
	}
	fnum++;
	firstf = 0;
    }
    reset_tty ();
    exit(EXIT_SUCCESS);
}
Пример #10
0
/*
 * Read a command and do it. A command consists of an optional integer
 * argument followed by the command character.  Return the number of lines
 * to display in the next screenful.  If there is nothing more to display
 * in the current file, zero is returned.
 */
int
command(char *filename, FILE *f)
{
	int nlines;
	int retval;
	int ch;
	char colonch;
	int done;
	char comchar, cmdbuf[80];

#define ret(val) retval=val;done++;break

	retval = done = 0;
	if (!errors)
		prompt(filename);
	else
		errors = 0;
	for (;;) {
		nlines = number(&comchar);
		lastp = colonch = 0;
		if (comchar == '.') {	/* Repeat last command */
			lastp++;
			comchar = lastcmd;
			nlines = lastarg;
			if (lastcmd == ':')
				colonch = lastcolon;
		}
		lastcmd = comchar;
		lastarg = nlines;
		if (comchar == otty.c_cc[VERASE]) {
			kill_line();
			prompt(filename);
			continue;
		}
		switch (comchar) {
		case ':':
			retval = colon(filename, colonch, nlines);
			if (retval >= 0)
				done++;
			break;
		case 'b':
		case ctrl('B'):
		    {
			int initline;

			if (no_intty) {
				write(STDERR_FILENO, &bell, 1);
				return (-1);
			}

			if (nlines == 0)
				nlines++;

			putchar('\r');
			erasep(0);
			putchar('\n');
			if (clreol)
				cleareol();
			printf("...back %d page", nlines);
			if (nlines > 1)
				fputs("s\n", stdout);
			else
				putchar('\n');

			if (clreol)
				cleareol();
			putchar('\n');

			initline = Currline - (off_t)dlines * (nlines + 1);
			if (!noscroll)
				--initline;
			if (initline < 0)
				initline = 0;
			Fseek(f, (off_t)0);
			Currline = 0; /* skiplns() will make Currline correct */
			skiplns(initline, f);
			ret(dlines);
		    }
		case ' ':
		case 'z':
			if (nlines == 0)
				nlines = dlines;
			else if (comchar == 'z')
				dlines = nlines;
			ret(nlines);
		case 'd':
		case ctrl('D'):
			if (nlines != 0)
				nscroll = nlines;
			ret(nscroll);
		case 'q':
		case 'Q':
			end_it();
		case 's':
		case 'f':
			if (nlines == 0)
				nlines++;
			if (comchar == 'f')
				nlines *= dlines;
			putchar('\r');
			erasep(0);
			putchar('\n');
			if (clreol)
				cleareol();
			printf("...skipping %d line", nlines);
			if (nlines > 1)
				fputs("s\n", stdout);
			else
				putchar('\n');

			if (clreol)
				cleareol();
			putchar('\n');

			while (nlines > 0) {
				while ((ch = Getc(f)) != '\n') {
					if (ch == EOF) {
						retval = 0;
						done++;
						goto endsw;
					}
				}
				Currline++;
				nlines--;
			}
			ret(dlines);
		case '\n':
			if (nlines != 0)
				dlines = nlines;
			else
				nlines = 1;
			ret(nlines);
		case '\f':
			if (!no_intty) {
				doclear();
				Fseek(f, screen_start.chrctr);
				Currline = screen_start.line;
				ret(dlines);
			} else {
				write(STDERR_FILENO, &bell, 1);
				break;
			}
		case '\'':
			if (!no_intty) {
				kill_line();
				fputs("\n***Back***\n\n", stdout);
				Fseek(f, context.chrctr);
				Currline = context.line;
				ret(dlines);
			} else {
				write(STDERR_FILENO, &bell, 1);
				break;
			}
		case '=':
			kill_line();
			promptlen = printf("%lld", (long long)Currline);
			fflush(stdout);
			break;
		case 'n':
			lastp++;
		case '/':
			if (nlines == 0)
				nlines++;
			kill_line();
			putchar('/');
			promptlen = 1;
			fflush(stdout);
			if (lastp) {
				/* Use previous r.e. */
				write(STDERR_FILENO, "\r", 1);
				if (search(NULL, f, nlines) < 0)
					break;
			} else {
				if (ttyin(cmdbuf, sizeof(cmdbuf) - 2, '/') < 0) {
					kill_line();
					prompt(filename);
					continue;
				}
				write(STDERR_FILENO, "\r", 1);
				if (search(cmdbuf, f, nlines) < 0)
					break;
			}
			ret(dlines-1);
		case '?':
		case 'h':
			if (noscroll)
				doclear();
			fputs(more_help, stdout);
			prompt(filename);
			break;
		default:
			if (dum_opt) {
				kill_line();
				if (Senter && Sexit) {
					tputs(Senter, 1, putch);
					fputs(DUM_ERROR, stdout);
					promptlen = sizeof(DUM_ERROR) - 1 +
					    (2 * soglitch);
					tputs(Sexit, 1, putch);
				} else {
					fputs(DUM_ERROR, stdout);
					promptlen = sizeof(DUM_ERROR) - 1;
				}
				fflush(stdout);
			} else
				write(STDERR_FILENO, &bell, 1);
			break;
		}
		if (done)
			break;
	}
	putchar('\r');
endsw:
	inwait = 0;
	notell++;
	return (retval);
}
Пример #11
0
lex()
{
  int c, d;
  char *s;

  if (regexflg)
	return sym = scanreg();
next:
  while ((c = Getc()) == ' ' || c == '\t')
	;
  while (c == '#')
	for (c = Getc(); c != '\n'; c = Getc())
		;
  switch (c) {
  case '\\':
	if ((c = Getc()) == '\n') {
		lineno++;
		goto next;
	}
	break;
  case '\n':
	lineno++;
	break;
  }
  switch (c) {
  case EOF:	return sym = 0;
  case '+':	return sym = follow2('=', '+', ADDEQ, INC, ADD);
  case '-':	return sym = follow2('=', '-', SUBEQ, DEC, SUB);
  case '*':	return sym = follow('=', MULTEQ, MULT);
  case '/':	return sym = follow('=', DIVEQ, DIV);
  case '%':	return sym = follow('=', MODEQ, MOD);
  case '^':	return sym = follow('=', POWEQ, POWER);
  case '=':	return sym = follow('=', EQ, ASSIGN);
  case '!':	return sym = follow2('=', '~', NE, NOMATCH, NOT);
  case '&':	return sym = follow('&', AND, BINAND);
  case '|':	sym = follow('|', OR, BINOR);
		if (printflg && sym == BINOR)
			sym = R_POUT;
		return sym;
  case '<':	sym = follow2('=', '<', LE, SHIFTL, LT);
		if (getlineflg && sym == LT)
			sym = R_IN;
		return sym;
  case '>':	sym = follow2('=', '>', GE, SHIFTR, GT);
		if (printflg) {
			switch (sym) {
			case GT: sym = R_OUT; break;
			case SHIFTR: sym = R_APD; break;
			}
		}
		return sym;
  case '~':	return sym = MATCH; break;
  case ';': case '\n':	return sym = EOL;
  }
  if (isalpha(c) || c == '_') {
	for (s = text; isalnum(c) || c == '_'; ) {
		*s++ = c; c = Getc();
	}
	Ungetc(c);
	*s = '\0';
	if ((d = iskeywd(text)) == 0 &&
		(d = isbuiltin(text, &sym1)) == 0) {
			if (c == '(')
				return sym = CALL;
			else if (funflg) {
				if ((sym1 = isarg(text)) != -1)
					return sym = ARG;
			}
	}
	return sym = d ? d : IDENT;
  }
  else if (c == '.' || (isdigit(c))) {
	Ungetc(c);
	return sym = scannum(text);	/* NUMBER */
  }
  else if (c == '"')
	return sym = scanstr(text);	/* STRING */
  return sym = c;
}
Пример #12
0
/**
 * This routine gets characters from the filter's underlying file, and
 * decodes them according to the ascii85 scheme. It returns the number
 * of bytes placed into the filter's buffer through the ret_bytes arguments.
 * This number is negative if the EOD is found.
 * It returns FALSE if anything goes wrong.
 *
 * \param[in,out]  filter       Input and output streams for the filter
 * \param[out]     ret_bytes    Number of bytes placed in output buffer
 *                              (negative if EOD found)
 * \return                      Success status
 */
static Bool ascii85DecodeBuffer(FILELIST *filter, int32 *ret_bytes)
{
  ASCII85DECODESTATE *ascii85state ;
  uint32    *ptr, *end;
  int32     i5, nbytes;
  FILELIST  *in;
  FOURBYTES  fb;

  HQASSERT(filter, "NULL /ASCII85Decode filter");
  ascii85state = theIFilterPrivate( filter ) ;
  HQASSERT( ascii85state, "ascii85state NULL in ascii85DecodeBuffer." ) ;

  if (ascii85state->cached_error != NOT_AN_ERROR)
    return error_handler( ascii85state->cached_error ) ;

  in = filter->underlying_file;
  ptr = (uint32 *)(filter->buffer);
  end = ptr + (filter->buffersize/sizeof(uint32));
  asInt(fb) = 0;

  HQASSERT(in, "NULL /ASCII85Decode input buffer");
  HQASSERT(ptr,  "NULL /ASCII85Decode output buffer");

  for ( i5 = 0, nbytes = 0; ptr < end; )
  {
    /*
     * Optimised code for the typical case :
     *
     * 0xffffffff (ascii85)-> s8W-! == 82/23/54/12/0
     * So if the first byte is less than 's'
     * then we do not need to test for overflow
     */
    if ( i5 == 0 && in->count > 5 && in->ptr[0] >= '!' && in->ptr[0] < 's' &&
         IS85(in->ptr[1]) && IS85(in->ptr[2]) &&
         IS85(in->ptr[3]) && IS85(in->ptr[4]) )
    {
      FOURBYTES  b4;

      asInt(b4) = POWER4 * (uint32)(in->ptr[0] - 33) +
                  POWER3 * (uint32)(in->ptr[1] - 33) +
                  POWER2 * (uint32)(in->ptr[2] - 33) +
                  POWER1 * (uint32)(in->ptr[3] - 33) +
                           (uint32)(in->ptr[4] - 33);

      HighOrder4Bytes(asBytes(b4));
      *ptr++ = asInt(b4);
      in->count -= 5;
      in->ptr   += 5;
    }
    else
    {
      register int32 ch = Getc(in);

      if ( IS85(ch) ) /* Part of valid ascii85 5-tuple */
      {
        if ( i5 == 4 )
        {
          if ( asInt(fb) > MAXHIGH4BYTES )
            return error_handler(IOERROR);
          asInt(fb) = POWER4 * (uint32)asBytes(fb)[BYTE_INDEX(0)] +
                      POWER3 * (uint32)asBytes(fb)[BYTE_INDEX(1)] +
                      POWER2 * (uint32)asBytes(fb)[BYTE_INDEX(2)] +
                      POWER1 * (uint32)asBytes(fb)[BYTE_INDEX(3)] +
                               (uint32)(ch - 33);
          HighOrder4Bytes(asBytes(fb));
          *ptr++ = asInt(fb);
          i5 = 0;
          asInt(fb) = 0;
        }
        else
          asBytes(fb)[BYTE_INDEX(i5++)] = (uint8)(ch - 33);
      }
      else if ( ch == 'z') /* special zero case */
      {
        if ( i5 != 0 )
          return error_handler(IOERROR);
        *ptr++ = 0;
      }
      else if ((ch == EOF ) || ( ch == '~' )) /* found EOD marker */
      {
        nbytes = (int32)(sizeof(uint32)*(ptr - (uint32 *)(filter->buffer)));

        if ( isIIOError(in) )
          return FALSE;
        if ( ch == '~' )
        {
          do
          {
            ch = Getc(in);
          } while ( IsWhiteSpace(ch) );

          if ( ch != '>')
            return error_handler(IOERROR);
        }
        if ( i5 > 0 ) /* only partial 5-tuple */
        {
          if ( i5 == 1 )
            return delay_filter_error(ascii85state, IOERROR, ret_bytes, nbytes);
          if ( asInt( fb ) > MAXHIGH4BYTES )
            return error_handler( IOERROR );
          asInt(fb) = POWER4 * (uint32)asBytes(fb)[BYTE_INDEX(0)] +
                      POWER3 * (uint32)asBytes(fb)[BYTE_INDEX(1)] +
                      POWER2 * (uint32)asBytes(fb)[BYTE_INDEX(2)] +
                      POWER1 * (uint32)asBytes(fb)[BYTE_INDEX(3)];
          if ( (int32)asBytes(fb)[BYTE_INDEX(i5 - 1)] >= 128 ) /* carry 1 */
            asInt(fb) += (uint32) (1 << (( 4 - i5 + 1 ) * 8 ));
          HighOrder4Bytes(asBytes(fb));
          *ptr++ = asInt(fb);
          nbytes = -(nbytes + i5 - 1);
        }
        else
          nbytes = -nbytes;
        break;
      }
      else if ( !IsWhiteSpace(ch) ) /* skip spaces, everything else errors */
        return error_handler(IOERROR);
    }
  }
  if ( nbytes == 0 )
    nbytes = (int32)(sizeof(uint32)*(ptr - (uint32 *)(filter->buffer)));
  *ret_bytes = nbytes;
  return TRUE;
}
Пример #13
0
void Wrapper_compact_print(String *str, File *f) {
  String *ts, *tf;		/*temp string & temp file */
  int level = 0;
  int c, i;
  int empty = 1;
  int indent = 2;

  ts = NewStringEmpty();
  tf = NewStringEmpty();
  Seek(str, 0, SEEK_SET);

  while ((c = Getc(str)) != EOF) {
    if (c == '\"') {		/* string 1 */
      empty = 0;
      Putc(c, ts);
      while ((c = Getc(str)) != EOF) {
	if (c == '\\') {
	  Putc(c, ts);
	  c = Getc(str);
	}
	Putc(c, ts);
	if (c == '\"')
	  break;
      }
    } else if (c == '\'') {	/* string 2 */
      empty = 0;
      Putc(c, ts);
      while ((c = Getc(str)) != EOF) {
	if (c == '\\') {
	  Putc(c, ts);
	  c = Getc(str);
	}
	Putc(c, ts);
	if (c == '\'')
	  break;
      }
    } else if (c == '{') {	/* start of {...} */
      empty = 0;
      Putc(c, ts);
      if (Len(tf) == 0) {
	for (i = 0; i < level; i++)
	  Putc(' ', tf);
      } else if ((Len(tf) + Len(ts)) < Max_line_size) {
	Putc(' ', tf);
      } else {
	Putc('\n', tf);
	Printf(f, "%s", tf);
	Clear(tf);
	for (i = 0; i < level; i++)
	  Putc(' ', tf);
      }
      Append(tf, ts);
      Clear(ts);
      level += indent;
      while ((c = Getc(str)) != EOF) {
	if (!isspace(c)) {
	  Ungetc(c, str);
	  break;
	}
      }
    } else if (c == '}') {	/* end of {...} */
      empty = 0;
      if (Len(tf) == 0) {
	for (i = 0; i < level; i++)
	  Putc(' ', tf);
      } else if ((Len(tf) + Len(ts)) < Max_line_size) {
	Putc(' ', tf);
      } else {
	Putc('\n', tf);
	Printf(f, "%s", tf);
	Clear(tf);
	for (i = 0; i < level; i++)
	  Putc(' ', tf);
      }
      Append(tf, ts);
      Putc(c, tf);
      Clear(ts);
      level -= indent;
    } else if (c == '\n') {	/* line end */
      while ((c = Getc(str)) != EOF) {
	if (!isspace(c))
	  break;
      }
      if (c == '#') {
	Putc('\n', ts);
      } else if (c == '}') {
	Putc(' ', ts);
      } else if ((c != EOF) || (Len(ts) != 0)) {
	if (Len(tf) == 0) {
	  for (i = 0; i < level; i++)
	    Putc(' ', tf);
	} else if ((Len(tf) + Len(ts)) < Max_line_size) {
	  Putc(' ', tf);
	} else {
	  Putc('\n', tf);
	  Printf(f, "%s", tf);
	  Clear(tf);
	  for (i = 0; i < level; i++)
	    Putc(' ', tf);
	}
	Append(tf, ts);
	Clear(ts);
      }
      Ungetc(c, str);

      empty = 1;
    } else if (c == '/') {	/* comment */
      empty = 0;
      c = Getc(str);
      if (c != EOF) {
	if (c == '/') {		/* C++ comment */
	  while ((c = Getc(str)) != EOF) {
	    if (c == '\n') {
	      Ungetc(c, str);
	      break;
	    }
	  }
	} else if (c == '*') {	/* C comment */
	  int endstar = 0;
	  while ((c = Getc(str)) != EOF) {
	    if (endstar && c == '/') {	/* end of C comment */
	      break;
	    }
	    endstar = (c == '*');
	  }
	} else {
	  Putc('/', ts);
	  Putc(c, ts);
	}
      }
    } else if (c == '#') {	/* Preprocessor line */
      Putc('#', ts);
      while ((c = Getc(str)) != EOF) {
	Putc(c, ts);
	if (c == '\\') {	/* Continued line of the same PP */
	  c = Getc(str);
	  if (c == '\n')
	    Putc(c, ts);
	  else
	    Ungetc(c, str);
	} else if (c == '\n')
	  break;
      }
      if (!empty) {
	Append(tf, "\n");
      }
      Append(tf, ts);
      Printf(f, "%s", tf);
      Clear(tf);
      Clear(ts);
      for (i = 0; i < level; i++)
	Putc(' ', tf);
      empty = 1;
    } else {
      if (!empty || !isspace(c)) {
	Putc(c, ts);
	empty = 0;
      }
    }
  }
  if (!empty) {
    Append(tf, ts);
  }
  if (Len(tf) != 0)
    Printf(f, "%s", tf);
  Delete(ts);
  Delete(tf);
  Printf(f, "\n");
}
Пример #14
0
void prompt_code(){
	Putc(COM1, 96);					// GO command for trains
	Create(8, timer_code);
	int dfa_tid = Create(10, dfa_code);
	int train_tid = Create(10, train_code);
	int switch_tid = Create(10, switch_code);
	Create(10, sensor_code);
	
	char input, state;
	char buff[3];
	
	while (1){
		input = Getc(COM2);
		if (input == 'q'){
			Putc(COM1, 97);							// Stop command for trains
			Putc(COM2, input);						// ECHO
			// Printf(COM2, "\033[2J\033[1;1H");		// clear the screen
			Printf(COM2, " ");Printf(COM2, " ");Printf(COM2, " ");
			SHUTDOWN();								// CALL SHUTDOWN SYSCALL to shutdown the program
		}
		Send(dfa_tid, &input, sizeof(char), &buff, 3*sizeof(char));
		state = buff[2];
		switch (state){
			case DFA_FULL:
				Printf(COM2, "\033[s\033[%d;%dHPrompt is full!                  \033[u", CMD_OUT_ROW, CMD_OUT_COL);
				break;
			case DFA_INVALID:
				Printf(COM2, "\033[%d;%dHInvalid input!!!                       \033[%d;%dH", CMD_OUT_ROW, CMD_OUT_COL, CMD_ROW, CMD_COL);
				Printf(COM2, "\033[%d;%dH\033[s                    \033[u", CMD_ROW, CMD_COL);
				break;
			case DFA_OK:
				Putc(COM2, input);			// ECHO
				//Printf(COM2, "\033[s\033[%d;%dHTyping...                      \033[u", CMD_OUT_ROW, CMD_OUT_COL);
				break;
			case DFA_BACKSPACE:
				Printf(COM2, "%c %c", input, input);		// Echo
				//Printf(COM2, "\033[s\033[%d;%dHRemoving...    \033[u", CMD_OUT_ROW, CMD_OUT_COL);
				break;
			case DFA_NO_BACKSPACE:
				Printf(COM2, "\033[s\033[%d;%dH                                 \033[u", CMD_OUT_ROW, CMD_OUT_COL);
				break;
			case DFA_TR_SP:
				Printf(COM2, "\033[s\033[%d;%dHSetting speed of tr#%d to %d...  \033[u", CMD_OUT_ROW, CMD_OUT_COL, buff[1], buff[0]);
				Printf(COM2, "\033[%d;%dH\033[s                    \033[u", CMD_ROW, CMD_COL);
				// Send command to the train task to set speed of the train
				Send(train_tid, &buff, 2*sizeof(char), &input, sizeof(char));
				break;
			case DFA_TR_RV:
				Printf(COM2, "\033[s\033[%d;%dHReversing tr#%d...               \033[u", CMD_OUT_ROW, CMD_OUT_COL, buff[1], buff[0]);
				Printf(COM2, "\033[%d;%dH\033[s                    \033[u", CMD_ROW, CMD_COL);
				buff[0] = 15;
				Send(train_tid, &buff, 2*sizeof(char), &input, sizeof(char));
				break;
			case DFA_SW:
				Printf(COM2, "\033[s\033[%d;%dHThrowing sw#%d to %c...          \033[u", CMD_OUT_ROW, CMD_OUT_COL, buff[1], buff[0]);
				Printf(COM2, "\033[%d;%dH\033[s                    \033[u", CMD_ROW, CMD_COL);
				Send(switch_tid, &buff, 2*sizeof(char), &input, sizeof(char));
				break;
			default:
				Printf(COM2, "\033[s\033[%d;%dHDFA PROBLEM!!!                   \033[u", CMD_OUT_ROW, CMD_OUT_COL);
				Printf(COM2, "\033[%d;%dH\033[s                    \033[u", CMD_ROW, CMD_COL);
				break;
		}
	}
	Putc(COM1, 97);			// Stop command for trains
	
	Exit();
	kprintf("Unexpected return from Exit() at prompt_code\n\r");
}
Пример #15
0
/* ----------------------------------------------------------------------------
   function:            getstatement()     author:              Andrew Cave
   creation date:       19-Oct-1987        last modification:   ##-###-####
   arguments:           flptr .
   description:

   This procedure reads the characters from the underlying file "%lineedit"
   until a complete statement has been read in.  A complete
   statement  is  defined as one or more P.S. tokens terminated by a newline,
   such that  no  '{'  or  '(' is  left unmatched. This procedure should
   only be called from the %statementedit fillbuff routine. After reading
   a newline character, the lineedit file must be reopened if further
   characters are required to complete the statement.

   errors:
   IOERROR, SYNTAXERROR

---------------------------------------------------------------------------- */
static Bool getstatement(FILELIST *flptr)
{
  register int32 c , last ;
  register int32 curl_count ;   /* Used to check for correct number of '{'. */
  register int32 paren_count ;  /* Used to check for correct number of '('. */
  register FILELIST *lflptr ;   /* lineedit file */
  register uint8    *ptr ;
  register int32    count ;

  count = curl_count = paren_count = 0 ;
  ptr = theIPtr( flptr ) = theIBuffer( flptr ) ;
  lflptr = theIUnderFile( flptr ) ;

  if (! isIOpenFileFilterById( theIUnderFilterId( flptr ), lflptr)) {
    SetIIOErrFlag( flptr ) ;
    return error_handler(IOERROR);
  }

  if (( c = Getc( lflptr )) == EOF ) {
    SetIEofFlag( flptr ) ;
    if ( isIIOError( lflptr )) {
      SetIIOErrFlag( flptr ) ;
      return (*theIFileLastError( lflptr ))( lflptr ) ;
    }
    else
      return FALSE ;
  }
  UnGetc( c , lflptr ) ;

  for (;;) {

    if (( c = Getc( lflptr )) == EOF ) {
      SetIEofFlag( flptr ) ;
      if ( isIIOError( lflptr )) {
        SetIIOErrFlag( flptr ) ;
        return (*theIFileLastError( lflptr ))( lflptr ) ;
      }
      else
        return FALSE ;
    }

    if ( count == STATEMAX ) {
      SetIIOErrFlag( flptr ) ;
      return error_handler( IOERROR ) ;
    }
    *ptr = (uint8) c ; ++count ; ++ptr ;

    switch ( c ) {

/* Case 1 - reading a comment */
    case '%' :
      do {
        if (( c = Getc( lflptr )) == EOF )
          return (*theIFileLastError( lflptr ))( lflptr ) ;
        if ( count == STATEMAX ) {
          SetIIOErrFlag( flptr ) ;
          return error_handler( IOERROR ) ;
        }
        *ptr = (uint8) c ;
        ++count ; ptr++ ;
      } while ( ! (( c == LF ) || ( c == CR ) || ( c == FF ))) ;
      if ( c == LF || c == CR ) {
        if (( ! paren_count ) && ( ! curl_count )) {
          theICount( flptr ) = count ;
          return TRUE ;
        }
        /* re-open lineedit file */
        if ( ! ( *theIMyInitFile( lflptr ))( lflptr , NULL , NULL ))
          return ( *theIFileLastError( lflptr ))( lflptr ) ;
      }
      break ;

/* Case 2 - reading a string */
    case '(' :
      ++paren_count ;
      last = ' ' ;
      do {
        if (( c = Getc( lflptr )) == EOF )
          return (*theIFileLastError( lflptr ))( lflptr ) ;
        if ( count == STATEMAX ) {
          SetIIOErrFlag( flptr ) ;
          return error_handler( IOERROR ) ;
        }
        *ptr = (uint8) c ;
        ++count ; ++ptr ;
        switch ( c ) {

        case '(' :
          if ( last != '\\' )
            ++paren_count;
          break ;

        case ')' :
          if ( last != '\\' )
            --paren_count;
          break ;

        case '\\' :
          if ( last == '\\' )
            c = (uint8) ' ' ;
          break ;

        case LF :
        case CR :
          /* re-open lineedit */
          if ( ! ( *theIMyInitFile( lflptr ))( lflptr , NULL , NULL ))
            return ( *theIFileLastError( lflptr ))( lflptr ) ;
        }
        last = c ;
      } while ( paren_count > 0 ) ;
      break ;

    case '{' :
      ++curl_count ;
      break ;

    case '<' :
      if (( c = Getc( lflptr )) == EOF )
        return (*theIFileLastError( lflptr ))( lflptr ) ;
      if ( count == STATEMAX ) {
        SetIIOErrFlag( flptr ) ;
        return error_handler( IOERROR ) ;
      }
      *ptr = (uint8) c ; count++ ; ptr++ ;

      if ( c != '<' ) {
        if ( c == '~' ) {
          do {
            if ( c == LF || c == CR ) { /* re-open lineedit */
              if ( ! ( *theIMyInitFile( lflptr ))( lflptr , NULL , NULL ))
                return ( *theIFileLastError( lflptr ))( lflptr ) ;
            }

            if (( c = Getc( lflptr )) == EOF )
              return (*theIFileLastError( lflptr ))( lflptr ) ;
            if ( count == STATEMAX ) {
              SetIIOErrFlag( flptr ) ;
              return error_handler( IOERROR ) ;
            }
            *ptr = (uint8) c ; count++ ; ptr++ ;
          } while ( c != '~' ) ;
        }
        else {
          while ( c != '>' ) {
            if ( ! ( isxdigit( c ) || isspace( c )))
              break ;

            if ( c == LF || c == CR ) { /* re-open lineedit */
              if ( ! ( *theIMyInitFile( lflptr ))( lflptr , NULL , NULL ))
                return ( *theIFileLastError( lflptr ))( lflptr ) ;
            }

            if (( c = Getc( lflptr )) == EOF )
              return (*theIFileLastError( lflptr ))( lflptr ) ;
            if ( count == STATEMAX ) {
              SetIIOErrFlag( flptr ) ;
              return error_handler( IOERROR ) ;
            }
            *ptr = (uint8) c ; count++ ; ptr++ ;
          }
        }
      }
      break ;

    case '}' :
      --curl_count ;
      if ( curl_count < 0 )
        curl_count = 0 ;
      break ;

    case LF :
    case CR :
      if (( ! paren_count ) && ( ! curl_count )) {
        theICount( flptr ) = count ;
        return TRUE ;
      }
      /* re-open lineedit */
      if ( ! ( *theIMyInitFile( lflptr ))( lflptr , NULL , NULL ))
        return ( *theIFileLastError( lflptr ))( lflptr ) ;
      break ;
    }
  }
}
Пример #16
0
static Bool mygetline(FILELIST *flptr)
{
  register int32    i ;
  register int32    temp ;
  register FILELIST *flinptr , *floutptr ;
  register int32    count ;
  register uint8    *ptr ;

  flinptr  = theIStdin ( workingsave ) ;
  floutptr = theIStdout( workingsave ) ;

  if (! isIOpenFileFilterById( theISaveStdinFilterId( workingsave ), flinptr)) {
    SetIIOErrFlag( flptr ) ;
    return error_handler(IOERROR);
  }
  if ( stream_echo_flag &&
      ! isIOpenFileFilterById( theISaveStdoutFilterId( workingsave ), floutptr)) {
    SetIIOErrFlag( flptr ) ;
    return error_handler(IOERROR);
  }

  count = 0 ;
  ptr = theIPtr( flptr ) = theIBuffer( flptr ) ;

  if (( temp = Getc( flinptr )) == EOF ) {
    SetIEofFlag( flptr ) ;
    if ( isIIOError( flinptr )) {
      SetIIOErrFlag( flptr ) ;
      return (*theIFileLastError( flinptr ))( flinptr ) ;
    }
    else
      return FALSE ;
  }
  UnGetc( temp , flinptr ) ;

  do {
    if (( temp = Getc( flinptr )) == EOF ) {
      SetIEofFlag( flptr ) ;
      if ( isIIOError( flinptr )) {
        SetIIOErrFlag( flptr ) ;
        return (*theIFileLastError( flinptr ))( flinptr ) ;
      }
      else
        return FALSE ;
    }

    switch ( temp ) {
    case controlU :
      if ( stream_echo_flag ) {
        for ( i = 0 ; i < count ; ++i )
          if ( Putc( controlH , floutptr ) == EOF )
            return (*theIFileLastError( flptr ))( floutptr ) ;

        if ((*theIMyFlushFile( floutptr ))( floutptr ) == EOF )
          return (*theIFileLastError( flptr ))( floutptr ) ;
      }
      count = 0 ;
      break ;
    case controlR :
      if ( stream_echo_flag ) {
        if ( Putc( '\r' , floutptr ) == EOF )
          return (*theIFileLastError( flptr ))( floutptr ) ;

        for ( i = 0 ; i < count ; ++i )
          if ( Putc( theIBuffer( flptr )[ i ] , floutptr ) == EOF )
            return (*theIFileLastError( flptr ))( floutptr ) ;

        if ((*theIMyFlushFile( floutptr ))( floutptr ) == EOF )
          return (*theIFileLastError( flptr ))( floutptr ) ;
      }
      break ;
    case controlC :
      if ( stream_echo_flag ) {
        if ( Putc( '\r' , floutptr ) == EOF )
          return (*theIFileLastError( flptr ))( floutptr ) ;

        if ((*theIMyFlushFile( floutptr ))( floutptr ) == EOF )
          return (*theIFileLastError( flptr ))( floutptr ) ;
      }
      count = 0 ;
      break ;
    case controlH :
      if ( count > 0 ) {
        count-- ;
        ptr-- ;
        if ( stream_echo_flag ) {
          if ( Putc( controlH , floutptr ) == EOF )
            return (*theIFileLastError( flptr ))( floutptr ) ;

          if ((*theIMyFlushFile( floutptr ))( floutptr ) == EOF )
            return (*theIFileLastError( flptr ))( floutptr ) ;
        }
      }
      break ;
    default:
      if ( count == LINEMAX ) {
        SetIIOErrFlag( flptr ) ;
        return error_handler( IOERROR ) ;
      }
      *ptr = (uint8) temp ; count++ ; ptr++ ;

      if ( stream_echo_flag ) {
        if ( Putc( temp , floutptr ) == EOF )
          return (*theIFileLastError( flptr ))( floutptr ) ;
        if ((*theIMyFlushFile( floutptr ))( floutptr ) == EOF )
          return (*theIFileLastError( flptr ))( floutptr ) ;
      }
    }
  } while ( ! (( temp == LF ) || ( temp == CR ))) ;

  theICount( flptr ) = count ;
  return TRUE ;
}
Пример #17
0
void motorDemo(void) {
    float left = 0, right = 0, speed = 0.75f, accel = 0.01f;
    char ch;    
    int i;

    Printf("Press:\n"
	   "  w-forward\n"
	   "  s-backward\n"
	   "  a-left\n"
	   "  d-right\n"    
           "  i-slowly forward\n"
	   "  k-slowly backward\n"
	   "  j-slowly left\n"
	   "  l-slowly right\n"    
           "  space-stop\n"
	   "  enter-quit\n");
  
    // wait for the user to enter a character
    ch = ' ';
    
    while (ch != '\n') {
        switch (ch) {
            case 'w':
                left = speed;
                right = speed;
                break;
            case 's':
                left = -speed;
                right = -speed;
                break;
            case 'a':
                left = -speed;
                right = speed;
                break;
            case 'd':
                left = speed;
                right = -speed;
                break;
            case 'i':
                right += accel;
                left += accel;
                break;
            case 'k':
                right -= accel;
                left -= accel;
                break;
            case 'j':
                right -= accel;
                left += accel;
                break;
            case 'l':
                right += accel;
                left -= accel;
                break;
            default:
                left = 0; 
                right = 0;
                break;
        }

        SetMotor(Motors[0], left);
        SetMotor(Motors[1], left);
        SetMotor(Motors[2], right);
        SetMotor(Motors[3], right);
        Printf(" set motor to %1.2f %1.2f  \r", left, right);
        
        ch = Getc();
    } 
   
    // make sure the motors are off before exiting the demo 
    for (i = 0; i < 4; ++i) 
      SetMotor(Motors[i], 0);
    Printf("\n");
}
Пример #18
0
/*
 * return end of string - WARNING: malloc!
 */
int
xpmGetString(
    xpmData		 *data,
    char		**sptr,
    unsigned int	 *l)
{
    unsigned int i, n = 0;
    int c;
    char *p = NULL, *q, buf[BUFSIZ];

    if (!data->type || data->type == XPMBUFFER) {
	if (data->cptr) {
	    char *start = data->cptr;
	    while ((c = *data->cptr) && c != data->Eos)
		data->cptr++;
	    n = data->cptr - start + 1;
	    p = (char *) XpmMalloc(n);
	    if (!p)
		return (XpmNoMemory);
	    strncpy(p, start, n);
	    if (data->type)		/* XPMBUFFER */
		p[n - 1] = '\0';
	}
    } else {
	FILE *file = data->stream.file;

	if ((c = Getc(data, file)) == EOF)
	    return (XpmFileInvalid);

	i = 0;
	q = buf;
	p = (char *) XpmMalloc(1);
	while (c != data->Eos && c != EOF) {
	    if (i == BUFSIZ) {
		/* get to the end of the buffer */
		/* malloc needed memory */
		q = (char *) XpmRealloc(p, n + i);
		if (!q) {
		    XpmFree(p);
		    return (XpmNoMemory);
		}
		p = q;
		q += n;
		/* and copy what we already have */
		strncpy(q, buf, i);
		n += i;
		i = 0;
		q = buf;
	    }
	    *q++ = c;
	    i++;
	    c = Getc(data, file);
	}
	if (c == EOF) {
	    XpmFree(p);
	    return (XpmFileInvalid);
	}
	if (n + i != 0) {
	    /* malloc needed memory */
	    q = (char *) XpmRealloc(p, n + i + 1);
	    if (!q) {
		XpmFree(p);
		return (XpmNoMemory);
	    }
	    p = q;
	    q += n;
	    /* and copy the buffer */
	    strncpy(q, buf, i);
	    n += i;
	    p[n++] = '\0';
	} else {
	    *p = '\0';
	    n = 1;
	}
	Ungetc(data, c, file);
    }
    *sptr = p;
    *l = n;
    return (XpmSuccess);
}
Пример #19
0
static int
ParseComment(xpmData *data)
{
    if (data->type == XPMBUFFER) {
	register char c;
	register unsigned int n = 0;
	unsigned int notend;
	char *s;
	const char *s2;

	s = data->Comment;
	*s = data->Bcmt[0];

	/* skip the string beginning comment */
	s2 = data->Bcmt;
	do {
	    c = *data->cptr++;
	    *++s = c;
	    n++;
	    s2++;
	} while (c == *s2 && *s2 != '\0' && c);

	if (*s2 != '\0') {
	    /* this wasn't the beginning of a comment */
	    data->cptr -= n;
	    return 0;
	}
	/* store comment */
	data->Comment[0] = *s;
	s = data->Comment;
	notend = 1;
	n = 0;
	while (notend) {
	    s2 = data->Ecmt;
	    while (*s != *s2 && c) {
		c = *data->cptr++;
		if (n == XPMMAXCMTLEN - 1)  { /* forget it */
		    s = data->Comment;
		    n = 0;
		}
		*++s = c;
		n++;
	    }
	    data->CommentLength = n;
	    do {
		c = *data->cptr++;
		if (n == XPMMAXCMTLEN - 1)  { /* forget it */
		    s = data->Comment;
		    n = 0;
		}
		*++s = c;
		n++;
		s2++;
	    } while (c == *s2 && *s2 != '\0' && c);
	    if (*s2 == '\0') {
		/* this is the end of the comment */
		notend = 0;
		data->cptr--;
	    }
	}
	return 0;
    } else {
	FILE *file = data->stream.file;
	register int c;
	register unsigned int n = 0, a;
	unsigned int notend;
	char *s;
	const char *s2;

	s = data->Comment;
	*s = data->Bcmt[0];

	/* skip the string beginning comment */
	s2 = data->Bcmt;
	do {
	    c = Getc(data, file);
	    *++s = c;
	    n++;
	    s2++;
	} while (c == *s2 && *s2 != '\0' && c != EOF);

	if (*s2 != '\0') {
	    /* this wasn't the beginning of a comment */
	    /* put characters back in the order that we got them */
	    for (a = n; a > 0; a--, s--)
		Ungetc(data, *s, file);
	    return 0;
	}
	/* store comment */
	data->Comment[0] = *s;
	s = data->Comment;
	notend = 1;
	n = 0;
	while (notend) {
	    s2 = data->Ecmt;
	    while (*s != *s2 && c != EOF) {
		c = Getc(data, file);
		if (n == XPMMAXCMTLEN - 1)  { /* forget it */
		    s = data->Comment;
		    n = 0;
		}
		*++s = c;
		n++;
	    }
	    data->CommentLength = n;
	    do {
		c = Getc(data, file);
		if (n == XPMMAXCMTLEN - 1)  { /* forget it */
		    s = data->Comment;
		    n = 0;
		}
		*++s = c;
		n++;
		s2++;
	    } while (c == *s2 && *s2 != '\0' && c != EOF);
	    if (*s2 == '\0') {
		/* this is the end of the comment */
		notend = 0;
		Ungetc(data, *s, file);
	    }
	}
	return 0;
    }
}
//marklin digital interface server
void task_system_mdi_server() {
	int recv_tid = 0, i = 0; 
	int train = 0, speed = 0, sw = 0, setting = 0;
	int switch_states[CONFIG_NUM_SWITCHES];
	struct sensor_reply_message sensor_rpl;
	struct number_message rpl;
	struct two_number_message msg;
	int last_sensor_poll_time = 0, current_sensor_poll_time = 0;
	RegisterAs("mdiserv");
	
	//Signal the trains to GO
	Putc(COM1, 96);
	
	//Set sensor module to reset
	Putc(COM1, 192);
	
	for(i = 0; i < CONFIG_NUM_SWITCHES; i++) {
		switch_states[i] = SWITCH_UNKNOWN;
	}
	
	while(1) {
		//get another message, we have reached the end
		Receive(&recv_tid, (char *) &msg, sizeof(msg));
		
		//act on the message type
		switch(msg.message_type) {
			case TRAIN_CTRL_MESSAGE:
				//reply immediately
				train = msg.num1;
				speed = msg.num2;
				rpl.message_type = ACK_MESSAGE;
				Reply(recv_tid, (char *) &rpl, sizeof(rpl));
				Putc(COM1, speed);
				Putc(COM1, train);
				break;
			case TRAIN_REVERSE_MESSAGE:
				//reply immediately
				train = msg.num1;
				rpl.message_type = ACK_MESSAGE;
				Reply(recv_tid, (char *) &rpl, sizeof(rpl));
				Putc(COM1, 15);
				Putc(COM1, train);
				break;
			case ABORT_MESSAGE:
				Putc(COM1, 97);	//STOP THE TRAIN CONTROLLER
				rpl.message_type = ACK_MESSAGE;
				Reply(recv_tid, (char *) &rpl, sizeof(rpl));
				break;				
			case SWITCH_CTRL_MESSAGE:
				//reply immediately
				sw = msg.num1;
				setting = msg.num2;
				rpl.message_type = ACK_MESSAGE;
				Reply(recv_tid, (char *) &rpl, sizeof(rpl));
				
				if(setting == SWITCH_STRAIGHT) {
					Putc(COM1, 33);
                                        //DisplaySwitch( sw, 'S');					
				} else if(setting == SWITCH_CURVED) {
					Putc(COM1, 34);
                                        //DisplaySwitch( sw, 'C');					
				}
				Putc(COM1, sw);
				Putc(COM1, 32);
				switch_states[switch_index(sw)] = setting;
				break;			
			case QUERY_ALL_SENSORS_MESSAGE:
				Putc(COM1, 128 + CONFIG_NUM_SENSOR_MODULES);
				int time1, time2, time_diff;
				
				for(i = 0; i < CONFIG_NUM_SENSOR_MODULES * 2; i++) {
					sensor_rpl.sensordata[i] = Getc(COM1);
					if(i == 0) {
						time1 = current_sensor_poll_time = Time();
					}
					//int * mdmctl = (int *)( UART1_BASE + UART_MDMCTL_OFFSET);
					//*mdmctl = *mdmctl | 3;
				}
				
				//time2 = Time();

				//time_diff = time2 - time1;
				//if( time_diff >= 0 ) {
				//	CommandOutput( "\x1B[30;47m[MDISERVER] SENSOR POLL TOOK %d TICKS\x1B[0m", time_diff );
				//}

				if(last_sensor_poll_time > 0) {
					sensor_rpl.time = (current_sensor_poll_time + last_sensor_poll_time) / 2;
				} else {
					sensor_rpl.time = current_sensor_poll_time;
				}

				//reply only after we have something
				sensor_rpl.message_type = SENSOR_REPLY_MESSAGE;
				Reply(recv_tid, (char *) &sensor_rpl, sizeof(sensor_rpl));
				last_sensor_poll_time = current_sensor_poll_time;
				break;
			default:
				//unexpected message, reply and say so
				rpl.message_type = INVALID_OPERATION_MESSAGE;
				rpl.num = 0;
				Reply(recv_tid, (char *) &rpl, sizeof(rpl));
				break;
		}
		
	}
}
Пример #21
0
void Wrapper_pretty_print(String *str, File *f) {
  String *ts;
  int level = 0;
  int c, i;
  int empty = 1;
  int indent = 2;
  int plevel = 0;
  int label = 0;

  ts = NewStringEmpty();
  Seek(str, 0, SEEK_SET);
  while ((c = Getc(str)) != EOF) {
    if (c == '\"') {
      Putc(c, ts);
      while ((c = Getc(str)) != EOF) {
	if (c == '\\') {
	  Putc(c, ts);
	  c = Getc(str);
	}
	Putc(c, ts);
	if (c == '\"')
	  break;
      }
      empty = 0;
    } else if (c == '\'') {
      Putc(c, ts);
      while ((c = Getc(str)) != EOF) {
	if (c == '\\') {
	  Putc(c, ts);
	  c = Getc(str);
	}
	Putc(c, ts);
	if (c == '\'')
	  break;
      }
      empty = 0;
    } else if (c == ':') {
      Putc(c, ts);
      if ((c = Getc(str)) == '\n') {
	if (!empty && !strchr(Char(ts), '?'))
	  label = 1;
      }
      Ungetc(c, str);
    } else if (c == '(') {
      Putc(c, ts);
      plevel += indent;
      empty = 0;
    } else if (c == ')') {
      Putc(c, ts);
      plevel -= indent;
      empty = 0;
    } else if (c == '{') {
      Putc(c, ts);
      Putc('\n', ts);
      for (i = 0; i < level; i++)
	Putc(' ', f);
      Printf(f, "%s", ts);
      Clear(ts);
      level += indent;
      while ((c = Getc(str)) != EOF) {
	if (!isspace(c)) {
	  Ungetc(c, str);
	  break;
	}
      }
      empty = 0;
    } else if (c == '}') {
      if (!empty) {
	Putc('\n', ts);
	for (i = 0; i < level; i++)
	  Putc(' ', f);
	Printf(f, "%s", ts);
	Clear(ts);
      }
      level -= indent;
      Putc(c, ts);
      empty = 0;
    } else if (c == '\n') {
      Putc(c, ts);
      empty = 0;
      if (!empty) {
	int slevel = level;
	if (label && (slevel >= indent))
	  slevel -= indent;
	if ((Char(ts))[0] != '#') {
	  for (i = 0; i < slevel; i++)
	    Putc(' ', f);
	}
	Printf(f, "%s", ts);
	for (i = 0; i < plevel; i++)
	  Putc(' ', f);
      }
      Clear(ts);
      label = 0;
      empty = 1;
    } else if (c == '/') {
      empty = 0;
      Putc(c, ts);
      c = Getc(str);
      if (c != EOF) {
	Putc(c, ts);
	if (c == '/') {		/* C++ comment */
	  while ((c = Getc(str)) != EOF) {
	    if (c == '\n') {
	      Ungetc(c, str);
	      break;
	    }
	    Putc(c, ts);
	  }
	} else if (c == '*') {	/* C comment */
	  int endstar = 0;
	  while ((c = Getc(str)) != EOF) {
	    if (endstar && c == '/') {	/* end of C comment */
	      Putc(c, ts);
	      break;
	    }
	    endstar = (c == '*');
	    Putc(c, ts);
	    if (c == '\n') {	/* multi-line C comment. Could be improved slightly. */
	      for (i = 0; i < level; i++)
		Putc(' ', ts);
	    }
	  }
	}
      }
    } else {
      if (!empty || !isspace(c)) {
	Putc(c, ts);
	empty = 0;
      }
    }
  }
  if (!empty)
    Printf(f, "%s", ts);
  Delete(ts);
  Printf(f, "\n");
}
Пример #22
0
/*
 * Print out the contents of the file f, one screenful at a time.
 */
void
screen(FILE *f, int num_lines)
{
	int ch;
	int nchars;
	int length;			/* length of current line */
	static int prev_len = 1;	/* length of previous line */

	for (;;) {
		while (num_lines > 0 && !Pause) {
			if ((nchars = get_line(f, &length)) == EOF) {
				if (clreol)
					clreos();
				return;
			}
			if (ssp_opt && length == 0 && prev_len == 0)
				continue;
			prev_len = length;
			if (bad_so ||
			    (Senter && *Senter == ' ' && promptlen > 0))
				erasep(0);
			/*
			 * Must clear before drawing line since tabs on some
			 * terminals do not erase what they tab over.
			 */
			if (clreol)
				cleareol();
			prbuf(Line, length);
			if (nchars < promptlen) {
				/* erasep() sets promptlen to 0 */
				erasep(nchars);
			} else
				promptlen = 0;
#if 0
			/* XXX - is this needed? */
			if (clreol) {
				/* must clear again in case we wrapped * */
				cleareol();
			}
#endif
			if (nchars < Mcol || !fold_opt) {
				/* will turn off UL if necessary */
				prbuf("\n", 1);
			}
			if (nchars == STOP)
				break;
			num_lines--;
		}
		if (pstate) {
			tputs(ULexit, 1, putch);
			pstate = 0;
		}
		fflush(stdout);
		if ((ch = Getc(f)) == EOF) {
			if (clreol)
				clreos();
			return;
		}

		if (Pause && clreol)
			clreos();
		Ungetc(ch, f);
		Pause = 0;
		startup = 0;
		if ((num_lines = command(NULL, f)) == 0)
			return;
		if (hard && promptlen > 0)
			erasep(0);
		if (noscroll && num_lines >= dlines) {
			if (clreol)
				home();
			else
				doclear();
		}
		/*
		 * XXX - should store the *first* line on the screen,
		 * not the last (but we don't know the file position).
		 * Fixing this requires keeping an arry of dline off_ts
		 * and updating each one when a new line is started.
		 */
		screen_start.line = Currline;
		screen_start.chrctr = Ftell(f);
	}
}
Пример #23
0
void task_user_cli( ) {
	char c;
	char cbuff_storage[CONFIG_CLI_MAX_CHARACTERS];
	struct char_buffer cbuff;
	cbuffer_init( &cbuff, cbuff_storage, CONFIG_CLI_MAX_CHARACTERS );

	//used for parsing out the first token
	char first_token[CONFIG_CLI_MAX_CHARACTERS];

	//keep track of which track we are
	int track = TRACK_UNINITIALIZED;

	//Copy of track data
	struct track_node track_data[TRACK_MAX];

	//for complex prints
	struct print_buffer pbuff;
	ap_init_buff( &pbuff );

	//go to the CLI location, and save it
	Printf( COM2, "\x1B[24;20f\x1B[s" );

	while( 1 ) {
		ap_init_buff( &pbuff );
		c = Getc( COM2 );

		//catch special characters
		switch( c ) {
			case CHAR_GRAVE_ACCENT:
				CommandOutput( "[CLI] ABORT!" );
				Abort( );
				break;
			case CHAR_BACKSPACE:
				if( cbuff.state == CBUFF_EMPTY ) {
					break;
				} //do nothing if empty

				//remove the last character
				cbuffer_pop_last( &cbuff );

				//move the cursor back one space and delete the character
				Printf( COM2, "\x1B[u\x1B[D\x1B[K\x1B[s" );

				break;
			case CHAR_PERIOD:
				TabRight( );
				break;
			case CHAR_COMMA:
				TabLeft( );
				break;
			case CHAR_NEWLINE:
			case CHAR_ENTER:
				if( cbuff.state == CBUFF_EMPTY ) {
					break;
				} //do nothing if empty

				//we need to parse, get the first token
				if( next_token( &cbuff, first_token ) == 0 ) {
					break;
				} //we were just spaces

				//now check which command the first token matches
				if( strcmp( first_token, "tr" ) == 0 ) {
					command_tr( &cbuff );
				} else if( strcmp( first_token, "q" ) == 0 ) {
					command_q( &cbuff );
				} else if( strcmp( first_token, "game" ) == 0 ) {
					command_game( &cbuff );
				} else if( strcmp( first_token, "wh" ) == 0 ) {
					command_wh( &cbuff );
				} else if( strcmp( first_token, "st" ) == 0 ) {
					command_st( &cbuff );
				} else if( strcmp( first_token, "sw" ) == 0 ) {
					command_sw( &cbuff );
				} else if( strcmp( first_token, "swa" ) == 0 ) {
					command_swa( &cbuff );
				} else if( strcmp( first_token, "rv" ) == 0 ) {
					command_rv( &cbuff );
				} else if( strcmp( first_token, "add" ) == 0 ) {
					command_add( &cbuff, track );
				} else if( strcmp( first_token, "echo" ) == 0 ) {
					command_echo( &cbuff );
				} else if( strcmp( first_token, "delay" ) == 0 ) {
					command_delay( &cbuff );
				} else if( strcmp( first_token, "beep" ) == 0 ) {
					command_beep( &cbuff );
				} else if( strcmp( first_token, "looptest" ) == 0 ) {
					command_looptest( &cbuff );
				} else if( strcmp( first_token, "zombtest" ) == 0 ) {
					command_zombtest( &cbuff );
				} else if( strcmp( first_token, "track" ) == 0 ) {
					command_track( &cbuff, &track, track_data );
				} else if( strcmp( first_token, "sos" ) == 0 ) {
					command_sos( &cbuff );
				} else if( strcmp( first_token, "calibrationout" ) == 0 ) {
					command_calibrationout( &cbuff );
				} else if( strcmp( first_token, "route" ) == 0 ) {
					command_route( &cbuff, track_data );
				} else if( strcmp( first_token, "tdir" ) == 0 ) {
					command_tdir( &cbuff );
				} else if( strcmp( first_token, "resv" ) == 0 ) {
					command_resv( &cbuff, track_data );
				} else if( strcmp( first_token, "free" ) == 0 ) {
					command_free( &cbuff, track_data );
				} else {
					CommandOutput( "Invalid Command" );
				}


				//empty the command buffer
				cbuffer_empty( &cbuff );
				//clear the command line
				Printf( COM2, "\x1B[24;20f\x1B[K\x1B[s" );

				break;
			default:
				//if it is not a valid character ignore it
				if( !validate_char( &c ) ) {
					break;
				}
				//if we are full, ignore the character
				if( cbuff.state == CBUFF_FULL ) {
					break;
				}

				//we have a valid character buffer and print it
				cbuffer_push_char( &cbuff, c );
				Printf( COM2, "\x1B[u%c\x1B[s", c );
				break;
		}

		//re-initialize the parse
		first_token[0] = '\0';
	}
}
Пример #24
0
/*
 * Keyboard polling routine
 */
kbpoll()
{
	int c;
	rsetdead();
	c = Getc();
	if (c == -1)
	        return;
	switch (c&0xff) {
#ifdef BILL
	case 'B':
		BillMode = !BillMode;
		break;
#endif
	case '+':
	        addmen(1);
	        break;
	case 'P':
#ifdef NOSCROLL
	case NOSCROLL:
#endif
		Paused = !Paused;
		break;
	case 'w':
		compwalls();
/*		Wallsoff = !Wallsoff; */
		break;
	case GAME4:
	case GAME3:
	case GAME2:
	case GAME1:
		if ( Game ) {
			Newgame = c-'0';
			break;
		}
		Game = c - '0';
		break;
	case LEFT:
	case ALTLEFT:
		Paused = FALSE;
		Pacman.pending = MOVELEFT;
		Pacman.pendcnt = PENDCOUNT;
		Pacman.moving = TRUE;
		break;
	case RIGHT:
	case ALTRIGHT:
		Paused = FALSE;
		Pacman.pending = MOVERIGHT;
		Pacman.pendcnt = PENDCOUNT;
		Pacman.moving = TRUE;
		break;
	case UP:
	case ALTUP:
		Paused = FALSE;
		Pacman.pending = MOVEUP;
		Pacman.pendcnt = PENDCOUNT;
		Pacman.moving = TRUE;
		break;
	case DOWN:
	case ALTDOWN:
	case ALTALTDOWN:
		Paused = FALSE;
		Pacman.pending = MOVEDOWN;
		Pacman.pendcnt = PENDCOUNT;
		Pacman.moving = TRUE;
		break;
	case SILENT:
		Silent = !Silent;
		break;
	case STOP:
		Paused = FALSE;
		Pacman.moving = FALSE;
		Pacman.pendcnt = 0;
		break;
	case ABORT:
		Running = FALSE;
		Abort = TRUE;
		break;
	case NEWGAME:
		Newgame = -1;
		break;
	case LOUDER:
		if (VolumeControl < 16)
		    VolumeControl++;
		break;
	case SOFTER:
		if (VolumeControl > 1)
		    VolumeControl--;
		break;
	}
}
Пример #25
0
int
main(int argc, char **argv)
{
	FILE * volatile f;
	char		*s;
	volatile int	left;
	volatile off_t	initline;
	volatile int	prnames = 0;
	volatile int	initopt = 0;
	volatile int	srchopt = 0;
	int		clearit = 0;
	int		ch;
	char		initbuf[80];

	if (pledge("stdio rpath tty", NULL) == -1) {
		perror("pledge");
		exit(1);
	}

	setlocale(LC_ALL, "");

	/* all signals just use a stub handler and interrupt syscalls */
	sigemptyset(&sa.sa_mask);
	sa.sa_flags = 0;
	sa.sa_handler = onsignal;

	nfiles = argc;
	fnames = argv;
	initterm();
	nscroll = Lpp/2 - 1;
	if (nscroll <= 0)
		nscroll = 1;
	if ((s = getenv("MORE")) != NULL && *s != '\0')
		argscan(s);
	while (--nfiles > 0) {
		if ((ch = (*++fnames)[0]) == '-')
			argscan(*fnames + 1);
		else if (ch == '+') {
			s = *fnames;
			if (*++s == '/') {
				srchopt++;
				(void)strlcpy(initbuf, ++s, sizeof(initbuf));
			} else {
				initopt++;
				for (initline = 0; *s != '\0'; s++) {
					if (isdigit((unsigned char)*s))
						initline =
						    initline * 10 + *s - '0';
				}
				--initline;
			}
		} else
			break;
	}
	/*
	 * Allow clreol only if Home and eraseln and EodClr strings are
	 * defined, and in that case, make sure we are in noscroll mode.
	 */
	if (clreol) {
		if (Home == NULL || *Home == '\0' || eraseln == NULL ||
		    *eraseln == '\0' || EodClr == NULL || *EodClr == '\0')
			clreol = 0;
		else
			noscroll = 1;
	}
	if (dlines == 0)
		dlines = Lpp - 1;
	left = dlines;
	if (nfiles > 1)
		prnames++;
	if (!no_intty && nfiles == 0)
		usage();
	else
		f = stdin;
	if (!no_tty) {
		struct sigaction osa;

		(void)sigaction(SIGQUIT, &sa, NULL);
		(void)sigaction(SIGINT, &sa, NULL);
		(void)sigaction(SIGWINCH, &sa, NULL);
		if (sigaction(SIGTSTP, &osa, NULL) == 0 &&
		    osa.sa_handler == SIG_DFL) {
			(void)sigaction(SIGTSTP, &sa, NULL);
			(void)sigaction(SIGTTIN, &sa, NULL);
			(void)sigaction(SIGTTOU, &sa, NULL);
			catch_susp++;
		}
		set_tty();
	}
	if (no_intty) {
		if (no_tty)
			copy_file(stdin);
		else {
			if ((ch = Getc(f)) == '\f')
				doclear();
			else {
				Ungetc(ch, f);
				if (noscroll && ch != EOF) {
					if (clreol)
						home();
					else
						doclear();
				}
			}
			if (srchopt) {
				if (search(initbuf, stdin, 1) == 0 && noscroll)
					left--;
			} else if (initopt)
				skiplns(initline, stdin);
			screen(stdin, left);
		}
		no_intty = 0;
		dup2(STDERR_FILENO, STDIN_FILENO);	/* stderr is a tty */
		prnames++;
		firstf = 0;
	}

	while (fnum < nfiles) {
		if ((f = checkf(fnames[fnum], &clearit)) != NULL) {
			context.line = context.chrctr = 0;
			Currline = 0;
		restart:
			if (firstf) {
				firstf = 0;
				if (srchopt) {
					if (search(initbuf, f, 1) < 0)
						goto restart;
					if (noscroll)
						left--;
				} else if (initopt)
					skiplns(initline, f);
			} else if (fnum < nfiles && !no_tty)
				left = command(fnames[fnum], f);
			if (left != 0) {
				if ((noscroll || clearit) &&
				    (file_size != LONG_MAX)) {
					if (clreol)
						home();
					else
						doclear();
				}
				if (prnames) {
					if (bad_so)
						erasep(0);
					if (clreol)
						cleareol();
					fputs("::::::::::::::", stdout);
					if (promptlen > 14)
						erasep(14);
					putchar('\n');
					if (clreol)
						cleareol();
					printf("%s\n", fnames[fnum]);
					if (clreol)
						cleareol();
					fputs("::::::::::::::\n", stdout);
					if (left > Lpp - 4)
						left = Lpp - 4;
				}
				if (no_tty)
					copy_file(f);
				else {
					within++;
					screen(f, left);
					within = 0;
				}
			}
			fflush(stdout);
			fclose(f);
			screen_start.line = screen_start.chrctr = 0L;
			context.line = context.chrctr = 0L;
		}
		fnum++;
		firstf = 0;
	}
	reset_tty();
	exit(0);
}
Пример #26
0
//-----------------------------------------------------------------------------
// Helpers to get 1, 2, or 4 bytes from the .ttf file. Big endian.
//-----------------------------------------------------------------------------
int TtfFont::GetBYTE(void) {
    return Getc();
}
Пример #27
0
/*
 * Get a logical line.
 */
int
get_line(FILE *f, int *length)
{
	int		ch, lastch;
	char		*p, *ep;
	int		column;
	static int	colflg;

	p = Line;
	ep = Line + linsize - 1;
	column = 0;
	ch = Getc(f);
	if (colflg && ch == '\n') {
		Currline++;
		ch = Getc(f);
	}
	for (;;) {
		if (p >= ep) {
			p = resize_line(p);
			ep = Line + linsize - 1;
		}
		if (ch == EOF) {
			if (p > Line) {
				*p = '\0';
				*length = p - Line;
				return (column);
			}
			*length = p - Line;
			return (EOF);
		}
		if (ch == '\n') {
			Currline++;
			break;
		}
		*p++ = (char)ch;
		if (ch == '\t') {
			if (!hardtabs || (column < promptlen && !hard)) {
				if (hardtabs && eraseln && !dumb) {
					column = 1 + (column | 7);
					tputs(eraseln, 1, putch);
					promptlen = 0;
				} else {
					for (--p;;) {
						if (p >= ep) {
							p = resize_line(p);
							ep = Line + linsize - 1;
						}
						*p++ = ' ';
						if ((++column & 7) == 0)
							break;
					}
					if (column >= promptlen)
						promptlen = 0;
				}
			} else
				column = 1 + (column | 7);
		} else if (ch == '\b' && column > 0)
			column--;
		else if (ch == '\f' && stop_opt) {
			p[-1] = '^';
			*p++ = 'L';
			column += 2;
			Pause++;
		} else if (ch == EOF) {
			*length = p - Line;
			return (column);
		} else if (ch >= ' ' && ch != RUBOUT)
			column++;
		if (column >= Mcol && fold_opt)
			break;
		lastch = ch;
		ch = Getc(f);
		if (lastch == '\r') {
			/*
			 * Reset column to 0 for carriage return unless
			 * immediately followed by a newline.
			 */
			if (ch != '\n')
				column = 0;
			else
				p--;
		}
	}
	/* XXX - potential oflow */
	if (column >= Mcol && Mcol > 0 && !Wrap)
		*p++ = '\n';
	colflg = (column == Mcol && fold_opt);
	if (colflg && eatnl && Wrap)
		*p++ = '\n';	/* simulate normal wrap */
	*length = p - Line;
	*p = '\0';
	return (column);
}
Пример #28
0
bool textSource::segment(int level
                        ,int sstatus
                        ,bool PrevIsField  // True if previous sibling block contains a \field
                        ,charprops CharProps
                        )
    {

    wint_t ch;
    curr_pos = Ftell(sourceFile);// After parsing a html-tag, seeking to curr_pos brings you back to the position where the parsed sequence started.                   

    if(Option.keepEOLsequence)
        {
        copyEOLsequence();
        // SourceFile is rewinded
        }

    do
        {
        ch = Getc(sourceFile);
        end_offset = Ftell(sourceFile);
        if(curr_pos >= tagendpos)
            {
            // We are not inside an HTML-tag.
            if(flgs.inhtmltag)
                {
                flgs.firstafterhtmltag = true;
                flgs.inhtmltag = false;
                }
            // Check whether a well-formed HTML tag is ahead. Returns sourceFile
            // in same file position.
            flgs.htmltagcoming = isHTMLtagComing(ch);
//            assert(new_pos == Ftell(sourceFile));
            assert(end_offset == Ftell(sourceFile));
            }
        else if(flgs.htmltagcoming)
            {
            // We are leaving an HTML-tag and entering a new one.
            flgs.inhtmltag = true;
            flgs.htmltagcoming = false;
            }
        /* Scan in advance, checking whether the line to come is a heading and 
        therefore must be preceded with a newline (WritePar will then be set to 
        true.)
        */

        if(  ch ==  '\n'
          || ch == '\r'
          || ch == WEOF
          || ch == 26
          )
            {
            flgs.in_fileName = false;
            heading = isHeading(firsttext,ch,WriteParAfterHeadingOrField);
            if(!skipSegmentation(firsttext,ch))
                {
                doTheSegmentation(CharProps,true,false); // Bart 20040120. true because: Suppose that end of line is end of segment
                if(!WriteParAfterHeadingOrField && heading)
                    {// A normal line after a heading has WritePar==false and heading==true
                    WriteParAfterHeadingOrField = true;
                    heading = false;
                    }
                }
            if(firsttext.EOL)
                firsttext.b.LS = 1;
            }
        else
            {
            updateFlags(ch,flgs);
            int EOL = firsttext.EOL;
            bool sentenceEnd = checkSentenceStartDueToBullet(ch);
            if(  sentenceEnd 
              || flgs.htmltagcoming
              || flgs.inhtmltag
              || (end_offset - begin_offset > MAXSEGMENTLENGTH && isSpace(ch)) // check for buffer overflow
              )
                {
                doTheSegmentation(CharProps,false,false); 
                firsttext.b.SD = 1;
                firsttext.b.LS = 0;
                }
            if(isSpace(ch))
                {
                if(EOL)
                    firsttext.b.LS = 1;
                }
            else
                {
                firsttext.b.LS = 0;
                firsttext.EOL = 0; // resets SD, CR and LF
                }
            }
        curr_pos = end_offset;
        }
    while(ch != WEOF && ch != 26);
    outputtext->PutHandlingLine('\n',flgs); // 20100106 Flush last line
    return false;
    }
Пример #29
0
static void scanner_locator(String *loc) {
  if (!follow_locators) {
    if (Equal(loc, "/*@SWIG@*/")) {
      /* End locator. */
      if (expanding_macro)
	--expanding_macro;
    } else {
      /* Begin locator. */
      ++expanding_macro;
    }
    /* Freeze line number processing in Scanner */
    Scanner_freeze_line(scan,expanding_macro);
  } else {
    int c;
    Locator *l;
    Seek(loc, 7, SEEK_SET);
    c = Getc(loc);
    if (c == '@') {
      /* Empty locator.  We pop the last location off */
      if (locs) {
	Scanner_set_location(scan,locs->filename,locs->line_number);
	cparse_file = locs->filename;
	cparse_line = locs->line_number;
	l = locs->next;
	free(locs);
	locs = l;
      }
      return;
    }

    /* We're going to push a new location */
    l = (Locator *) malloc(sizeof(Locator));
    l->filename = cparse_file;
    l->line_number = cparse_line;
    l->next = locs;
    locs = l;

    /* Now, parse the new location out of the locator string */
    {
      String *fn = NewStringEmpty();
      /*      Putc(c, fn); */
      
      while ((c = Getc(loc)) != EOF) {
	if ((c == '@') || (c == ','))
	  break;
	Putc(c, fn);
      }
      cparse_file = Swig_copy_string(Char(fn));
      Clear(fn);
      cparse_line = 1;
      /* Get the line number */
      while ((c = Getc(loc)) != EOF) {
	if ((c == '@') || (c == ','))
	  break;
	Putc(c, fn);
      }
      cparse_line = atoi(Char(fn));
      Clear(fn);
      
      /* Get the rest of it */
      while ((c = Getc(loc)) != EOF) {
	if (c == '@')
	  break;
	Putc(c, fn);
      }
      /*  Printf(stderr,"location: %s:%d\n",cparse_file,cparse_line); */
      Scanner_set_location(scan,cparse_file,cparse_line);
      Delete(fn);
    }
  }
}
Пример #30
0
void terminalDriver() {
  char commands[NUM_SAVED_COMMANDS][BUFFERSIZE];
  int lengths[NUM_SAVED_COMMANDS];
  int commandNum = 0, viewingNum = 0;

  char curCommand[BUFFERSIZE];
  int commandLength = 0, totalCommands = 0;

  char c;

  int trainSpeeds[80];
  int i;
  for(i=0; i<80; i++) {
    trainSpeeds[i] = 0;
  }
  int train[80];
  for(i=0; i<80; i++) {
    train[i] = -1;
  }

  Create(2, clockDriver);

  outputEscape("[2J[13;100r");
  refreshScreen();
  initializeTrack();
  moveCursor(13, 1);
  Putc(2, '>');
  while(true) {
    c = (char)Getc(2);
    switch(c) {
      case '\r':
	curCommand[commandLength] = '\0';
	strcpy(commands[commandNum], curCommand);
	lengths[commandNum] = commandLength;
	Putc(2, '\r');
	parseCommand(curCommand, trainSpeeds, train);
	commandNum++;
	commandNum %= NUM_SAVED_COMMANDS;
	viewingNum = commandNum;
	commands[commandNum][0] = '\0';
	commandLength = 0;
	if(totalCommands < NUM_SAVED_COMMANDS-1) totalCommands++;
	Putc(2, '>');
	break;
      case '\t':
	if(commandLength > 0) {
	  curCommand[commandLength] = '\0';
	  commandLength = tabComplete(curCommand);
	  outputEscape("[100D[K");
	  printf(">%s", curCommand);
	}
	break;
      case '\x8':
	if(commandLength > 0) {
	  commandLength--;
	  outputEscape("[1D[K");
	}
	break;
      case '\x1B':	//escape
	c = (char)Getc(2);
	c = (char)Getc(2);
	if(c == 'A') {
	  if(commandNum == viewingNum) {
	    curCommand[commandLength] = '\0';
	    strcpy(commands[commandNum], curCommand);
	    lengths[commandNum] = commandLength;
	  }
	  if(viewingNum != ((commandNum + NUM_SAVED_COMMANDS - totalCommands) 
					% NUM_SAVED_COMMANDS)) {
	    viewingNum += NUM_SAVED_COMMANDS - 1;
	    viewingNum %= NUM_SAVED_COMMANDS;
	    strcpy(curCommand, commands[viewingNum]);
	    commandLength = lengths[viewingNum];
	    outputEscape("[100D[K");
	    printf(">%s", curCommand);
	  }
	}else if(c == 'B') {
	  if(viewingNum != commandNum) {
	    viewingNum += 1;
	    viewingNum %= NUM_SAVED_COMMANDS;
	    strcpy(curCommand, commands[viewingNum]);
	    commandLength = lengths[viewingNum];
	    outputEscape("[100D[K");
	    printf(">%s", curCommand);
	  }
	}
	break;
      default:
	if(commandLength < BUFFERSIZE - 1) {
          curCommand[commandLength++] = c;
          Putc(2, c);
	}
        break;
    }
  }
}