1 /* io.c Larn is copyrighted 1986 by Noah Morgan.
2 * $FreeBSD: src/games/larn/io.c,v 1.7 1999/11/16 02:57:22 billf Exp $
3 * $DragonFly: src/games/larn/io.c,v 1.2 2003/06/17 04:25:24 dillon Exp $
5 * Below are the functions in this file:
7 * setupvt100() Subroutine to set up terminal in correct mode for game
8 * clearvt100() Subroutine to clean up terminal when the game is over
9 * getchar() Routine to read in one character from the terminal
10 * scbr() Function to set cbreak -echo for the terminal
11 * sncbr() Function to set -cbreak echo for the terminal
12 * newgame() Subroutine to save the initial time and seed rnd()
14 * FILE OUTPUT ROUTINES
16 * lprintf(format,args . . .) printf to the output buffer
17 * lprint(integer) send binary integer to output buffer
18 * lwrite(buf,len) write a buffer to the output buffer
19 * lprcat(str) sent string to output buffer
21 * FILE OUTPUT MACROS (in header.h)
23 * lprc(character) put the character into the output buffer
27 * long lgetc() read one character from input buffer
28 * long lrint() read one integer from input buffer
29 * lrfill(address,number) put input bytes into a buffer
30 * char *lgetw() get a whitespace ended word from input
31 * char *lgetl() get a \n or EOF ended line from input
33 * FILE OPEN / CLOSE ROUTINES
35 * lcreat(filename) create a new file for write
36 * lopen(filename) open a file for read
37 * lappend(filename) open for append to an existing file
38 * lrclose() close the input file
39 * lwclose() close output file
40 * lflush() flush the output buffer
44 * cursor(x,y) position cursor at [x,y]
45 * cursors() position cursor at [1,24] (saves memory)
46 * cl_line(x,y) Clear line at [1,y] and leave cursor at [x,y]
47 * cl_up(x,y) Clear screen from [x,1] to current line.
48 * cl_dn(x,y) Clear screen from [1,y] to end of display.
49 * standout(str) Print the string in standout mode.
50 * set_score_output() Called when output should be literally printed.
51 ** putchar(ch) Print one character in decoded output buffer.
52 ** flush_buf() Flush buffer with decoded output.
53 ** init_term() Terminal initialization -- setup termcap info
54 ** char *tmcapcnv(sd,ss) Routine to convert VT100 \33's to termcap format
55 * beep() Routine to emit a beep if enabled (see no-beep in .larnopts)
57 * Note: ** entries are available only in termcap mode.
62 #ifdef SYSV /* system III or system V */
65 #define stty(_a,_b) ioctl(_a,TCSETA,_b)
66 #define gtty(_a,_b) ioctl(_a,TCGETA,_b)
67 static int rawflg = 0;
68 static char saveeof,saveeol;
69 #define doraw(_a) if(!rawflg){++rawflg;saveeof=_a.c_cc[VMIN];saveeol=_a.c_cc[VTIME];}\
70 _a.c_cc[VMIN]=1;_a.c_cc[VTIME]=1;_a.c_lflag &= ~(ICANON|ECHO|ECHOE|ECHOK|ECHONL)
71 #define unraw(_a) _a.c_cc[VMIN]=saveeof;_a.c_cc[VTIME]=saveeol;_a.c_lflag |= ICANON|ECHO|ECHOE|ECHOK|ECHONL
76 #define CBREAK RAW /* V7 has no CBREAK */
79 #define doraw(_a) (_a.sg_flags |= CBREAK,_a.sg_flags &= ~ECHO)
80 #define unraw(_a) (_a.sg_flags &= ~CBREAK,_a.sg_flags |= ECHO)
84 #ifndef NOVARARGS /* if we have varargs */
86 #else NOVARARGS /* if we don't have varargs */
87 typedef char *va_list;
88 #define va_dcl int va_alist;
89 #define va_start(plist) plist = (char *) &va_alist
91 #define va_arg(plist,mode) ((mode *)(plist += sizeof(mode)))[-1]
94 #define LINBUFSIZE 128 /* size of the lgetw() and lgetl() buffer */
95 int lfd; /* output file numbers */
96 int fd; /* input file numbers */
97 static struct sgttyb ttx; /* storage for the tty modes */
98 static int ipoint=MAXIBUF,iepoint=MAXIBUF; /* input buffering pointers */
99 static char lgetwbuf[LINBUFSIZE]; /* get line (word) buffer */
102 * setupvt100() Subroutine to set up terminal in correct mode for game
104 * Attributes off, clear screen, set scrolling region, set tty mode
108 clear(); setscroll(); scbr(); /* system("stty cbreak -echo"); */
112 * clearvt100() Subroutine to clean up terminal when the game is over
114 * Attributes off, clear screen, unset scrolling region, restore tty mode
118 resetscroll(); clear(); sncbr(); /* system("stty -cbreak echo"); */
122 * getchar() Routine to read in one character from the terminal
130 lflush(); /* be sure output buffer is flushed */
131 read(0,&byt,1); /* get byte from terminal */
136 * scbr() Function to set cbreak -echo for the terminal
138 * like: system("stty cbreak -echo")
142 gtty(0,&ttx); doraw(ttx); stty(0,&ttx);
146 * sncbr() Function to set -cbreak echo for the terminal
148 * like: system("stty -cbreak echo")
152 gtty(0,&ttx); unraw(ttx); stty(0,&ttx);
156 * newgame() Subroutine to save the initial time and seed rnd()
161 for (p=c,pe=c+100; p<pe; *p++ =0);
162 time(&initialtime); srandomdev();
163 lcreat((char*)0); /* open buffering for output to terminal */
167 * lprintf(format,args . . .) printf to the output buffer
171 * Enter with the format string in "format", as per printf() usage
172 * and any needed arguments following it
173 * Note: lprintf() only supports %s, %c and %d, with width modifier and left
174 * or right justification.
175 * No correct checking for output buffer overflow is done, but flushes
176 * are done beforehand if needed.
177 * Returns nothing of value.
186 str = str2; /* to make lint happy */
194 str = str2; /* to make lint happy */
201 va_list ap; /* pointer for variable argument list */
204 long wide,left,cont,n; /* data for lprintf */
205 char db[12]; /* %d buffer in lprintf */
207 va_start(ap); /* initialize the var args pointer */
208 fmt = va_arg(ap, char *); /* pointer to format string */
209 if (lpnt >= lpend) lflush();
214 if (*fmt) *outb++ = *fmt++; else { lpnt=outb; return; }
215 wide = 0; left = 1; cont=1;
219 case 'd': n = va_arg(ap, long);
220 if (n<0) { n = -n; *outb++ = '-'; if (wide) --wide; }
221 tmpb = db+11; *tmpb = (char)(n % 10 + '0');
222 while (n>9) *(--tmpb) = (char)((n /= 10) % 10 + '0');
223 if (wide==0) while (tmpb < db+12) *outb++ = *tmpb++;
227 if (left) while (wide-- > 0) *outb++ = ' ';
228 while (tmpb < db+12) *outb++ = *tmpb++;
229 if (left==0) while (wide-- > 0) *outb++ = ' ';
233 case 's': tmpb = va_arg(ap, char *);
234 if (wide==0) { while (*outb++ = *tmpb++); --outb; }
237 n = wide - strlen(tmpb);
238 if (left) while (n-- > 0) *outb++ = ' ';
239 while (*outb++ = *tmpb++); --outb;
240 if (left==0) while (n-- > 0) *outb++ = ' ';
244 case 'c': *outb++ = va_arg(ap, int); cont=0; break;
255 case '9': wide = 10*wide + *fmt - '0'; break;
257 case '-': left = 0; break;
259 default: *outb++ = *fmt; cont=0; break;
268 * lprint(long-integer) send binary integer to output buffer
271 * +---------+---------+---------+---------+
273 * | order | | | order |
274 * | byte | | | byte |
275 * +---------+---------+---------+---------+
276 * 31 --- 24 23 --- 16 15 --- 8 7 --- 0
278 * The save order is low order first, to high order (4 bytes total)
279 * and is written to be system independent.
280 * No checking for output buffer overflow is done, but flushes if needed!
281 * Returns nothing of value.
286 if (lpnt >= lpend) lflush();
287 *lpnt++ = 255 & x; *lpnt++ = 255 & (x>>8);
288 *lpnt++ = 255 & (x>>16); *lpnt++ = 255 & (x>>24);
292 * lwrite(buf,len) write a buffer to the output buffer
296 * Enter with the address and number of bytes to write out
297 * Returns nothing of value
305 if (len > 399) /* don't copy data if can just write it */
312 for (str=buf; len>0; --len)
321 if (lpnt >= lpend) lflush(); /* if buffer is full flush it */
322 num2 = lpbuf+BUFBIG-lpnt; /* # bytes left in output buffer */
323 if (num2 > len) num2=len;
324 str = lpnt; len -= num2;
325 while (num2--) *str++ = *buf++; /* copy in the bytes */
331 * long lgetc() Read one character from input buffer
333 * Returns 0 if EOF, otherwise the character
338 if (ipoint != iepoint) return(inbuffer[ipoint++]);
339 if (iepoint!=MAXIBUF) return(0);
340 if ((i=read(fd,inbuffer,MAXIBUF))<=0)
342 if (i!=0) write(1,"error reading from input file\n",30);
343 iepoint = ipoint = 0; return(0);
345 ipoint=1; iepoint=i; return(*inbuffer);
349 * long lrint() Read one integer from input buffer
351 * +---------+---------+---------+---------+
353 * | order | | | order |
354 * | byte | | | byte |
355 * +---------+---------+---------+---------+
356 * 31 --- 24 23 --- 16 15 --- 8 7 --- 0
358 * The save order is low order first, to high order (4 bytes total)
359 * Returns the int read
364 i = 255 & lgetc(); i |= (255 & lgetc()) << 8;
365 i |= (255 & lgetc()) << 16; i |= (255 & lgetc()) << 24;
370 * lrfill(address,number) put input bytes into a buffer
374 * Reads "number" bytes into the buffer pointed to by "address".
375 * Returns nothing of value
385 if (iepoint == ipoint)
387 if (num>5) /* fast way */
389 if (read(fd,adr,num) != num)
390 write(2,"error reading from input file\n",30);
393 else { *adr++ = lgetc(); --num; }
397 num2 = iepoint-ipoint; /* # of bytes left in the buffer */
398 if (num2 > num) num2=num;
399 pnt = inbuffer+ipoint; num -= num2; ipoint += num2;
400 while (num2--) *adr++ = *pnt++;
406 * char *lgetw() Get a whitespace ended word from input
408 * Returns pointer to a buffer that contains word. If EOF, returns a NULL
413 int n=LINBUFSIZE,quote=0;
415 do cc=lgetc(); while ((cc <= 32) && (cc > NULL)); /* eat whitespace */
416 for ( ; ; --n,cc=lgetc())
418 if ((cc==NULL) && (lgp==lgetwbuf)) return(NULL); /* EOF */
419 if ((n<=1) || ((cc<=32) && (quote==0))) { *lgp=NULL; return(lgetwbuf); }
420 if (cc != '"') *lgp++ = cc; else quote ^= 1;
425 * char *lgetl() Function to read in a line ended by newline or EOF
427 * Returns pointer to a buffer that contains the line. If EOF, returns NULL
435 if ((*str++ = ch = lgetc()) == NULL)
437 if (str == lgetwbuf+1) return(NULL); /* EOF */
438 ot: *str = NULL; return(lgetwbuf); /* line ended by EOF */
440 if ((ch=='\n') || (i<=1)) goto ot; /* line ended by \n */
445 * lcreat(filename) Create a new file for write
448 * lcreat((char*)0); means to the terminal
449 * Returns -1 if error, otherwise the file descriptor opened.
454 lpnt = lpbuf; lpend = lpbuf+BUFBIG;
455 if (str==NULL) return(lfd=1);
456 if ((lfd=creat(str,0644)) < 0)
458 lfd=1; lprintf("error creating file <%s>\n",str); lflush(); return(-1);
464 * lopen(filename) Open a file for read
467 * lopen(0) means from the terminal
468 * Returns -1 if error, otherwise the file descriptor opened.
473 ipoint = iepoint = MAXIBUF;
474 if (str==NULL) return(fd=0);
475 if ((fd=open(str,0)) < 0)
477 lwclose(); lfd=1; lpnt=lpbuf; return(-1);
483 * lappend(filename) Open for append to an existing file
486 * lappend(0) means to the terminal
487 * Returns -1 if error, otherwise the file descriptor opened.
492 lpnt = lpbuf; lpend = lpbuf+BUFBIG;
493 if (str==NULL) return(lfd=1);
494 if ((lfd=open(str,2)) < 0)
498 lseek(lfd,0,2); /* seek to end of file */
503 * lrclose() close the input file
505 * Returns nothing of value.
509 if (fd > 0) close(fd);
513 * lwclose() close output file flushing if needed
515 * Returns nothing of value.
519 lflush(); if (lfd > 2) close(lfd);
523 * lprcat(string) append a string to the output buffer
524 * avoids calls to lprintf (time consuming)
530 if (lpnt >= lpend) lflush();
532 while (*str2++ = *str++);
538 * cursor(x,y) Subroutine to set the cursor position
540 * x and y are the cursor coordinates, and lpbuff is the output buffer where
541 * escape sequence will be placed.
543 static char *y_num[]= { "\33[","\33[","\33[2","\33[3","\33[4","\33[5","\33[6",
544 "\33[7","\33[8","\33[9","\33[10","\33[11","\33[12","\33[13","\33[14",
545 "\33[15","\33[16","\33[17","\33[18","\33[19","\33[20","\33[21","\33[22",
548 static char *x_num[]= { "H","H",";2H",";3H",";4H",";5H",";6H",";7H",";8H",";9H",
549 ";10H",";11H",";12H",";13H",";14H",";15H",";16H",";17H",";18H",";19H",
550 ";20H",";21H",";22H",";23H",";24H",";25H",";26H",";27H",";28H",";29H",
551 ";30H",";31H",";32H",";33H",";34H",";35H",";36H",";37H",";38H",";39H",
552 ";40H",";41H",";42H",";43H",";44H",";45H",";46H",";47H",";48H",";49H",
553 ";50H",";51H",";52H",";53H",";54H",";55H",";56H",";57H",";58H",";59H",
554 ";60H",";61H",";62H",";63H",";64H",";65H",";66H",";67H",";68H",";69H",
555 ";70H",";71H",";72H",";73H",";74H",";75H",";76H",";77H",";78H",";79H",
562 if (lpnt >= lpend) lflush();
564 p = y_num[y]; /* get the string to print */
565 while (*p) *lpnt++ = *p++; /* print the string */
567 p = x_num[x]; /* get the string to print */
568 while (*p) *lpnt++ = *p++; /* print the string */
572 * cursor(x,y) Put cursor at specified coordinates staring at [1,1] (termcap)
577 if (lpnt >= lpend) lflush ();
579 *lpnt++ = CURSOR; *lpnt++ = x; *lpnt++ = y;
584 * Routine to position cursor at beginning of 24th line
593 * Warning: ringing the bell is control code 7. Don't use in defines.
594 * Don't change the order of these defines.
595 * Also used in helpfiles. Codes used in helpfiles should be \E[1 to \E[7 with
599 static char cap[256];
600 char *CM, *CE, *CD, *CL, *SO, *SE, *AL, *DL;/* Termcap capabilities */
601 static char *outbuf=0; /* translated output buffer */
606 * init_term() Terminal initialization -- setup termcap info
611 char *capptr = cap+10;
615 switch (tgetent(termbuf, term = getenv("TERM")))
618 write(2, "Cannot open termcap file.\n", 26); exit(1);
620 write(2, "Cannot find entry of ", 21);
621 write(2, term, strlen (term));
622 write(2, " in termcap\n", 12);
626 if (gtty(0, &tt) == 0)
627 /* ospeed = tt.sg_ospeed */ ;
629 CM = tgetstr("cm", &capptr); /* Cursor motion */
630 CE = tgetstr("ce", &capptr); /* Clear to eoln */
631 CL = tgetstr("cl", &capptr); /* Clear screen */
634 AL = tgetstr("al", &capptr); /* Insert line */
635 DL = tgetstr("dl", &capptr); /* Delete line */
636 SO = tgetstr("so", &capptr); /* Begin standout mode */
637 SE = tgetstr("se", &capptr); /* End standout mode */
638 CD = tgetstr("cd", &capptr); /* Clear to end of display */
640 if (!CM) /* can't find cursor motion entry */
642 write(2, "Sorry, for a ",13); write(2, term, strlen(term));
643 write(2, ", I can't find the cursor motion entry in termcap\n",50);
646 if (!CE) /* can't find clear to end of line entry */
648 write(2, "Sorry, for a ",13); write(2, term, strlen(term));
649 write(2,", I can't find the clear to end of line entry in termcap\n",57);
652 if (!CL) /* can't find clear entire screen entry */
654 write(2, "Sorry, for a ",13); write(2, term, strlen(term));
655 write(2, ", I can't find the clear entire screen entry in termcap\n",56);
658 if ((outbuf=malloc(BUFBIG+16))==0) /* get memory for decoded output buffer*/
660 write(2,"Error malloc'ing memory for decoded output buffer\n",50);
661 died(-285); /* malloc() failure */
667 * cl_line(x,y) Clear the whole line indicated by 'y' and leave cursor at [x,y]
673 cursor(x,y); lprcat("\33[2K");
675 cursor(1,y); *lpnt++ = CL_LINE; cursor(x,y);
680 * cl_up(x,y) Clear screen from [x,1] to current position. Leave cursor at [x,y]
686 cursor(x,y); lprcat("\33[1J\33[2K");
690 for (i=1; i<=y; i++) { *lpnt++ = CL_LINE; *lpnt++ = '\n'; }
696 * cl_dn(x,y) Clear screen from [1,y] to end of display. Leave cursor at [x,y]
702 cursor(x,y); lprcat("\33[J\33[2K");
709 for (i=y; i<=24; i++) { *lpnt++ = CL_LINE; if (i!=24) *lpnt++ = '\n'; }
719 * standout(str) Print the argument string in inverse video (standout mode).
738 * set_score_output() Called when output should be literally printed.
746 * lflush() Flush the output buffer
748 * Returns nothing of value.
749 * for termcap version: Flush output in output buffer according to output
750 * status as indicated by `enable_scroll'
753 static int scrline=18; /* line # for wraparound instead of scrolling if no DL */
761 if ((lpoint = lpnt - lpbuf) > 0)
764 c[BYTESOUT] += lpoint;
766 if (enable_scroll <= -1)
769 if (write(lfd,lpbuf,lpoint) != lpoint)
770 write(2,"error writing to output file\n",29);
771 lpnt = lpbuf; /* point back to beginning of buffer */
774 for (str = lpbuf; str < lpnt; str++)
776 if (*str>=32) { putchar (*str); curx++; }
779 case CLEAR: tputs (CL, 0, putchar); curx = cury = 0;
782 case CL_LINE: tputs (CE, 0, putchar);
785 case CL_DOWN: tputs (CD, 0, putchar);
788 case ST_START: tputs (SO, 0, putchar);
791 case ST_END: tputs (SE, 0, putchar);
794 case CURSOR: curx = *++str - 1; cury = *++str - 1;
795 tputs (tgoto (CM, curx, cury), 0, putchar);
798 case '\n': if ((cury == 23) && enable_scroll)
800 if (!DL || !AL) /* wraparound or scroll? */
802 if (++scrline > 23) scrline=19;
804 if (++scrline > 23) scrline=19;
805 tputs (tgoto (CM, 0, scrline), 0, putchar);
806 tputs (CE, 0, putchar);
808 if (--scrline < 19) scrline=23;
809 tputs (tgoto (CM, 0, scrline), 0, putchar);
810 tputs (CE, 0, putchar);
814 tputs (tgoto (CM, 0, 19), 0, putchar);
815 tputs (DL, 0, putchar);
816 tputs (tgoto (CM, 0, 23), 0, putchar);
817 /* tputs (AL, 0, putchar); */
822 putchar ('\n'); cury++;
827 default: putchar (*str); curx++;
832 flush_buf(); /* flush real output buffer now */
836 * lflush() flush the output buffer
838 * Returns nothing of value.
843 if ((lpoint = lpnt - lpbuf) > 0)
846 c[BYTESOUT] += lpoint;
848 if (write(lfd,lpbuf,lpoint) != lpoint)
849 write(2,"error writing to output file\n",29);
851 lpnt = lpbuf; /* point back to beginning of buffer */
858 * putchar(ch) Print one character in decoded output buffer.
863 outbuf[pindex++] = c;
864 if (pindex >= BUFBIG) flush_buf();
868 * flush_buf() Flush buffer with decoded output.
872 if (pindex) write(lfd, outbuf, pindex);
877 * char *tmcapcnv(sd,ss) Routine to convert VT100 escapes to termcap format
879 * Processes only the \33[#m sequence (converts . files for termcap use
881 char *tmcapcnv(sd,ss)
884 int tmstate=0; /* 0=normal, 1=\33 2=[ 3=# */
885 char tmdigit=0; /* the # in \33[#m */
890 case 0: if (*ss=='\33') { tmstate++; break; }
894 case 1: if (*ss!='[') goto ign;
897 case 2: if (isdigit(*ss)) { tmdigit= *ss-'0'; tmstate++; break; }
898 if (*ss == 'm') { *sd++ = ST_END; goto ign2; }
900 case 3: if (*ss == 'm')
902 if (tmdigit) *sd++ = ST_START;
910 *sd=0; /* NULL terminator */
916 * beep() Routine to emit a beep if enabled (see no-beep in .larnopts)
920 if (!nobeep) *lpnt++ = '\7';