]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/console/conio.c
Restore old split path in sql.c
[bacula/bacula] / bacula / src / console / conio.c
1 /*        
2       Generalized console input/output handler                     
3       A maintanable replacement for readline()
4
5          Kern Sibbald, December MMIII
6
7       This code is in part derived from code that I wrote in
8       1981, so some of it is a bit old and could use a cleanup.
9          
10 */
11 /*
12    Copyright (C) 1981-2004 Kern Sibbald and John Walker
13
14    This program is free software; you can redistribute it and/or
15    modify it under the terms of the GNU General Public License as
16    published by the Free Software Foundation; either version 2 of
17    the License, or (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22    General Public License for more details.
23
24    You should have received a copy of the GNU General Public
25    License along with this program; if not, write to the Free
26    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
27    MA 02111-1307, USA.
28
29  */
30
31
32 #ifdef  TEST_PROGRAM
33 #include <stdio.h>
34 #include <unistd.h>
35 #include <stdlib.h>
36 #include <signal.h>
37 #include <string.h>
38 #include <ctype.h> 
39 #else
40
41 /* We are in Bacula */
42 #include "bacula.h"
43
44 #endif
45
46 #ifdef HAVE_TERMCAP_H
47 #include <termcap.h>
48 #endif
49 #include "func.h"
50
51
52 /* From termios library */
53 extern char *BC;
54 extern char *UP;
55
56 /* Forward referenced functions */
57 static void sigintcatcher(int);
58 static void add_smap(char *str, int func);
59
60
61 /* Global variables */
62
63 static char *t_up = "\n";                    /* scroll up character */
64 static char *t_honk = "\007";                /* sound beep */
65 static char *t_il;                           /* insert line */
66 static char *t_dl;                           /* delete line */
67 static char *t_cs;                           /* clear screen */
68 static char *t_cl;                           /* clear line */
69 static int t_width = 79;                     /* terminal width */
70 static int t_height = 24;                    /* terminal height */
71 static int linsdel_ok = 0;              /* set if term has line insert & delete fncs */
72
73 static char *t_cm;                           /* cursor positioning */
74 static char *t_ti;                           /* init sequence */
75 static char *t_te;                           /* end sequence */
76 static char *t_do;                           /* down one line */
77 static char *t_sf;                           /* scroll screen one line up */
78
79 /* Keypad and Function Keys */
80 static char *kl;                             /* left key */
81 static char *kr;                             /* right */
82 static char *ku;                             /* up */
83 static char *kd;                             /* down */
84 static char *kh;                             /* home */
85 static char *kb;                             /* backspace */
86 static char *kD;                             /* delete key */
87 static char *kI;                             /* insert */
88 static char *kN;                             /* next page */
89 static char *kP;                             /* previous page */
90 static char *kH;                             /* home */
91 static char *kE;                             /* end */
92
93 #ifndef EOS
94 #define EOS  '\0'                     /* end of string terminator */
95 #endif
96
97 #define TRUE  1
98 #define FALSE 0
99 /*
100  * Stab entry. Input chars (str), the length, and the desired
101  *  func code.
102  */
103 typedef struct s_stab {
104    struct s_stab *next;
105    int len;
106    int func;
107    char *str;
108 } stab_t;
109
110 #define MAX_STAB 30
111
112 static stab_t **stab = NULL;                 /* array of stabs by length */
113 static int num_stab;                         /* size of stab array */
114
115 static bool old_term_params_set = false;
116 static struct termios old_term_params;
117
118 /* Maintain lines in a doubly linked circular pool of lines. Each line is
119    preceded by a header defined by the lstr structure */
120
121
122 struct lstr {                         /* line pool structure */
123    struct lstr *prevl;                /* link to previous line */
124    struct lstr *nextl;                /* link to next line */
125    long len;                          /* length of line+header */
126    char used;                         /* set if line valid */
127    char line;                         /* line is actually varying length */
128 };
129
130 #ifdef unix
131 #define POOLEN 128000                 /* bytes in line pool */
132 #else
133 #define POOLEN 500                    /* bytes in line pool */
134 #endif
135 char pool[POOLEN];                    /* line pool */
136 #define PHDRL ((int)sizeof(struct lstr))  /* length of line header */
137
138 static struct lstr *lptr;             /* current line pointer */
139 static struct lstr *slptr;            /* store line pointer */
140 static int cl, cp;
141 static char *getnext(), *getprev();
142 static int first = 1;
143 static int mode_insert = 0;
144 static int mode_wspace = 1;           /* words separated by spaces */
145
146
147 static short char_map[600]= {
148    0,                                  F_SOL,    /* ^a Line start */
149    F_PRVWRD, /* ^b Previous word */    F_BREAK,  /* ^C break */
150    F_DELCHR, /* ^D Delete character */ F_EOL,    /* ^e End of line */
151    F_CSRRGT, /* ^f Right */            F_TABBAK, /* ^G Back tab */
152    F_CSRLFT, /* ^H Left */             F_TAB,    /* ^I Tab */
153    F_CSRDWN, /* ^J Down */             F_DELEOL, /* ^K kill to eol */
154    F_CLRSCRN,/* ^L clear screen */     F_RETURN, /* ^M Carriage return */
155    F_RETURN, /* ^N enter line  */      F_CONCAT, /* ^O Concatenate lines */
156    F_CSRUP,  /* ^P cursor up */        F_TINS,   /* ^Q Insert character mode */
157    F_PAGUP,  /* ^R Page up */          F_CENTER, /* ^S Center text */
158    F_PAGDWN, /* ^T Page down */        F_DELSOL, /* ^U delete to start of line */
159    F_DELWRD, /* ^V Delete word */      F_PRVWRD, /* ^W Previous word */
160    F_NXTMCH, /* ^X Next match */       F_DELEOL, /* ^Y Delete to end of line */
161    F_BACKGND,/* ^Z Background */       0x1B,     /* ^[=ESC escape */
162    F_TENTRY, /* ^\ Entry mode */       F_PASTECB,/* ^]=paste clipboard */
163    F_HOME,   /* ^^ Home */             F_ERSLIN, /* ^_ Erase line */
164
165    ' ','!','"','#','$','%','&','\047',
166    '(',')','*','+','\054','-','.','/',
167    '0','1','2','3','4','5','6','7',
168    '8','9',':',';','<','=','>','?',
169    '@','A','B','C','D','E','F','G',
170    'H','I','J','K','L','M','N','O',
171    'P','Q','R','S','T','U','V','W',
172    'X','Y','Z','[','\\',']','^','_',
173    '\140','a','b','c','d','e','f','g',
174    'h','i','j','k','l','m','n','o',
175    'p','q','r','s','t','u','v','w',
176    'x','y','z','{','|','}','\176',F_ERSCHR  /* erase character */
177
178   };
179
180
181 #define NVID  0x1E                    /* normal video -- blue */
182 #define RVID  0x4F                    /* reverse video -- red */
183 #define MNVID 0x07                    /* normal video (monochrome tube) */
184 #define MRVID 0x70                    /* reverse video (monochrome tube) */
185
186
187 /* Local variables */
188
189 #define CR '\r'                       /* carriage return */
190
191
192 /* Function Prototypes */
193
194 static int input_char(void);
195 static int t_gnc(void);
196 static void insert_space(char *curline, int line_len);
197 static void forward(int i, char *str, int str_len);
198 static void backup(int i);
199 static void delchr(int cnt, char *curline, int line_len);
200 static int iswordc(char c);
201 static int  next_word(char *ldb_buf);
202 static int  prev_word(char *ldb_buf);
203 static void prtcur(char *str);
204 static void poolinit(void);
205 static char * getnext(void);
206 static char * getprev(void);
207 static void putline(char *newl, int newlen);
208 static void t_honk_horn(void);
209 static void t_insert_line(void);
210 static void t_delete_line(void);
211 static void t_clrline(int pos, int width);
212 void t_sendl(char *msg, int len);
213 void t_send(char *msg);
214 void t_char(char c);
215 static void asclrs();
216 static void ascurs(int y, int x);
217
218 static void rawmode(FILE *input);
219 static void normode(void);
220 static int t_getch();
221 static void asclrl(int pos, int width);
222 static void asinsl();
223 static void asdell();
224
225 int input_line(char *string, int length);
226 void con_term();
227 void trapctlc();
228     
229 void con_init(FILE *input)
230 {
231    atexit(con_term); 
232    rawmode(input);
233    trapctlc();
234 }
235
236 /*
237  * Zed control keys
238  */
239 void con_set_zed_keys(void)
240 {
241    char_map[1]  = F_NXTWRD; /* ^A Next Word */
242    char_map[2]  = F_SPLIT;  /* ^B Split line */
243    char_map[3]  = F_EOI;    /* ^C Quit */
244    char_map[4]  = F_DELCHR; /* ^D Delete character */
245    char_map[5]  = F_EOF;    /* ^E End of file */
246    char_map[6]  = F_INSCHR; /* ^F Insert character */
247    char_map[7]  = F_TABBAK; /* ^G Back tab */
248    char_map[8]  = F_CSRLFT; /* ^H Left */
249    char_map[9]  = F_TAB;    /* ^I Tab */
250    char_map[10] = F_CSRDWN; /* ^J Down */
251    char_map[11] = F_CSRUP;  /* ^K Up */
252    char_map[12] = F_CSRRGT; /* ^L Right */
253    char_map[13] = F_RETURN; /* ^M Carriage return */
254    char_map[14] = F_EOL;    /* ^N End of line */
255    char_map[15] = F_CONCAT; /* ^O Concatenate lines */
256    char_map[16] = F_MARK;   /* ^P Set marker */
257    char_map[17] = F_TINS;   /* ^Q Insert character mode */
258    char_map[18] = F_PAGUP;  /* ^R Page up */
259    char_map[19] = F_CENTER; /* ^S Center text */
260    char_map[20] = F_PAGDWN; /* ^T Page down */
261    char_map[21] = F_SOL;    /* ^U Line start */
262    char_map[22] = F_DELWRD; /* ^V Delete word */
263    char_map[23] = F_PRVWRD; /* ^W Previous word */
264    char_map[24] = F_NXTMCH; /* ^X Next match */
265    char_map[25] = F_DELEOL; /* ^Y Delete to end of line */
266    char_map[26] = F_DELLIN; /* ^Z Delete line */
267    /* 27 = ESC */
268    char_map[28] = F_TENTRY; /* ^\ Entry mode */
269    char_map[29] = F_PASTECB;/* ^]=paste clipboard */
270    char_map[30] = F_HOME;   /* ^^ Home */
271    char_map[31] = F_ERSLIN; /* ^_ Erase line */
272
273 }
274
275 void con_term()
276 {
277    normode();
278 }
279
280 #ifdef TEST_PROGRAM
281 /*
282  * Guarantee that the string is properly terminated */
283 char *bstrncpy(char *dest, const char *src, int maxlen)
284 {
285    strncpy(dest, src, maxlen-1);
286    dest[maxlen-1] = 0;
287    return dest;
288 }
289 #endif
290
291
292 /*
293  * New style string mapping to function code
294  */
295 static int do_smap(int c)
296 {
297     char str[MAX_STAB];
298     int len = 0; 
299     stab_t *tstab;
300     int i, found;
301
302     len = 1;
303     str[0] = c;
304     str[1] = 0;
305
306     if (c != 27) {
307        c = char_map[c];
308     }
309     if (c <= 0) {
310        return c;
311     }
312     for ( ;; ) {
313        found = 0;
314        for (i=len-1; i<MAX_STAB; i++) {
315           for (tstab=stab[i]; tstab; tstab=tstab->next) {
316              if (strncmp(str, tstab->str, len) == 0) {
317                 if (len == tstab->len) {
318                    return tstab->func;
319                 }
320                 found = 1;
321                 break;                /* found possibility continue searching */
322              }
323           }
324        }
325        if (!found) {
326           return len==1?c:0;
327        }
328        /* found partial match, so get next character and retry */
329        str[len++] = t_gnc();
330        str[len] = 0;
331     }
332 }
333
334 #ifdef DEBUG_x
335 static void dump_stab()
336 {
337     int i, j, c;
338     stab_t *tstab;
339     char buf[100];
340
341     for (i=0; i<MAX_STAB; i++) {
342        for (tstab=stab[i]; tstab; tstab=tstab->next) {
343           for (j=0; j<tstab->len; j++) {
344              c = tstab->str[j];
345              if (c < 0x20 || c > 0x7F) {
346                 sprintf(buf, " 0x%x ", c);
347                 t_send(buf);
348              } else {
349                 buf[0] = c;
350                 buf[1] = 0;
351                 t_sendl(buf, 1);
352              }
353           }
354           sprintf(buf, " func=%d len=%d\n\r", tstab->func, tstab->len);
355           t_send(buf);
356        }
357     }
358 }
359 #endif
360
361 /*
362  * New routine. Add string to string->func mapping table.
363  */
364 static void add_smap(char *str, int func)
365 {
366    stab_t *tstab;
367    int len;
368   
369    if (!str) {
370       return;
371    }
372    len = strlen(str);
373    if (len == 0) {
374 /*    errmsg("String for func %d is zero length\n", func); */
375       return;
376    }
377    tstab = (stab_t *)malloc(sizeof(stab_t));
378    memset(tstab, 0, sizeof(stab_t));
379    tstab->len = len;
380    tstab->str = (char *)malloc(tstab->len + 1);
381    bstrncpy(tstab->str, str, tstab->len + 1);
382    tstab->func = func;
383    if (tstab->len > num_stab) {
384       printf("stab string too long %d. Max is %d\n", tstab->len, num_stab);
385       exit(1);
386    }
387    tstab->next = stab[tstab->len-1];
388    stab[tstab->len-1] = tstab;
389 /* printf("Add_smap tstab=%x len=%d func=%d tstab->next=%x\n\r", tstab, len, 
390           func, tstab->next); */
391
392 }
393
394
395 /* Get the next character from the terminal - performs table lookup on
396    the character to do the desired translation */
397 static int
398 input_char()
399 {
400     int c;
401
402     if ((c=t_gnc()) <= 599) {         /* IBM generates codes up to 260 */
403           c = do_smap(c);
404     } else if (c > 1000) {            /* stuffed function */
405        c -= 1000;                     /* convert back to function code */
406     }
407     if (c <= 0) {
408         t_honk_horn();
409     }
410     /* if we got a screen size escape sequence, read height, width */
411     if (c == F_SCRSIZ) {
412        int y, x;
413        y = t_gnc() - 0x20;        /* y */
414        x = t_gnc() - 0x20;        /* x */
415        c = input_char();
416     }
417     return c;
418 }
419
420
421 /* Get a complete input line */
422
423 int
424 input_line(char *string, int length)
425 {
426    char curline[200];                 /* edit buffer */
427    int noline;
428    int c;
429
430     if (first) {
431         poolinit();                   /* build line pool */
432         first = 0;
433     }
434     noline = 1;                       /* no line fetched yet */
435     for (cl=cp=0; cl<length && cl<(int)sizeof(curline); ) {
436         switch (c=(int)input_char()) {
437         case F_RETURN:                /* CR */
438             t_sendl("\r\n", 2);       /* yes, print it and */
439             goto done;                /* get out */
440         case F_CLRSCRN:               /* clear screen */
441            asclrs();
442            t_sendl(curline, cl);
443            ascurs(0, cp);
444            break;
445         case F_CSRUP:
446             if (noline) {             /* no line fetched yet */
447                 getnext();            /* getnext so getprev gets current */
448                 noline = 0;           /* we now have line */
449             }
450             bstrncpy(curline, getprev(), sizeof(curline));
451             prtcur(curline);
452             break;
453         case F_CSRDWN:
454             noline = 0;               /* mark line fetched */
455             bstrncpy(curline, getnext(), sizeof(curline));
456             prtcur(curline);
457             break;
458         case F_INSCHR:
459             insert_space(curline, sizeof(curline));
460             break;
461         case F_DELCHR:
462             delchr(1, curline, sizeof(curline));       /* delete one character */
463             break;
464         case F_CSRLFT:                /* Backspace */
465             backup(1);
466             break;
467         case F_CSRRGT:
468             forward(1,curline, sizeof(curline));
469             break;
470         case F_ERSCHR:                /* Rubout */
471             backup(1);
472             delchr(1, curline, sizeof(curline));
473             break;
474         case F_DELEOL:
475             t_clrline(0, t_width);
476             if (cl > cp)
477                 cl = cp;
478             break;
479         case F_NXTWRD:
480             forward(next_word(curline),curline, sizeof(curline));
481             break;
482         case F_PRVWRD:
483             backup(prev_word(curline));
484             break;
485         case F_DELWRD:
486             delchr(next_word(curline), curline, sizeof(curline)); /* delete word */
487             break;
488         case F_NXTMCH:                /* Ctl-X */
489             if (cl==0) {
490                 *string = EOS;        /* terminate string */
491                 return(c);            /* give it to him */
492             }
493             /* Note fall through */
494         case F_DELLIN:
495         case F_ERSLIN:
496             backup(cp);               /* backup to beginning of line */
497             t_clrline(0,t_width);     /* erase line */
498             cp = 0;
499             cl = 0;                   /* reset cursor counter */
500             break;
501         case F_SOL:
502             backup(cp);
503             break;
504         case F_EOL:
505             while (cp < cl) {
506                 forward(1,curline, sizeof(curline));
507             }
508             while (cp > cl) {
509                 backup(1);
510             }
511             break;
512         case F_TINS:                  /* toggle insert mode */
513             mode_insert = !mode_insert;  /* flip bit */
514             break;
515         default:
516             if (c > 255) {            /* function key hit */
517                 if (cl==0) {          /* if first character then */
518                     *string = EOS;         /* terminate string */
519                     return c;              /* return it */
520                 }
521                 t_honk_horn();        /* complain */
522             } else {
523                 if (mode_insert) {
524                     insert_space(curline, sizeof(curline));
525                 }
526                 curline[cp++] = c;    /* store character in line being built */
527                 t_char((char)c);      /* echo character to terminal */
528                 if (cp > cl) {
529                     cl = cp;          /* keep current length */
530                 }
531             }
532             break;
533         }                             /* end switch */
534     }
535 /* If we fall through here rather than goto done, the line is too long
536    simply return what we have now. */
537 done:
538     curline[cl++] = EOS;              /* terminate */
539     bstrncpy(string,curline,length);           /* return line to caller */
540     /* Note, put line zaps curline */
541     putline(curline,cl);              /* save line for posterity */
542     return 0;                         /* give it to him/her */
543 }
544
545 /* Insert a space at the current cursor position */
546 static void
547 insert_space(char *curline, int curline_len)
548 {
549     int i;
550
551     if (cp > cl || cl+1 > curline_len) return;
552     /* Note! source and destination overlap */
553     memmove(&curline[cp+1],&curline[cp],i=cl-cp);
554     cl++;
555     i++;
556     curline[cp] = ' ';
557     forward(i,curline, curline_len);
558     backup(i);
559 }
560
561
562 /* Move cursor forward keeping characters under it */
563 static void
564 forward(int i,char *str, int str_len)
565 {
566     while (i--) {
567         if (cp > str_len) {
568            return;
569         }
570         if (cp>=cl) {
571             t_char(' ');
572             str[cp+1] = ' ';
573         } else {
574             t_char(str[cp]);
575         }
576         cp++;
577     }
578 }
579
580 /* Backup cursor keeping characters under it */
581 static void
582 backup(int i)
583 {
584     for ( ;i && cp; i--,cp--)
585         t_char('\010');
586 }
587
588 /* Delete the character under the cursor */
589 static void
590 delchr(int cnt, char *curline, int line_len) 
591 {
592     register int i;
593
594     if (cp > cl)
595         return;
596     if ((i=cl-cp-cnt+1) > 0) {
597         memcpy(&curline[cp],&curline[cp+cnt],i);
598     }
599     curline[cl -= cnt] = EOS;
600     t_clrline(0,t_width);
601     if (cl > cp) {
602         forward(i=cl-cp,curline, line_len);
603         backup(i);
604     }
605 }
606
607 /* Determine if character is part of a word */
608 static int
609 iswordc(char c)
610 {
611    if (mode_wspace)
612       return !isspace(c);
613    if (c >= '0' && c <= '9')
614       return TRUE;
615    if (c == '$' || c == '%')
616       return TRUE;
617    return isalpha(c);
618 }
619
620 /* Return number of characters to get to next word */
621 static int
622 next_word(char *ldb_buf)
623 {
624     int ncp;
625
626     if (cp > cl)
627         return 0;
628     ncp = cp;
629     for ( ; ncp<cl && iswordc(*(ldb_buf+ncp)); ncp++) ;
630     for ( ; ncp<cl && !iswordc(*(ldb_buf+ncp)); ncp++) ;
631     return ncp-cp;
632 }
633
634 /* Return number of characters to get to previous word */
635 static int
636 prev_word(char *ldb_buf)
637 {
638     int ncp, i;
639
640     if (cp == 0)                      /* if at begin of line stop now */
641         return 0;
642     if (cp > cl)                      /* if past eol start at eol */
643         ncp=cl+1;
644     else
645         ncp = cp;
646     /* backup to end of previous word - i.e. skip special chars */
647     for (i=ncp-1; i && !iswordc(*(ldb_buf+i)); i--) ;
648     if (i == 0) {                     /* at beginning of line? */
649         return cp;                    /* backup to beginning */
650     }
651     /* now move back through word to beginning of word */
652     for ( ; i && iswordc(*(ldb_buf+i)); i--) ;
653     ncp = i+1;                        /* position to first char of word */
654     if (i==0 && iswordc(*ldb_buf))    /* check for beginning of line */
655         ncp = 0;
656     return cp-ncp;                    /* return count */
657 }
658
659 /* Display new current line */
660 static void
661 prtcur(char *str)
662 {
663     backup(cp);
664     t_clrline(0,t_width);
665     cp = cl = strlen(str);
666     t_sendl(str,cl);
667 }
668
669
670 /* Initialize line pool. Split pool into two pieces. */
671 static void
672 poolinit()
673 {
674     slptr = lptr = (struct lstr *)pool;
675     lptr->nextl = lptr;
676     lptr->prevl = lptr;
677     lptr->used = 1;
678     lptr->line = 0;
679     lptr->len = POOLEN;
680 }
681
682
683 /* Return pointer to next line in the pool and advance current line pointer */
684 static char *
685 getnext()
686 {
687     do {                              /* find next used line */
688         lptr = lptr->nextl;
689     } while (!lptr->used);
690     return (char *)&lptr->line;
691 }
692
693 /* Return pointer to previous line in the pool */
694 static char *
695 getprev()
696 {
697     do {                              /* find previous used line */
698         lptr = lptr->prevl;
699     } while (!lptr->used);
700     return (char *)&lptr->line;
701 }
702
703 static void
704 putline(char *newl, int newlen)
705 {
706     struct lstr *nptr;                /* points to next line */
707     char *p;
708
709     lptr = slptr;                     /* get ptr to last line stored */
710     lptr = lptr->nextl;               /* advance pointer */
711     if ((char *)lptr-pool+newlen+PHDRL > POOLEN) { /* not enough room */
712         lptr->used = 0;               /* delete line */
713         lptr = (struct lstr *)pool;   /* start at beginning of buffer */
714     }
715     while (lptr->len < newlen+PHDRL) { /* concatenate buffers */
716         nptr = lptr->nextl;           /* point to next line */
717         lptr->nextl = nptr->nextl;    /* unlink it from list */
718         nptr->nextl->prevl = lptr;
719         lptr->len += nptr->len;
720     }
721     if (lptr->len > newlen + 2 * PHDRL) { /* split buffer */
722         nptr = (struct lstr *)((char *)lptr + newlen + PHDRL);
723         /* Appropriate byte alignment - normally 2 byte, but on
724            sparc we need 4 byte alignment, so we always do 4 */
725         if (((unsigned)nptr & 3) != 0) { /* test four byte alignment */
726             p = (char *)nptr;
727             nptr = (struct lstr *)((((unsigned) p) & ~3) + 4);
728         }
729         nptr->len = lptr->len - ((char *)nptr - (char *)lptr);
730         lptr->len -= nptr->len;
731         nptr->nextl = lptr->nextl;    /* link in new buffer */
732         lptr->nextl->prevl = nptr;
733         lptr->nextl = nptr;
734         nptr->prevl = lptr;
735         nptr->used = 0;
736     }
737     memcpy(&lptr->line,newl,newlen);
738     lptr->used = 1;                   /* mark line used */
739     slptr = lptr;                     /* save as stored line */
740 }
741
742 #ifdef  DEBUGOUT
743 static void
744 dump(struct lstr *ptr, char *msg)
745 {
746     printf("%s buf=%x nextl=%x prevl=%x len=%d used=%d\n",
747         msg,ptr,ptr->nextl,ptr->prevl,ptr->len,ptr->used);
748     if (ptr->used)
749         printf("line=%s\n",&ptr->line);
750 }
751 #endif  /* DEBUGOUT */
752
753
754 /* Honk horn on terminal */
755 static void
756 t_honk_horn()
757 {
758     t_send(t_honk);
759 }
760
761 /* Insert line on terminal */
762 static void
763 t_insert_line()
764 {
765     asinsl();
766 }
767
768 /* Delete line from terminal */
769 static void
770 t_delete_line()
771 {
772     asdell();
773 }
774
775 /* clear line from pos to width */
776 static void
777 t_clrline(int pos, int width)
778 {
779     asclrl(pos, width);           /* clear to end of line */
780 }
781
782 /* Helper function to add string preceded by 
783  *  ESC to smap table */
784 static void add_esc_smap(char *str, int func)
785 {
786    char buf[100];
787    buf[0] = 0x1B;                     /* esc */
788    bstrncpy(buf+1, str, sizeof(buf)-1);
789    add_smap(buf, func);
790 }
791
792 /* Set raw mode on terminal file.  Basically, get the terminal into a
793    mode in which all characters can be read as they are entered.  CBREAK
794    mode is not sufficient.
795  */
796 static void rawmode(FILE *input)
797 {
798    struct termios t;
799    static char term_buf[2048];
800    static char *term_buffer = term_buf;
801    char *termtype = (char *)getenv("TERM");
802
803    /* Make sure we are dealing with a terminal */
804    if (!isatty(fileno(input))) {
805       return;
806    }
807    if (tcgetattr(0, &old_term_params) != 0) {
808       printf("conio: Cannot tcgetattr()\n");
809       exit(1);
810    }
811    old_term_params_set = true;
812    t = old_term_params;                         
813    t.c_cc[VMIN] = 1; /* satisfy read after 1 char */
814    t.c_cc[VTIME] = 0;
815    t.c_iflag &= ~(BRKINT | IGNPAR | PARMRK | INPCK | 
816                   ISTRIP | ICRNL | IXON | IXOFF | INLCR | IGNCR);     
817    t.c_iflag |= IGNBRK;
818    t.c_oflag |= ONLCR;
819    t.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL | ICANON |
820                   NOFLSH | TOSTOP);
821    tcflush(0, TCIFLUSH);
822    if (tcsetattr(0, TCSANOW, &t) == -1) {
823       printf("Cannot tcsetattr()\n");
824    }
825
826    /* Defaults, the main program can override these */
827    signal(SIGQUIT, SIG_IGN);
828    signal(SIGHUP, SIG_IGN);
829 // signal(SIGSTOP, SIG_IGN);
830    signal(SIGINT, sigintcatcher);
831    signal(SIGWINCH, SIG_IGN);   
832    signal(SIGQUIT, SIG_IGN);
833    signal(SIGCHLD, SIG_IGN);
834 // signal(SIGTSTP, SIG_IGN);
835
836    if (!termtype) {
837       printf("Cannot get terminal type.\n");
838       normode();
839       _exit(1);
840    }
841    if (tgetent(term_buffer, termtype) < 0) {
842       printf("Cannot get terminal termcap entry.\n");
843       normode();
844       _exit(1);
845    }
846    t_width = t_height = -1;
847    t_width = tgetnum("co") - 1;
848    t_height = tgetnum("li");
849    BC = NULL;
850    UP = NULL;
851    t_cm = (char *)tgetstr("cm", &term_buffer);
852    t_cs = (char *)tgetstr("cl", &term_buffer); /* clear screen */
853    t_cl = (char *)tgetstr("ce", &term_buffer); /* clear line */
854    t_dl = (char *)tgetstr("dl", &term_buffer); /* delete line */
855    t_il = (char *)tgetstr("al", &term_buffer); /* insert line */
856    t_honk = (char *)tgetstr("bl", &term_buffer); /* beep */
857    t_ti = (char *)tgetstr("ti", &term_buffer);
858    t_te = (char *)tgetstr("te", &term_buffer);
859    t_up = (char *)tgetstr("up", &term_buffer);
860    t_do = (char *)tgetstr("do", &term_buffer);
861    t_sf = (char *)tgetstr("sf", &term_buffer);
862
863    num_stab = MAX_STAB;                  /* get default stab size */
864    stab = (stab_t **)malloc(sizeof(stab_t *) * num_stab);
865    memset(stab, 0, sizeof(stab_t *) * num_stab);
866
867    /* Key bindings */
868    kl = (char *)tgetstr("kl", &term_buffer);
869    kr = (char *)tgetstr("kr", &term_buffer);
870    ku = (char *)tgetstr("ku", &term_buffer);
871    kd = (char *)tgetstr("kd", &term_buffer);
872    kh = (char *)tgetstr("kh", &term_buffer);
873    kb = (char *)tgetstr("kb", &term_buffer);
874    kD = (char *)tgetstr("kD", &term_buffer);
875    kI = (char *)tgetstr("kI", &term_buffer);
876    kN = (char *)tgetstr("kN", &term_buffer);
877    kP = (char *)tgetstr("kP", &term_buffer);
878    kH = (char *)tgetstr("kH", &term_buffer);
879    kE = (char *)tgetstr("kE", &term_buffer);
880
881    add_smap(kl, F_CSRLFT);
882    add_smap(kr, F_CSRRGT);
883    add_smap(ku, F_CSRUP);
884    add_smap(kd, F_CSRDWN);
885    add_smap(kI, F_TINS);
886    add_smap(kN, F_PAGDWN);
887    add_smap(kP, F_PAGUP);
888    add_smap(kH, F_HOME);
889    add_smap(kE, F_EOF);
890
891
892    add_esc_smap("[A",   F_CSRUP);
893    add_esc_smap("[B",   F_CSRDWN);
894    add_esc_smap("[C",   F_CSRRGT);
895    add_esc_smap("[D",   F_CSRLFT);
896    add_esc_smap("[1~",  F_HOME);
897    add_esc_smap("[2~",  F_TINS);
898    add_esc_smap("[3~",  F_DELCHR);
899    add_esc_smap("[4~",  F_EOF);
900    add_esc_smap("f",    F_NXTWRD);
901    add_esc_smap("b",    F_PRVWRD);
902
903
904 #ifdef needed
905    for (i=301; i<600; i++) {
906       char_map[i] = i;                /* setup IBM function codes */
907    }
908 #endif
909 }
910
911
912 /* Restore tty mode */
913 static void normode()
914 {
915    if (old_term_params_set) {
916       tcsetattr(0, TCSANOW, &old_term_params);
917       old_term_params_set = false;
918    }
919 }
920
921 /* Get next character from terminal/script file/unget buffer */
922 static int
923 t_gnc()
924 {
925     return t_getch();
926 }
927
928
929 /* Get next character from OS */
930 static int t_getch(void)
931 {
932    char c;
933
934    if (read(0, &c, 1) != 1) {
935       c = 0;
936    }
937    return (int)c;   
938 }
939     
940 #ifdef xxx
941
942 /* window_size -- Return window height and width to caller. */
943 static int window_size(int *height, int *width)         /* /window_size/ */
944 {
945    *width = tgetnum("co") - 1;
946    *height = tgetnum("li");
947    return 1;
948 }
949 #endif
950
951 /* Send message to terminal - primitive routine */
952 void
953 t_sendl(char *msg,int len)
954 {
955     write(1, msg, len);
956 }
957
958 void
959 t_send(char *msg)
960 {
961     if (msg == NULL) {
962        return;
963     }
964     t_sendl(msg, strlen(msg));    /* faster than one char at time */
965 }
966
967 /* Send single character to terminal - primitive routine - */
968 void
969 t_char(char c)
970 {
971    write(1, &c, 1);
972 }
973
974
975 static int brkflg = 0;              /* set on user break */
976
977 /* Routine to return true if user types break */
978 int usrbrk()
979 {
980    return brkflg;
981 }
982
983 /* Clear break flag */
984 void clrbrk()
985 {
986    brkflg = 0;
987
988 }
989
990 /* Interrupt caught here */
991 static void sigintcatcher(int sig)
992 {
993    brkflg++;
994    if (brkflg > 1) {
995       normode();
996       _exit(1);
997    }
998    signal(SIGINT, sigintcatcher);
999 }
1000
1001
1002 /* Trap Ctl-C */
1003 void trapctlc()
1004 {
1005    signal(SIGINT, sigintcatcher);
1006 }
1007
1008
1009 /* ASCLRL() -- Clear to end of line from current position */
1010 static void asclrl(int pos, int width) 
1011 {
1012     int i;
1013
1014     if (t_cl) {
1015         t_send(t_cl);                 /* use clear to eol function */
1016         return;
1017     }
1018     if (pos==1 && linsdel_ok) {
1019         t_delete_line();              /* delete line */
1020         t_insert_line();              /* reinsert it */
1021         return;
1022     }
1023     for (i=1; i<=width-pos+1; i++)
1024         t_char(' ');                  /* last resort, blank it out */
1025     for (i=1; i<=width-pos+1; i++)    /* backspace to original position */
1026         t_char(0x8);
1027     return;
1028   
1029 }
1030
1031
1032 /* ASCURS -- Set cursor position */
1033 static void ascurs(int y, int x)
1034 {
1035    t_send((char *)tgoto(t_cm, x, y));
1036 }
1037                                                                                         
1038
1039 /* ASCLRS -- Clear whole screen */
1040 static void asclrs() 
1041 {
1042    ascurs(0,0);
1043    t_send(t_cs);
1044 }
1045
1046
1047
1048 /* ASINSL -- insert new line after cursor */
1049 static void asinsl()
1050 {
1051    t_clrline(0, t_width);
1052    t_send(t_il);                      /* insert before */
1053 }
1054
1055 /* ASDELL -- Delete line at cursor */
1056 static void asdell()
1057 {
1058    t_send(t_dl);
1059 }