]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - terminal.c
Silly mistake - restore-cursor-pos doesn't make sure the cursor
[PuTTY.git] / terminal.c
1 #include <windows.h>
2
3 #include <stdio.h>
4 #include <stdlib.h>
5
6 #include "putty.h"
7
8 #define CL_ANSIMIN      0x0001  /* Everybody has these even MSDOS */
9 #define CL_VT100        0x0002  /* VT100 */
10 #define CL_VT100AVO     0x0004  /* VT100 +AVO; 132x24 (not 132x14) & attrs */
11 #define CL_VT102        0x0008  /* VT102 */
12 #define CL_VT220        0x0010  /* VT220 */
13 #define CL_VT320        0x0020  /* VT320 */
14 #define CL_VT420        0x0040  /* VT420 */
15 #define CL_VT510        0x0080  /* VT510, NB VT510 includes ANSI */
16 #define CL_VT340TEXT    0x0100  /* VT340 extensions that appear in the VT420 */
17 #define CL_ANSI         0x1000  /* ANSI ECMA-48 not in the VT100..VT420 */
18 #define CL_OTHER        0x2000  /* Others, Xterm, linux, putty, dunno, etc */
19
20 #define TM_ANSIMIN      (CL_ANSIMIN)
21 #define TM_VT100        (CL_ANSIMIN+CL_VT100)
22 #define TM_VT100AVO     (TM_VT100+CL_VT100AVO)
23 #define TM_VT102        (TM_VT100AVO+CL_VT102)
24 #define TM_PUTTY        (-1)
25
26 #define compatibility(x) \
27     if ( ((CL_##x)&compatibility_level) == 0 ) {        \
28        termstate=TOPLEVEL;                              \
29        break;                                           \
30     }
31
32 #define has_compat(x) ( ((CL_##x)&compatibility_level) != 0 )
33
34 static int compatibility_level = TM_PUTTY;
35
36
37 static unsigned long *text;            /* buffer of text on terminal screen */
38 static unsigned long *scrtop;          /* top of working screen */
39 static unsigned long *disptop;         /* top of displayed screen */
40 static unsigned long *sbtop;           /* top of scrollback */
41 static unsigned long *cpos;            /* cursor position (convenience) */
42 static unsigned long *disptext;        /* buffer of text on real screen */
43 static unsigned long *wanttext;        /* buffer of text we want on screen */
44 static unsigned long *alttext;         /* buffer of text on alt. screen */
45
46 static unsigned char *selspace;        /* buffer for building selections in */
47
48 #define TSIZE (sizeof(*text))
49 #define fix_cpos  do { cpos = scrtop + curs_y * (cols+1) + curs_x; } while(0)
50
51 static unsigned long curr_attr, save_attr;
52 static unsigned long erase_char = ERASE_CHAR;
53
54 static int curs_x, curs_y;             /* cursor */
55 static int save_x, save_y;             /* saved cursor position */
56 static int marg_t, marg_b;             /* scroll margins */
57 static int dec_om;                     /* DEC origin mode flag */
58 static int wrap, wrapnext;             /* wrap flags */
59 static int insert;                     /* insert-mode flag */
60 static int cset;                       /* 0 or 1: which char set */
61 static int save_cset, save_csattr;     /* saved with cursor position */
62 static int rvideo;                     /* global reverse video flag */
63 static int cursor_on;                  /* cursor enabled flag */
64 static int reset_132;                  /* Flag ESC c resets to 80 cols */
65 static int use_bce;                    /* Use Background coloured erase */
66 static int blinker;                    /* When blinking is the cursor on ? */
67 static int vt52_mode;                  /* Is VT100+ in vt52 mode ? */
68
69 static unsigned long cset_attr[2];
70
71 /*
72  * Saved settings on the alternate screen.
73  */
74 static int alt_x, alt_y, alt_om, alt_wrap, alt_wnext, alt_ins, alt_cset;
75 static int alt_t, alt_b;
76 static int alt_which;
77
78 #define ARGS_MAX 32                    /* max # of esc sequence arguments */
79 #define ARG_DEFAULT 0                  /* if an arg isn't specified */
80 #define def(a,d) ( (a) == ARG_DEFAULT ? (d) : (a) )
81 static int esc_args[ARGS_MAX];
82 static int esc_nargs;
83 static int esc_query;
84 #define ANSI(x,y)       ((x)+((y)<<8))
85 #define ANSI_QUE(x)     ANSI(x,TRUE)
86
87 #define OSC_STR_MAX 2048
88 static int osc_strlen;
89 static char osc_string[OSC_STR_MAX+1];
90 static int osc_w;
91
92 static unsigned char *tabs;
93
94 static enum {
95     TOPLEVEL,
96     SEEN_ESC,
97     SEEN_CSI,
98     SEEN_OSC,
99     SEEN_OSC_W,
100
101     DO_CTRLS,
102
103     IGNORE_NEXT,
104     SET_GL, SET_GR,
105     SEEN_OSC_P,
106     OSC_STRING, OSC_MAYBE_ST,
107     SEEN_ESCHASH,
108     VT52_ESC,
109     VT52_Y1,
110     VT52_Y2
111 } termstate;
112
113 static enum {
114     NO_SELECTION, ABOUT_TO, DRAGGING, SELECTED
115 } selstate;
116 static enum {
117     SM_CHAR, SM_WORD, SM_LINE
118 } selmode;
119 static unsigned long *selstart, *selend, *selanchor;
120
121 static short wordness[256] = {
122     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 01 */
123     0,1,2,1,1,1,1,1,1,1,1,1,1,2,2,2, 2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1, /* 23 */
124     1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,2, /* 45 */
125     1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1, /* 67 */
126     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 89 */
127     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* AB */
128     2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2, /* CD */
129     2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2, /* EF */
130 };
131
132 static unsigned char sel_nl[] = SEL_NL;
133
134 /*
135  * Internal prototypes.
136  */
137 static void do_paint (Context, int);
138 static void erase_lots (int, int, int);
139 static void swap_screen (int);
140 static void update_sbar (void);
141 static void deselect (void);
142
143 /*
144  * Set up power-on settings for the terminal.
145  */
146 static void power_on(void) {
147     curs_x = curs_y = alt_x = alt_y = save_x = save_y = 0;
148     alt_t = marg_t = 0;
149     if (rows != -1)
150         alt_b = marg_b = rows - 1;
151     else
152         alt_b = marg_b = 0;
153     if (cols != -1) {
154         int i;
155         for (i = 0; i < cols; i++)
156             tabs[i] = (i % 8 == 0 ? TRUE : FALSE);
157     }
158     alt_om = dec_om = cfg.dec_om;
159     alt_wnext = wrapnext = alt_ins = insert = FALSE;
160     alt_wrap = wrap = cfg.wrap_mode;
161     alt_cset = cset = 0;
162     cset_attr[0] = cset_attr[1] = ATTR_ASCII;
163     rvideo = 0;
164     cursor_on = 1;
165     save_attr = curr_attr = ATTR_DEFAULT;
166     app_cursor_keys = cfg.app_cursor;
167     app_keypad_keys = cfg.app_keypad;
168     use_bce = 0;
169     erase_char = ERASE_CHAR;
170     alt_which = 0;
171     {
172         int i;
173         for (i = 0; i < 256; i++)
174             wordness[i] = cfg.wordness[i];
175     }
176     if (text) {
177         swap_screen (1);
178         erase_lots (FALSE, TRUE, TRUE);
179         swap_screen (0);
180         erase_lots (FALSE, TRUE, TRUE);
181     }
182 }
183
184 /*
185  * Force a screen update.
186  */
187 void term_update(void) {
188     Context ctx;
189     ctx = get_ctx();
190     if (ctx) {
191         if ( (seen_key_event && (unscroll_event & US_KEY)) ||
192              (seen_disp_event && (unscroll_event & US_DISP)) ) {
193             disptop = scrtop;
194             seen_disp_event = seen_key_event = 0;
195         }
196         do_paint (ctx, TRUE);
197         free_ctx (ctx);
198     }
199 }
200
201 /*
202  * Same as power_on(), but an external function.
203  */
204 void term_pwron(void) {
205     power_on();
206     fix_cpos;
207     disptop = scrtop;
208     deselect();
209     term_update();
210 }
211
212 /*
213  * Clear the scrollback.
214  */
215 void term_clrsb(void) {
216     disptop = sbtop = scrtop;
217     update_sbar();
218 }
219
220 /*
221  * Initialise the terminal.
222  */
223 void term_init(void) {
224     text = sbtop = scrtop = disptop = cpos = NULL;
225     disptext = wanttext = NULL;
226     tabs = NULL;
227     selspace = NULL;
228     deselect();
229     rows = cols = -1;
230     power_on();
231 }
232
233 /*
234  * Set up the terminal for a given size.
235  */
236 void term_size(int newrows, int newcols, int newsavelines) {
237     unsigned long *newtext, *newdisp, *newwant, *newalt;
238     int i, j, crows, ccols;
239
240     int save_alt_which = alt_which;
241
242     if (newrows == rows && newcols == cols && newsavelines == savelines)
243         return;                        /* nothing to do */
244
245     deselect();
246     swap_screen(0);
247
248     alt_t = marg_t = 0;
249     alt_b = marg_b = newrows - 1;
250
251     newtext = smalloc ((newrows+newsavelines)*(newcols+1)*TSIZE);
252     disptop = newtext + newsavelines*(newcols+1);
253     for (i=0; i<(newrows+newsavelines)*(newcols+1); i++)
254         newtext[i] = ERASE_CHAR;
255     if (rows != -1) {
256         crows = rows + (scrtop - sbtop) / (cols+1);
257         if (crows > newrows+newsavelines)
258             crows = newrows+newsavelines;
259         ccols = (cols < newcols ? cols : newcols);
260         for (i=0; i<crows; i++) {
261             int oldidx = (rows + savelines - crows + i) * (cols+1);
262             int newidx = (newrows + newsavelines - crows + i) * (newcols+1);
263             for (j=0; j<ccols; j++)
264                 newtext[newidx+j] = text[oldidx+j];
265             newtext[newidx+newcols] =
266                 (cols == newcols ? text[oldidx+cols] : 0);
267         }
268         sbtop = disptop - (crows - newrows) * (newcols+1);
269         if (sbtop > disptop)
270             sbtop = disptop;
271     } else
272         sbtop = disptop;
273     scrtop = disptop;
274     sfree (text);
275     text = newtext;
276
277     newdisp = smalloc (newrows*(newcols+1)*TSIZE);
278     for (i=0; i<newrows*(newcols+1); i++)
279         newdisp[i] = ATTR_INVALID;
280     sfree (disptext);
281     disptext = newdisp;
282
283     newwant = smalloc (newrows*(newcols+1)*TSIZE);
284     for (i=0; i<newrows*(newcols+1); i++)
285         newwant[i] = ATTR_INVALID;
286     sfree (wanttext);
287     wanttext = newwant;
288
289     newalt = smalloc (newrows*(newcols+1)*TSIZE);
290     for (i=0; i<newrows*(newcols+1); i++)
291         newalt[i] = erase_char;
292     sfree (alttext);
293     alttext = newalt;
294
295     sfree (selspace);
296     selspace = smalloc ( (newrows+newsavelines) * (newcols+sizeof(sel_nl)) );
297
298     tabs = srealloc (tabs, newcols*sizeof(*tabs));
299     {
300         int i;
301         for (i = (cols > 0 ? cols : 0); i < newcols; i++)
302             tabs[i] = (i % 8 == 0 ? TRUE : FALSE);
303     }
304
305     if (rows > 0)
306         curs_y += newrows - rows;
307     if (curs_y < 0)
308         curs_y = 0;
309     if (curs_y >= newrows)
310         curs_y = newrows-1;
311     if (curs_x >= newcols)
312         curs_x = newcols-1;
313     alt_x = alt_y = 0;
314     wrapnext = alt_wnext = FALSE;
315
316     rows = newrows;
317     cols = newcols;
318     savelines = newsavelines;
319     fix_cpos;
320
321     swap_screen(save_alt_which);
322
323     update_sbar();
324     term_update();
325 }
326
327 /*
328  * Swap screens.
329  */
330 static void swap_screen (int which) {
331     int t;
332     unsigned long tt;
333
334     if (which == alt_which)
335         return;
336
337     alt_which = which;
338
339     for (t=0; t<rows*(cols+1); t++) {
340         tt = scrtop[t]; scrtop[t] = alttext[t]; alttext[t] = tt;
341     }
342
343     t = curs_x; curs_x = alt_x; alt_x = t;
344     t = curs_y; curs_y = alt_y; alt_y = t;
345     t = marg_t; marg_t = alt_t; alt_t = t;
346     t = marg_b; marg_b = alt_b; alt_b = t;
347     t = dec_om; dec_om = alt_om; alt_om = t;
348     t = wrap; wrap = alt_wrap; alt_wrap = t;
349     t = wrapnext; wrapnext = alt_wnext; alt_wnext = t;
350     t = insert; insert = alt_ins; alt_ins = t;
351     t = cset; cset = alt_cset; alt_cset = t;
352
353     fix_cpos;
354 }
355
356 /*
357  * Retrieve a character from `inbuf'.
358  */
359 static int inbuf_getc(void) {
360     if (inbuf_head == inbuf_reap)
361         return -1;                     /* EOF */
362     else {
363         int n = inbuf_reap;
364         inbuf_reap = (inbuf_reap+1) & INBUF_MASK;
365         return inbuf[n];
366     }
367 }
368
369 /*
370  * Update the scroll bar.
371  */
372 static void update_sbar(void) {
373     int min;
374
375     min = (sbtop - text) / (cols+1);
376     set_sbar ((scrtop - text) / (cols+1) + rows - min,
377               (disptop - text) / (cols+1) - min,
378               rows);
379 }
380
381 /*
382  * Check whether the region bounded by the two pointers intersects
383  * the scroll region, and de-select the on-screen selection if so.
384  */
385 static void check_selection (unsigned long *from, unsigned long *to) {
386     if (from < selend && selstart < to)
387         deselect();
388 }
389
390 /*
391  * Scroll the screen. (`lines' is +ve for scrolling forward, -ve
392  * for backward.) `sb' is TRUE if the scrolling is permitted to
393  * affect the scrollback buffer.
394  */
395 static void scroll (int topline, int botline, int lines, int sb) {
396     unsigned long *scroll_top;
397     int scroll_size, size, i;
398
399     scroll_top = scrtop + topline*(cols+1);
400     size = (lines < 0 ? -lines : lines) * (cols+1);
401     scroll_size = (botline - topline + 1) * (cols+1) - size;
402
403     if (lines > 0 && topline == 0 && alt_which == 0 && sb) {
404         /*
405          * Since we're going to scroll the top line and we're on the 
406          * scrolling screen let's also affect the scrollback buffer.
407          */
408         sbtop -= lines * (cols+1);
409         if (sbtop < text)
410             sbtop = text;
411         scroll_size += scroll_top - sbtop;
412         scroll_top = sbtop;
413         update_sbar();
414     }
415
416     if (scroll_size < 0) {
417         size += scroll_size;
418         scroll_size = 0;
419     }
420
421     if (lines > 0) {
422         if (scroll_size)
423             memmove (scroll_top, scroll_top + size, scroll_size*TSIZE);
424         for (i = 0; i < size; i++)
425             scroll_top[i+scroll_size] = erase_char;
426         if (selstart > scroll_top &&
427             selstart < scroll_top + size + scroll_size) {
428             selstart -= size;
429             if (selstart < scroll_top)
430                 selstart = scroll_top;
431         }
432         if (selend > scroll_top &&
433             selend < scroll_top + size + scroll_size) {
434             selend -= size;
435             if (selend < scroll_top)
436                 selend = scroll_top;
437         }
438     } else {
439         if (scroll_size)
440             memmove (scroll_top + size, scroll_top, scroll_size*TSIZE);
441         for (i = 0; i < size; i++)
442             scroll_top[i] = erase_char;
443         if (selstart > scroll_top &&
444             selstart < scroll_top + size + scroll_size) {
445             selstart += size;
446             if (selstart > scroll_top + size + scroll_size)
447                 selstart = scroll_top + size + scroll_size;
448         }
449         if (selend > scroll_top &&
450             selend < scroll_top + size + scroll_size) {
451             selend += size;
452             if (selend > scroll_top + size + scroll_size)
453                 selend = scroll_top + size + scroll_size;
454         }
455     }
456 }
457
458 /*
459  * Move the cursor to a given position, clipping at boundaries. We
460  * may or may not want to clip at the scroll margin: marg_clip is 0
461  * not to, 1 to disallow _passing_ the margins, and 2 to disallow
462  * even _being_ outside the margins.
463  */
464 static void move (int x, int y, int marg_clip) {
465     if (x < 0)
466         x = 0;
467     if (x >= cols)
468         x = cols-1;
469     if (marg_clip) {
470         if ((curs_y >= marg_t || marg_clip == 2) && y < marg_t)
471             y = marg_t;
472         if ((curs_y <= marg_b || marg_clip == 2) && y > marg_b)
473             y = marg_b;
474     }
475     if (y < 0)
476         y = 0;
477     if (y >= rows)
478         y = rows-1;
479     curs_x = x;
480     curs_y = y;
481     fix_cpos;
482     wrapnext = FALSE;
483 }
484
485 /*
486  * Save or restore the cursor and SGR mode.
487  */
488 static void save_cursor(int save) {
489     if (save) {
490         save_x = curs_x;
491         save_y = curs_y;
492         save_attr = curr_attr;
493         save_cset = cset;
494         save_csattr = cset_attr[cset];
495     } else {
496         curs_x = save_x;
497         curs_y = save_y;
498         /* Make sure the window hasn't shrunk since the save */
499         if (curs_x >= cols) curs_x = cols-1;
500         if (curs_y >= rows) curs_y = rows-1;
501         curr_attr = save_attr;
502         cset = save_cset;
503         cset_attr[cset] = save_csattr;
504         fix_cpos;
505         if (use_bce) erase_char = (' ' |(curr_attr&(ATTR_FGMASK|ATTR_BGMASK)));
506     }
507 }
508
509 /*
510  * Erase a large portion of the screen: the whole screen, or the
511  * whole line, or parts thereof.
512  */
513 static void erase_lots (int line_only, int from_begin, int to_end) {
514     unsigned long *startpos, *endpos;
515
516     if (line_only) {
517         startpos = cpos - curs_x;
518         endpos = startpos + cols+1;
519     } else {
520         startpos = scrtop;
521         endpos = startpos + rows * (cols+1);
522     }
523     if (!from_begin)
524         startpos = cpos;
525     if (!to_end)
526         endpos = cpos+1;
527     check_selection (startpos, endpos);
528
529     /* Clear screen also forces a full window redraw, just in case. */
530     if (startpos == scrtop && endpos == scrtop + rows * (cols+1))
531        term_invalidate();
532
533     while (startpos < endpos)
534         *startpos++ = erase_char;
535 }
536
537 /*
538  * Insert or delete characters within the current line. n is +ve if
539  * insertion is desired, and -ve for deletion.
540  */
541 static void insch (int n) {
542     int dir = (n < 0 ? -1 : +1);
543     int m;
544
545     n = (n < 0 ? -n : n);
546     if (n > cols - curs_x)
547         n = cols - curs_x;
548     m = cols - curs_x - n;
549     check_selection (cpos, cpos+n);
550     if (dir < 0) {
551         memmove (cpos, cpos+n, m*TSIZE);
552         while (n--)
553             cpos[m++] = erase_char;
554     } else {
555         memmove (cpos+n, cpos, m*TSIZE);
556         while (n--)
557             cpos[n] = erase_char;
558     }
559 }
560
561 /*
562  * Toggle terminal mode `mode' to state `state'. (`query' indicates
563  * whether the mode is a DEC private one or a normal one.)
564  */
565 static void toggle_mode (int mode, int query, int state) {
566     if (query) switch (mode) {
567       case 1:                          /* application cursor keys */
568         app_cursor_keys = state;
569         break;
570       case 2:                          /* VT52 mode */
571         vt52_mode = !state;
572         break;
573       case 3:                          /* 80/132 columns */
574         deselect();
575         request_resize (state ? 132 : 80, rows, 1);
576         reset_132 = state;
577         break;
578       case 5:                          /* reverse video */
579         rvideo = state;
580         seen_disp_event = TRUE;
581         if (state) term_update();
582         break;
583       case 6:                          /* DEC origin mode */
584         dec_om = state;
585         break;
586       case 7:                          /* auto wrap */
587         wrap = state;
588         break;
589       case 25:                         /* enable/disable cursor */
590         compatibility(VT220);
591         cursor_on = state;
592         seen_disp_event = TRUE;
593         break;
594       case 47:                         /* alternate screen */
595         compatibility(OTHER);
596         deselect();
597         swap_screen (state);
598         disptop = scrtop;
599         break;
600     } else switch (mode) {
601       case 4:                          /* set insert mode */
602         compatibility(VT102);
603         insert = state;
604         break;
605       case 12:                         /* set echo mode */
606         /* 
607          * This may be very good in smcup and rmcup (or smkx & rmkx) if you
608          * have a long RTT and the telnet client/daemon doesn't understand
609          * linemode.
610          *
611          * DONT send TS_RECHO/TS_LECHO; the telnet daemon tries to fix the
612          * tty and _really_ confuses some programs.
613          */
614         compatibility(VT220);
615         ldisc = (state? &ldisc_simple : &ldisc_term);
616         break;
617     }
618 }
619
620 /*
621  * Process an OSC sequence: set window title or icon name.
622  */
623 static void do_osc(void) {
624     if (osc_w) {
625         while (osc_strlen--)
626             wordness[(unsigned char)osc_string[osc_strlen]] = esc_args[0];
627     } else {
628         osc_string[osc_strlen] = '\0';
629         switch (esc_args[0]) {
630           case 0:
631           case 1:
632             set_icon (osc_string);
633             if (esc_args[0] == 1)
634                 break;
635             /* fall through: parameter 0 means set both */
636           case 2:
637           case 21:
638             set_title (osc_string);
639             break;
640         }
641     }
642 }
643
644 /*
645  * Remove everything currently in `inbuf' and stick it up on the
646  * in-memory display. There's a big state machine in here to
647  * process escape sequences...
648  */
649 void term_out(void) {
650     int c;
651
652     while ( (c = inbuf_getc()) != -1) {
653         /*
654          * Optionally log the session traffic to a file. Useful for
655          * debugging and possibly also useful for actual logging.
656          */
657         if (logfile) {
658             static FILE *fp = NULL;
659             if (!fp) fp = fopen(logfile, "wb");
660             if (fp) fputc (c, fp);
661         }
662         /* Note only VT220+ are 8-bit VT102 is seven bit, it shouldn't even
663          * be able to display 8-bit characters, but I'll let that go 'cause
664          * of i18n.
665          */
666         if( (c&0x60) == 0 && termstate < DO_CTRLS &&
667             ( (c&0x80) == 0 || has_compat(VT220))) {
668             switch (c) {
669               case '\005':             /* terminal type query */
670                 /* Strictly speaking this is VT100 but a VT100 defaults to
671                  * no response. Other terminals respond at their option.
672                  *
673                  * Don't put a CR in the default string as this tends to
674                  * upset some weird software.
675                  *
676                  * An xterm returns "xterm" (5 characters)
677                  */
678                 compatibility(OTHER);
679                 ldisc->send ("PuTTY", 5);
680                 break;
681               case '\007':
682                 if(cfg.beep) beep();
683                 disptop = scrtop;
684                 break;
685               case '\b':
686                 if (curs_x == 0 && curs_y > 0)
687                     curs_x = cols-1, curs_y--;
688                 else if (wrapnext)
689                     wrapnext = FALSE;
690                 else
691                     curs_x--;
692                 fix_cpos;
693                 seen_disp_event = TRUE;
694                 break;
695               case '\016':
696                 compatibility(VT100);
697                 cset = 1;
698                 break;
699               case '\017':
700                 compatibility(VT100);
701                 cset = 0;
702                 break;
703               case '\033':
704                 if (vt52_mode) 
705                    termstate = VT52_ESC;
706                 else {
707                     compatibility(ANSIMIN);
708                     termstate = SEEN_ESC;
709                 }
710                 break;
711               case 0233:
712                 compatibility(VT220);
713                 termstate = SEEN_CSI;
714                 esc_nargs = 1;
715                 esc_args[0] = ARG_DEFAULT;
716                 esc_query = FALSE;
717                 break;
718               case 0235:
719                 compatibility(VT220);
720                 termstate = SEEN_OSC;
721                 esc_args[0] = 0;
722                 break;
723               case '\r':
724                 curs_x = 0;
725                 wrapnext = FALSE;
726                 fix_cpos;
727                 seen_disp_event = TRUE;
728                 break;
729               case '\013':
730               case '\014':
731                 compatibility(VT100);
732               case '\n':
733                 if (curs_y == marg_b)
734                     scroll (marg_t, marg_b, 1, TRUE);
735                 else if (curs_y < rows-1)
736                     curs_y++;
737                 if (cfg.lfhascr)
738                     curs_x = 0;
739                 fix_cpos;
740                 wrapnext = FALSE;
741                 seen_disp_event = 1;
742                 break;
743               case '\t':
744                 do {
745                     curs_x++;
746                 } while (curs_x < cols-1 && !tabs[curs_x]);
747                 if (curs_x >= cols)
748                     curs_x = cols-1;
749                 {
750                     unsigned long *old_cpos = cpos;
751                     fix_cpos;
752                     check_selection (old_cpos, cpos);
753                 }
754                 seen_disp_event = TRUE;
755                 break;
756             }
757         }
758         else switch (termstate) {
759           case TOPLEVEL:
760           /* Only graphic characters get this far, ctrls are stripped above */
761             if (wrapnext) {
762                 cpos[1] = ATTR_WRAPPED;
763                 if (curs_y == marg_b)
764                     scroll (marg_t, marg_b, 1, TRUE);
765                 else if (curs_y < rows-1)
766                     curs_y++;
767                 curs_x = 0;
768                 fix_cpos;
769                 wrapnext = FALSE;
770             }
771             if (insert)
772                 insch (1);
773             if (selstate != NO_SELECTION)
774                 check_selection (cpos, cpos+1);
775             switch (cset_attr[cset]) {
776                 /* Linedraw characters are different from 'ESC ( B' only 
777                  * for a small range, for ones outside that range make sure 
778                  * we use the same font as well as the same encoding.
779                  */
780             case ATTR_LINEDRW:
781                 if (c<0x60 || c>0x7F)
782                     *cpos++ = xlat_tty2scr((unsigned char)c) | curr_attr |
783                               ATTR_ASCII;
784                 else
785                     *cpos++ = ((unsigned char)c) | curr_attr | ATTR_LINEDRW;
786                 break;
787             default:
788                 *cpos++ = xlat_tty2scr((unsigned char)c) | curr_attr |
789                     (c <= 0x7F ? cset_attr[cset] : ATTR_ASCII);
790                 break;
791             }
792             curs_x++;
793             if (curs_x == cols) {
794                 cpos--;
795                 curs_x--;
796                 wrapnext = wrap;
797             }
798             seen_disp_event = 1;
799             break;
800
801           case IGNORE_NEXT:
802             termstate = TOPLEVEL;
803             break;
804           case OSC_MAYBE_ST:
805             /*
806              * This state is virtually identical to SEEN_ESC, with the
807              * exception that we have an OSC sequence in the pipeline,
808              * and _if_ we see a backslash, we process it.
809              */
810             if (c == '\\') {
811                 do_osc();
812                 termstate = TOPLEVEL;
813                 break;
814             }
815             /* else fall through */
816           case SEEN_ESC:
817             termstate = TOPLEVEL;
818             switch (c) {
819               case ' ':                /* some weird sequence? */
820                 compatibility(VT220);
821                 termstate = IGNORE_NEXT;
822                 break;
823               case '[':                /* enter CSI mode */
824                 termstate = SEEN_CSI;
825                 esc_nargs = 1;
826                 esc_args[0] = ARG_DEFAULT;
827                 esc_query = FALSE;
828                 break;
829               case ']':                /* xterm escape sequences */
830                 /* Compatibility is nasty here, xterm, linux, decterm yuk! */
831                 compatibility(OTHER);
832                 termstate = SEEN_OSC;
833                 esc_args[0] = 0;
834                 break;
835               case '(':                /* should set GL */
836                 compatibility(VT100);
837                 termstate = SET_GL;
838                 break;
839               case ')':                /* should set GR */
840                 compatibility(VT100);
841                 termstate = SET_GR;
842                 break;
843               case '7':                /* save cursor */
844                 compatibility(VT100);
845                 save_cursor (TRUE);
846                 break;
847               case '8':                /* restore cursor */
848                 compatibility(VT100);
849                 save_cursor (FALSE);
850                 seen_disp_event = TRUE;
851                 break;
852               case '=':
853                 compatibility(VT100);
854                 app_keypad_keys = TRUE;
855                 break;
856               case '>':
857                 compatibility(VT100);
858                 app_keypad_keys = FALSE;
859                 break;
860               case 'D':                /* exactly equivalent to LF */
861                 compatibility(VT100);
862                 if (curs_y == marg_b)
863                     scroll (marg_t, marg_b, 1, TRUE);
864                 else if (curs_y < rows-1)
865                     curs_y++;
866                 fix_cpos;
867                 wrapnext = FALSE;
868                 seen_disp_event = TRUE;
869                 break;
870               case 'E':                /* exactly equivalent to CR-LF */
871                 compatibility(VT100);
872                 curs_x = 0;
873                 wrapnext = FALSE;
874                 if (curs_y == marg_b)
875                     scroll (marg_t, marg_b, 1, TRUE);
876                 else if (curs_y < rows-1)
877                     curs_y++;
878                 fix_cpos;
879                 wrapnext = FALSE;
880                 seen_disp_event = TRUE;
881                 break;
882               case 'M':                /* reverse index - backwards LF */
883                 compatibility(VT100);
884                 if (curs_y == marg_t)
885                     scroll (marg_t, marg_b, -1, TRUE);
886                 else if (curs_y > 0)
887                     curs_y--;
888                 fix_cpos;
889                 wrapnext = FALSE;
890                 seen_disp_event = TRUE;
891                 break;
892               case 'Z':                /* terminal type query */
893                 compatibility(VT100);
894                 ldisc->send ("\033[?6c", 5);
895                 break;
896               case 'c':                /* restore power-on settings */
897                 compatibility(VT100);
898                 power_on();
899                 if (reset_132) {
900                     request_resize (80, rows, 1);
901                     reset_132 = 0;
902                 }
903                 fix_cpos;
904                 disptop = scrtop;
905                 seen_disp_event = TRUE;
906                 break;
907               case '#':                /* ESC # 8 fills screen with Es :-) */
908                 compatibility(VT100);
909                 termstate = SEEN_ESCHASH;
910                 break;
911               case 'H':                /* set a tab */
912                 compatibility(VT100);
913                 tabs[curs_x] = TRUE;
914                 break;
915             }
916             break;
917           case SEEN_CSI:
918             termstate = TOPLEVEL;      /* default */
919             if( isdigit(c) )
920             {
921                 if (esc_nargs <= ARGS_MAX) {
922                     if (esc_args[esc_nargs-1] == ARG_DEFAULT)
923                         esc_args[esc_nargs-1] = 0;
924                     esc_args[esc_nargs-1] =
925                         10 * esc_args[esc_nargs-1] + c - '0';
926                 }
927                 termstate = SEEN_CSI;
928             }
929             else if( c == ';' )
930             {
931                 if (++esc_nargs <= ARGS_MAX)
932                     esc_args[esc_nargs-1] = ARG_DEFAULT;
933                 termstate = SEEN_CSI;
934             }
935             else if( c < '@' )
936             {
937                 if( esc_query )     esc_query = -1;
938                 else if( c == '?' ) esc_query = TRUE;
939                 else                esc_query = c;
940                 termstate = SEEN_CSI;
941             }
942             else switch (ANSI(c,esc_query)) {
943               case 'A':                /* move up N lines */
944                 move (curs_x, curs_y - def(esc_args[0], 1), 1);
945                 seen_disp_event = TRUE;
946                 break;
947               case 'e':      /* move down N lines */
948                 compatibility(ANSI);
949               case 'B':
950                 move (curs_x, curs_y + def(esc_args[0], 1), 1);
951                 seen_disp_event = TRUE;
952                 break;
953               case 'a':      /* move right N cols */
954                 compatibility(ANSI);
955               case 'C':
956                 move (curs_x + def(esc_args[0], 1), curs_y, 1);
957                 seen_disp_event = TRUE;
958                 break;
959               case 'D':                /* move left N cols */
960                 move (curs_x - def(esc_args[0], 1), curs_y, 1);
961                 seen_disp_event = TRUE;
962                 break;
963               case 'E':                /* move down N lines and CR */
964                 compatibility(ANSI);
965                 move (0, curs_y + def(esc_args[0], 1), 1);
966                 seen_disp_event = TRUE;
967                 break;
968               case 'F':                /* move up N lines and CR */
969                 compatibility(ANSI);
970                 move (0, curs_y - def(esc_args[0], 1), 1);
971                 seen_disp_event = TRUE;
972                 break;
973               case 'G': case '`':      /* set horizontal posn */
974                 compatibility(ANSI);
975                 move (def(esc_args[0], 1) - 1, curs_y, 0);
976                 seen_disp_event = TRUE;
977                 break;
978               case 'd':                /* set vertical posn */
979                 compatibility(ANSI);
980                 move (curs_x, (dec_om ? marg_t : 0) + def(esc_args[0], 1) - 1,
981                       (dec_om ? 2 : 0));
982                 seen_disp_event = TRUE;
983                 break;
984               case 'H': case 'f':      /* set horz and vert posns at once */
985                 if (esc_nargs < 2)
986                     esc_args[1] = ARG_DEFAULT;
987                 move (def(esc_args[1], 1) - 1,
988                       (dec_om ? marg_t : 0) + def(esc_args[0], 1) - 1,
989                       (dec_om ? 2 : 0));
990                 seen_disp_event = TRUE;
991                 break;
992               case 'J':                /* erase screen or parts of it */
993                 {
994                     unsigned int i = def(esc_args[0], 0) + 1;
995                     if (i > 3)
996                         i = 0;
997                     erase_lots(FALSE, !!(i & 2), !!(i & 1));
998                 }
999                 disptop = scrtop;
1000                 seen_disp_event = TRUE;
1001                 break;
1002               case 'K':                /* erase line or parts of it */
1003                 {
1004                     unsigned int i = def(esc_args[0], 0) + 1;
1005                     if (i > 3)
1006                         i = 0;
1007                     erase_lots(TRUE, !!(i & 2), !!(i & 1));
1008                 }
1009                 seen_disp_event = TRUE;
1010                 break;
1011               case 'L':                /* insert lines */
1012                 compatibility(VT102);
1013                 if (curs_y <= marg_b)
1014                     scroll (curs_y, marg_b, -def(esc_args[0], 1), FALSE);
1015                 seen_disp_event = TRUE;
1016                 break;
1017               case 'M':                /* delete lines */
1018                 compatibility(VT102);
1019                 if (curs_y <= marg_b)
1020                     scroll (curs_y, marg_b, def(esc_args[0], 1), TRUE);
1021                 seen_disp_event = TRUE;
1022                 break;
1023               case '@':                /* insert chars */
1024                 /* XXX VTTEST says this is vt220, vt510 manual says vt102 */
1025                 compatibility(VT102);   
1026                 insch (def(esc_args[0], 1));
1027                 seen_disp_event = TRUE;
1028                 break;
1029               case 'P':                /* delete chars */
1030                 compatibility(VT102);   
1031                 insch (-def(esc_args[0], 1));
1032                 seen_disp_event = TRUE;
1033                 break;
1034               case 'c':                /* terminal type query */
1035                 compatibility(VT100);
1036                 /* This is the response for a VT102 */
1037                 ldisc->send ("\033[?6c", 5);
1038                 break;
1039               case 'n':                /* cursor position query */
1040                 if (esc_args[0] == 6) {
1041                     /* Wonder of wonders ANSI.SYS has this!! */
1042                     char buf[32];
1043                     sprintf (buf, "\033[%d;%dR", curs_y + 1, curs_x + 1);
1044                     ldisc->send (buf, strlen(buf));
1045                 }
1046                 else if (esc_args[0] == 5) {
1047                     /* Are we working ... well I suppose so :-) */
1048                     /* But ANSI.SYS doesn't say it's working :-) :-) */
1049                     compatibility(VT100);
1050                     ldisc->send ("\033[0n", 4);
1051                 }
1052                 break;
1053               case 'h':                /* toggle modes to high */
1054               case ANSI_QUE('h'):
1055                 compatibility(VT100);
1056                 {
1057                     int i;
1058                     for (i=0; i<esc_nargs; i++)
1059                         toggle_mode (esc_args[i], esc_query, TRUE);
1060                 }
1061                 break;
1062               case 'l':                /* toggle modes to low */
1063               case ANSI_QUE('l'):
1064                 compatibility(VT100);
1065                 {
1066                     int i;
1067                     for (i=0; i<esc_nargs; i++)
1068                         toggle_mode (esc_args[i], esc_query, FALSE);
1069                 }
1070                 break;
1071               case 'g':                /* clear tabs */
1072                 compatibility(VT100);
1073                 if (esc_nargs == 1) {
1074                     if (esc_args[0] == 0) {
1075                         tabs[curs_x] = FALSE;
1076                     } else if (esc_args[0] == 3) {
1077                         int i;
1078                         for (i = 0; i < cols; i++)
1079                             tabs[i] = FALSE;
1080                     }
1081                 }
1082                 break;
1083               case 'r':                /* set scroll margins */
1084                 compatibility(VT100);
1085                 if (esc_nargs <= 2) {
1086                     int top, bot;
1087                     /* VTTEST Bug 9 if the first arg is default _or_ zero
1088                      * this is a full screen region irrespective of 2nd arg.
1089                      */
1090                     if (esc_args[0] <= 0) {
1091                        top=0;
1092                        bot=rows-1;
1093                     } else {
1094                        top = def(esc_args[0], 1) - 1;
1095                        bot = (esc_nargs <= 1 || esc_args[1] == 0 ? rows :
1096                               def(esc_args[1], rows)) - 1;
1097                     }
1098                     if (bot >= rows)
1099                         bot = rows-1;
1100                     if (top <= bot) {
1101                         marg_t = top;
1102                         marg_b = bot;
1103                         curs_x = 0;
1104                         /*
1105                          * I used to think the cursor should be
1106                          * placed at the top of the newly marginned
1107                          * area. Apparently not: VMS TPU falls over
1108                          * if so.
1109                          *
1110                          * Well actually it should for Origin mode - RDB
1111                          */
1112                         curs_y = (dec_om ? marg_t : 0);
1113                         fix_cpos;
1114                         seen_disp_event = TRUE;
1115                     }
1116                 }
1117                 break;
1118               case 'm':                /* set graphics rendition */
1119                 {
1120                     /* 
1121                      * A VT100 without the AVO only had one attribute, either
1122                      * underline or reverse video depending on the cursor type,
1123                      * this was selected by CSI 7m.
1124                      *
1125                      * case 2:
1126                      *  This is DIM on the VT100-AVO and VT102
1127                      * case 5:
1128                      *  This is BLINK on the VT100-AVO and VT102+
1129                      * case 8:
1130                      *  This is INVIS on the VT100-AVO and VT102
1131                      * case 21:
1132                      *  This like 22 disables BOLD, DIM and INVIS
1133                      *
1134                      * The ANSI colours appear on any terminal that has colour
1135                      * (obviously) but the interaction between sgr0 and the
1136                      * colours varies but is usually related to the background
1137                      * colour erase item.
1138                      * The interaction between colour attributes and the mono
1139                      * ones is also very implementation dependent.
1140                      *
1141                      * The 39 and 49 attributes are likely to be unimplemented.
1142                      */
1143                     int i;
1144                     for (i=0; i<esc_nargs; i++) {
1145                         switch (def(esc_args[i], 0)) {
1146                           case 0:      /* restore defaults */
1147                             curr_attr = ATTR_DEFAULT; break;
1148                           case 1:      /* enable bold */
1149                             compatibility(VT100AVO);
1150                             curr_attr |= ATTR_BOLD; break;
1151                           case 21:     /* (enable double underline) */
1152                             compatibility(OTHER);
1153                           case 4:      /* enable underline */
1154                             compatibility(VT100AVO);
1155                             curr_attr |= ATTR_UNDER; break;
1156                           case 5:      /* enable blink */
1157                             compatibility(VT100AVO);
1158                             curr_attr |= ATTR_BLINK; break;
1159                           case 7:      /* enable reverse video */
1160                             curr_attr |= ATTR_REVERSE; break;
1161                           case 22:     /* disable bold */
1162                             compatibility(VT220);
1163                             curr_attr &= ~ATTR_BOLD; break;
1164                           case 24:     /* disable underline */
1165                             compatibility(VT220);
1166                             curr_attr &= ~ATTR_UNDER; break;
1167                           case 25:     /* disable blink */
1168                             compatibility(VT220);
1169                             curr_attr &= ~ATTR_BLINK; break;
1170                           case 27:     /* disable reverse video */
1171                             compatibility(VT220);
1172                             curr_attr &= ~ATTR_REVERSE; break;
1173                           case 30: case 31: case 32: case 33:
1174                           case 34: case 35: case 36: case 37:
1175                             /* foreground */
1176                             curr_attr &= ~ATTR_FGMASK;
1177                             curr_attr |= (esc_args[i] - 30) << ATTR_FGSHIFT;
1178                             break;
1179                           case 39:     /* default-foreground */
1180                             curr_attr &= ~ATTR_FGMASK;
1181                             curr_attr |= ATTR_DEFFG;
1182                             break;
1183                           case 40: case 41: case 42: case 43:
1184                           case 44: case 45: case 46: case 47:
1185                             /* background */
1186                             curr_attr &= ~ATTR_BGMASK;
1187                             curr_attr |= (esc_args[i] - 40) << ATTR_BGSHIFT;
1188                             break;
1189                           case 49:     /* default-background */
1190                             curr_attr &= ~ATTR_BGMASK;
1191                             curr_attr |= ATTR_DEFBG;
1192                             break;
1193                         }
1194                     }
1195                     if (use_bce) 
1196                        erase_char = (' '|(curr_attr&(ATTR_FGMASK|ATTR_BGMASK)));
1197                 }
1198                 break;
1199               case 's':                /* save cursor */
1200                 save_cursor (TRUE);
1201                 break;
1202               case 'u':                /* restore cursor */
1203                 save_cursor (FALSE);
1204                 seen_disp_event = TRUE;
1205                 break;
1206               case 't':                /* set page size - ie window height */
1207                 /*
1208                  * VT340/VT420 sequence DECSLPP, DEC only allows values
1209                  *  24/25/36/48/72/144 other emulators (eg dtterm) use
1210                  * illegal values (eg first arg 1..9) for window changing 
1211                  * and reports.
1212                  */
1213                 compatibility(VT340TEXT);
1214                 if (esc_nargs<=1 && (esc_args[0]<1 || esc_args[0]>=24)) {
1215                     unsigned int newrows = def(esc_args[0], 24);
1216                     /* Hack: prevent big-resize DoS attack. */
1217                     if (newrows > max(512, cfg.height))
1218                         newrows = max(512, cfg.height);
1219                     request_resize (cols, newrows, 0);
1220                     deselect();
1221                 }
1222                 break;
1223               case ANSI('|', '*'):
1224                 /* VT420 sequence DECSNLS
1225                  * Set number of lines on screen
1226                  * VT420 uses VGA like hardware and can support any size in
1227                  * reasonable range (24..49 AIUI) with no default specified.
1228                  */
1229                 compatibility(VT420);
1230                 if (esc_nargs==1 && esc_args[0]>=24) {
1231                     unsigned int newrows = def(esc_args[0], cfg.height);
1232                     /* Hack: prevent big-resize DoS attack. */
1233                     if (newrows > max(512, cfg.height))
1234                         newrows = max(512, cfg.height);
1235                     request_resize (cols, newrows, 0);
1236                     deselect();
1237                 }
1238                 break;
1239               case ANSI('|', '$'):
1240                 /* VT340/VT420 sequence DECSCPP
1241                  * Set number of columns per page
1242                  * Docs imply range is only 80 or 132, but I'll allow any.
1243                  */
1244                 compatibility(VT340TEXT);
1245                 if (esc_nargs<=1) {
1246                     unsigned int newcols = def(esc_args[0], cfg.width);
1247                     /* Hack: prevent big-resize DoS attack. */
1248                     if (newcols > max(512, cfg.width))
1249                         newcols = max(512, cfg.width);
1250                     request_resize (newcols, rows, 0);
1251                     deselect();
1252                 }
1253                 break;
1254               case 'X':                /* write N spaces w/o moving cursor */
1255                 /* XXX VTTEST says this is vt220, vt510 manual says vt100 */
1256                 compatibility(VT100);
1257                 {
1258                     int n = def(esc_args[0], 1);
1259                     unsigned long *p = cpos;
1260                     if (n > cols - curs_x)
1261                         n = cols - curs_x;
1262                     check_selection (cpos, cpos+n);
1263                     while (n--)
1264                         *p++ = erase_char;
1265                     seen_disp_event = TRUE;
1266                 }
1267                 break;
1268               case 'x':                /* report terminal characteristics */
1269                 compatibility(VT100);
1270                 {
1271                     char buf[32];
1272                     int i = def(esc_args[0], 0);
1273                     if (i == 0 || i == 1) {
1274                         strcpy (buf, "\033[2;1;1;112;112;1;0x");
1275                         buf[2] += i;
1276                         ldisc->send (buf, 20);
1277                     }
1278                 }
1279                 break;
1280               case ANSI('L','='):
1281                 compatibility(OTHER);
1282                 use_bce = (esc_args[0]<=0);
1283                 erase_char = ERASE_CHAR;
1284                 if (use_bce)
1285                     erase_char = (' '|(curr_attr&(ATTR_FGMASK|ATTR_BGMASK)));
1286                 break;
1287               case ANSI('p','"'):
1288                 /* Allow the host to make this emulator a 'perfect' VT102.
1289                  * This first appeared in the VT220, but we do need to get 
1290                  * back to PuTTY mode so I won't check it.
1291                  *
1292                  * The arg == 60 is a PuTTY extension.
1293                  * The 2nd arg, 8bit vs 7bit is not obeyed.
1294                  *
1295                  * Setting VT102 mode should also change the Fkeys to
1296                  * generate PF* codes as a real VT102 has no Fkeys.
1297                  * The VT220 does this, F11..F13 become ESC,BS,LF other Fkeys
1298                  * send nothing.
1299                  *
1300                  * Note ESC c will NOT change this!
1301                  */
1302
1303                 if (esc_args[0] == 61)      compatibility_level = TM_VT102;
1304                 else if (esc_args[0] == 60) compatibility_level = TM_ANSIMIN;
1305                 else                        compatibility_level = TM_PUTTY;
1306                 break;
1307             }
1308             break;
1309           case SET_GL:
1310           case SET_GR:
1311             /* VT100 only here, checked above */
1312             switch (c) {
1313               case 'A':
1314                 cset_attr[termstate == SET_GL ? 0 : 1] = ATTR_GBCHR;
1315                 break;
1316               case '0':
1317                 cset_attr[termstate == SET_GL ? 0 : 1] = ATTR_LINEDRW;
1318                 break;
1319               case 'B':
1320               default:                 /* specifically, 'B' */
1321                 cset_attr[termstate == SET_GL ? 0 : 1] = ATTR_ASCII;
1322                 break;
1323             }
1324             if( !has_compat(VT220) || c != '%' )
1325                 termstate = TOPLEVEL;
1326             break;
1327           case SEEN_OSC:
1328             osc_w = FALSE;
1329             switch (c) {
1330               case 'P':                /* Linux palette sequence */
1331                 termstate = SEEN_OSC_P;
1332                 osc_strlen = 0;
1333                 break;
1334               case 'R':                /* Linux palette reset */
1335                 palette_reset();
1336                 term_invalidate();
1337                 termstate = TOPLEVEL;
1338                 break;
1339               case 'W':                /* word-set */
1340                 termstate = SEEN_OSC_W;
1341                 osc_w = TRUE;
1342                 break;
1343               case '0': case '1': case '2': case '3': case '4':
1344               case '5': case '6': case '7': case '8': case '9':
1345                 esc_args[0] = 10 * esc_args[0] + c - '0';
1346                 break;
1347               case 'L':
1348                 /*
1349                  * Grotty hack to support xterm and DECterm title
1350                  * sequences concurrently.
1351                  */
1352                 if (esc_args[0] == 2) {
1353                     esc_args[0] = 1;
1354                     break;
1355                 }
1356                 /* else fall through */
1357               default:
1358                 termstate = OSC_STRING;
1359                 osc_strlen = 0;
1360             }
1361             break;
1362           case OSC_STRING:
1363             /*
1364              * This OSC stuff is EVIL. It takes just one character to get into
1365              * sysline mode and it's not initially obvious how to get out.
1366              * So I've added CR and LF as string aborts.
1367              * This shouldn't effect compatibility as I believe embedded 
1368              * control characters are supposed to be interpreted (maybe?) 
1369              * and they don't display anything useful anyway.
1370              *
1371              * -- RDB
1372              */
1373             if (c == '\n' || c == '\r') {
1374                 termstate = TOPLEVEL;
1375             } else if (c == 0234 || c == '\007' ) {
1376                 /*
1377                  * These characters terminate the string; ST and BEL
1378                  * terminate the sequence and trigger instant
1379                  * processing of it, whereas ESC goes back to SEEN_ESC
1380                  * mode unless it is followed by \, in which case it is
1381                  * synonymous with ST in the first place.
1382                  */
1383                 do_osc();
1384                 termstate = TOPLEVEL;
1385             } else if (c == '\033')
1386                     termstate = OSC_MAYBE_ST;
1387             else if (osc_strlen < OSC_STR_MAX)
1388                 osc_string[osc_strlen++] = c;
1389             break;
1390           case SEEN_OSC_P:
1391             {
1392                 int max = (osc_strlen == 0 ? 21 : 16);
1393                 int val;
1394                 if (c >= '0' && c <= '9')
1395                     val = c - '0';
1396                 else if (c >= 'A' && c <= 'A'+max-10)
1397                     val = c - 'A' + 10;
1398                 else if (c >= 'a' && c <= 'a'+max-10)
1399                     val = c - 'a' + 10;
1400                 else
1401                     termstate = TOPLEVEL;
1402                 osc_string[osc_strlen++] = val;
1403                 if (osc_strlen >= 7) {
1404                     palette_set (osc_string[0],
1405                                  osc_string[1] * 16 + osc_string[2],
1406                                  osc_string[3] * 16 + osc_string[4],
1407                                  osc_string[5] * 16 + osc_string[6]);
1408                     term_invalidate();
1409                     termstate = TOPLEVEL;
1410                 }
1411             }
1412             break;
1413           case SEEN_OSC_W:
1414             switch (c) {
1415               case '0': case '1': case '2': case '3': case '4':
1416               case '5': case '6': case '7': case '8': case '9':
1417                 esc_args[0] = 10 * esc_args[0] + c - '0';
1418                 break;
1419               default:
1420                 termstate = OSC_STRING;
1421                 osc_strlen = 0;
1422             }
1423             break;
1424           case SEEN_ESCHASH:
1425             if (c == '8') {
1426                 unsigned long *p = scrtop;
1427                 int n = rows * (cols+1);
1428                 while (n--)
1429                     *p++ = ATTR_DEFAULT | 'E';
1430                 disptop = scrtop;
1431                 seen_disp_event = TRUE;
1432                 check_selection (scrtop, scrtop + rows * (cols+1));
1433             }
1434             termstate = TOPLEVEL;
1435             break;
1436           case VT52_ESC:
1437             termstate = TOPLEVEL;
1438             seen_disp_event = TRUE;
1439             switch (c) {
1440               case 'A':
1441                 move (curs_x, curs_y - 1, 1);
1442                 break;
1443               case 'B':
1444                 move (curs_x, curs_y + 1, 1);
1445                 break;
1446               case 'C':
1447                 move (curs_x + 1, curs_y, 1);
1448                 break;
1449               case 'D':
1450                 move (curs_x - 1, curs_y, 1);
1451                 break;
1452               case 'F':
1453                 cset_attr[cset=0] = ATTR_LINEDRW;
1454                 break;
1455               case 'G':
1456                 cset_attr[cset=0] = ATTR_ASCII;
1457                 break;
1458               case 'H':
1459                 move (0, 0, 0);
1460                 break;
1461               case 'I':
1462                 if (curs_y == 0)
1463                     scroll (0, rows-1, -1, TRUE);
1464                 else if (curs_y > 0)
1465                     curs_y--;
1466                 fix_cpos;
1467                 wrapnext = FALSE;
1468                 break;
1469               case 'J':
1470                 erase_lots(FALSE, FALSE, TRUE);
1471                 disptop = scrtop;
1472                 break;
1473               case 'K':
1474                 erase_lots(TRUE, FALSE, TRUE);
1475                 break;
1476               case 'V':
1477                 /* XXX Print cursor line */
1478                 break;
1479               case 'W':
1480                 /* XXX Start controller mode */
1481                 break;
1482               case 'X':
1483                 /* XXX Stop controller mode */
1484                 break;
1485               case 'Y':
1486                 termstate = VT52_Y1;
1487                 break;
1488               case 'Z':
1489                 ldisc->send ("\033/Z", 3);
1490                 break;
1491               case '=':
1492                 app_cursor_keys = TRUE;
1493                 break;
1494               case '>':
1495                 app_cursor_keys = FALSE;
1496                 break;
1497               case '<':
1498                 /* XXX This should switch to VT100 mode not current or default
1499                  *     VT mode. But this will only have effect in a VT220+
1500                  *     emulation.
1501                  */
1502                 vt52_mode = FALSE;
1503                 break;
1504               case '^':
1505                 /* XXX Enter auto print mode */
1506                 break;
1507               case '_':
1508                 /* XXX Exit auto print mode */
1509                 break;
1510               case ']':
1511                 /* XXX Print screen */
1512                 break;
1513             }
1514             break;
1515           case VT52_Y1:
1516             termstate = VT52_Y2;
1517             move(curs_x, c-' ', 0);
1518             break;
1519           case VT52_Y2:
1520             termstate = TOPLEVEL;
1521             move(c-' ', curs_y, 0);
1522             break;
1523         }
1524         if (selstate != NO_SELECTION)
1525             check_selection (cpos, cpos+1);
1526     }
1527 }
1528
1529 /*
1530  * Compare two lines to determine whether they are sufficiently
1531  * alike to scroll-optimise one to the other. Return the degree of
1532  * similarity.
1533  */
1534 static int linecmp (unsigned long *a, unsigned long *b) {
1535     int i, n;
1536
1537     for (i=n=0; i < cols; i++)
1538         n += (*a++ == *b++);
1539     return n;
1540 }
1541
1542 /*
1543  * Given a context, update the window. Out of paranoia, we don't
1544  * allow WM_PAINT responses to do scrolling optimisations.
1545  */
1546 static void do_paint (Context ctx, int may_optimise){ 
1547     int i, j, start, our_curs_y;
1548     unsigned long attr, rv, cursor;
1549     char ch[1024];
1550
1551     if (cursor_on) {
1552         if (has_focus) {
1553             if (blinker || !cfg.blink_cur)
1554                 cursor = ATTR_ACTCURS;
1555             else
1556                 cursor = 0;
1557         }
1558         else
1559             cursor = ATTR_PASCURS;
1560     }
1561     else           cursor = 0;
1562     rv = (rvideo ? ATTR_REVERSE : 0);
1563     our_curs_y = curs_y + (scrtop - disptop) / (cols+1);
1564
1565     for (i=0; i<rows; i++) {
1566         int idx = i*(cols+1);
1567         for (j=0; j<=cols; j++,idx++) {
1568             unsigned long *d = disptop+idx;
1569             wanttext[idx] = ((*d ^ rv
1570                               ^ (selstart <= d && d < selend ?
1571                                  ATTR_REVERSE : 0)) |
1572                              (i==our_curs_y && j==curs_x ? cursor : 0));
1573         }
1574     }
1575
1576     /*
1577      * We would perform scrolling optimisations in here, if they
1578      * didn't have a nasty tendency to cause the whole sodding
1579      * program to hang for a second at speed-critical moments.
1580      * We'll leave it well alone...
1581      */
1582
1583     for (i=0; i<rows; i++) {
1584         int idx = i*(cols+1);
1585         start = -1;
1586         for (j=0; j<=cols; j++,idx++) {
1587             unsigned long t = wanttext[idx];
1588             int needs_update = (j < cols && t != disptext[idx]);
1589             int keep_going = (start != -1 && needs_update &&
1590                               (t & ATTR_MASK) == attr &&
1591                               j-start < sizeof(ch));
1592             if (start != -1 && !keep_going) {
1593                 do_text (ctx, start, i, ch, j-start, attr);
1594                 start = -1;
1595             }
1596             if (needs_update) {
1597                 if (start == -1) {
1598                     start = j;
1599                     attr = t & ATTR_MASK;
1600                 }
1601                 ch[j-start] = (char) (t & CHAR_MASK);
1602             }
1603             disptext[idx] = t;
1604         }
1605     }
1606 }
1607
1608 /*
1609  * Flick the switch that says if blinking things should be shown or hidden.
1610  */
1611
1612 void term_blink(int flg) {
1613 static long last_blink = 0;
1614     long now, blink_diff;
1615
1616     if (flg) {
1617         blinker = 1;
1618         last_blink = GetTickCount();
1619         return;
1620     } 
1621     now = GetTickCount();
1622
1623     blink_diff = now-last_blink;
1624
1625     /* Make sure the cursor blinks no more than 2Hz */
1626     if (blink_diff>=0 && blink_diff<450)
1627        return;
1628  
1629     last_blink = now;
1630     blinker = !blinker;
1631 }
1632
1633 /*
1634  * Invalidate the whole screen so it will be repainted in full.
1635  */
1636 void term_invalidate(void) {
1637     int i;
1638
1639     for (i=0; i<rows*(cols+1); i++)
1640         disptext[i] = ATTR_INVALID;
1641 }
1642
1643 /*
1644  * Paint the window in response to a WM_PAINT message.
1645  */
1646 void term_paint (Context ctx, int l, int t, int r, int b) {
1647     int i, j, left, top, right, bottom;
1648
1649     left = l / font_width;
1650     right = (r - 1) / font_width;
1651     top = t / font_height;
1652     bottom = (b - 1) / font_height;
1653     for (i = top; i <= bottom && i < rows ; i++)
1654       for (j = left; j <= right && j < cols ; j++)
1655             disptext[i*(cols+1)+j] = ATTR_INVALID;
1656
1657     /* This should happen soon enough, also for some reason it sometimes 
1658      * fails to actually do anything when re-sizing ... painting the wrong
1659      * window perhaps ?
1660     do_paint (ctx, FALSE);
1661     */
1662 }
1663
1664 /*
1665  * Attempt to scroll the scrollback. The second parameter gives the
1666  * position we want to scroll to; the first is +1 to denote that
1667  * this position is relative to the beginning of the scrollback, -1
1668  * to denote it is relative to the end, and 0 to denote that it is
1669  * relative to the current position.
1670  */
1671 void term_scroll (int rel, int where) {
1672     int n = where * (cols+1);
1673
1674     disptop = (rel < 0 ? scrtop :
1675                rel > 0 ? sbtop : disptop) + n;
1676     if (disptop < sbtop)
1677         disptop = sbtop;
1678     if (disptop > scrtop)
1679         disptop = scrtop;
1680     update_sbar();
1681     term_update();
1682 }
1683
1684 /*
1685  * Spread the selection outwards according to the selection mode.
1686  */
1687 static unsigned long *sel_spread_half (unsigned long *p, int dir) {
1688     unsigned long *linestart, *lineend;
1689     int x;
1690     short wvalue;
1691
1692     x = (p - text) % (cols+1);
1693     linestart = p - x;
1694     lineend = linestart + cols;
1695
1696     switch (selmode) {
1697       case SM_CHAR:
1698         /*
1699          * In this mode, every character is a separate unit, except
1700          * for runs of spaces at the end of a non-wrapping line.
1701          */
1702         if (!(linestart[cols] & ATTR_WRAPPED)) {
1703             unsigned long *q = lineend;
1704             while (q > linestart && (q[-1] & CHAR_MASK) == 0x20)
1705                 q--;
1706             if (q == lineend)
1707                 q--;
1708             if (p >= q)
1709                 p = (dir == -1 ? q : lineend - 1);
1710         }
1711         break;
1712       case SM_WORD:
1713         /*
1714          * In this mode, the units are maximal runs of characters
1715          * whose `wordness' has the same value.
1716          */
1717         wvalue = wordness[*p & CHAR_MASK];
1718         if (dir == +1) {
1719             while (p < lineend && wordness[p[1] & CHAR_MASK] == wvalue)
1720                 p++;
1721         } else {
1722             while (p > linestart && wordness[p[-1] & CHAR_MASK] == wvalue)
1723                 p--;
1724         }
1725         break;
1726       case SM_LINE:
1727         /*
1728          * In this mode, every line is a unit.
1729          */
1730         p = (dir == -1 ? linestart : lineend - 1);
1731         break;
1732     }
1733     return p;
1734 }
1735
1736 static void sel_spread (void) {
1737     selstart = sel_spread_half (selstart, -1);
1738     selend = sel_spread_half (selend - 1, +1) + 1;
1739 }
1740
1741 void term_mouse (Mouse_Button b, Mouse_Action a, int x, int y) {
1742     unsigned long *selpoint;
1743     
1744     if (y<0) y = 0;
1745     if (y>=rows) y = rows-1;
1746     if (x<0) {
1747         if (y > 0) {
1748             x = cols-1;
1749             y--;
1750         } else
1751             x = 0;
1752     }
1753     if (x>=cols) x = cols-1;
1754
1755     selpoint = disptop + y * (cols+1) + x;
1756
1757     if (b == MB_SELECT && a == MA_CLICK) {
1758         deselect();
1759         selstate = ABOUT_TO;
1760         selanchor = selpoint;
1761         selmode = SM_CHAR;
1762     } else if (b == MB_SELECT && (a == MA_2CLK || a == MA_3CLK)) {
1763         deselect();
1764         selmode = (a == MA_2CLK ? SM_WORD : SM_LINE);
1765         selstate = DRAGGING;
1766         selstart = selanchor = selpoint;
1767         selend = selstart + 1;
1768         sel_spread();
1769     } else if ((b == MB_SELECT && a == MA_DRAG) ||
1770                (b == MB_EXTEND && a != MA_RELEASE)) {
1771         if (selstate == ABOUT_TO && selanchor == selpoint)
1772             return;
1773         if (b == MB_EXTEND && a != MA_DRAG && selstate == SELECTED) {
1774             if (selpoint-selstart < (selend-selstart)/2)
1775                 selanchor = selend - 1;
1776             else
1777                 selanchor = selstart;
1778             selstate = DRAGGING;
1779         }
1780         if (selstate != ABOUT_TO && selstate != DRAGGING)
1781             selanchor = selpoint;
1782         selstate = DRAGGING;
1783         if (selpoint < selanchor) {
1784             selstart = selpoint;
1785             selend = selanchor + 1;
1786         } else {
1787             selstart = selanchor;
1788             selend = selpoint + 1;
1789         }
1790         sel_spread();
1791     } else if ((b == MB_SELECT || b == MB_EXTEND) && a == MA_RELEASE) {
1792         if (selstate == DRAGGING) {
1793             /*
1794              * We've completed a selection. We now transfer the
1795              * data to the clipboard.
1796              */
1797             unsigned char *p = selspace;
1798             unsigned long *q = selstart;
1799
1800             while (q < selend) {
1801                 int nl = FALSE;
1802                 unsigned long *lineend = q - (q-text) % (cols+1) + cols;
1803                 unsigned long *nlpos = lineend;
1804
1805                 if (!(*nlpos & ATTR_WRAPPED)) {
1806                     while ((nlpos[-1] & CHAR_MASK) == 0x20 && nlpos > q)
1807                         nlpos--;
1808                     if (nlpos < selend)
1809                         nl = TRUE;
1810                 }
1811                 while (q < nlpos && q < selend)
1812                     *p++ = (unsigned char) (*q++ & CHAR_MASK);
1813                 if (nl) {
1814                     int i;
1815                     for (i=0; i<sizeof(sel_nl); i++)
1816                         *p++ = sel_nl[i];
1817                 }
1818                 q = lineend + 1;       /* start of next line */
1819             }
1820             write_clip (selspace, p - selspace);
1821             selstate = SELECTED;
1822         } else
1823             selstate = NO_SELECTION;
1824     } else if (b == MB_PASTE && (a==MA_CLICK || a==MA_2CLK || a==MA_3CLK)) {
1825         char *data;
1826         int len;
1827
1828         get_clip((void **) &data, &len);
1829         if (data) {
1830             char *p, *q;
1831             p = q = data;
1832             while (p < data+len) {
1833                 while (p < data+len &&
1834                        !(p <= data+len-sizeof(sel_nl) &&
1835                          !memcmp(p, sel_nl, sizeof(sel_nl))))
1836                     p++;
1837
1838                 {
1839                     int i;
1840                     unsigned char c;
1841                     for(i=0;i<p-q;i++)
1842                     {
1843                         c=xlat_kbd2tty(q[i]);
1844                         ldisc->send(&c,1);
1845                     }
1846                 }
1847
1848                 if (p <= data+len-sizeof(sel_nl) &&
1849                     !memcmp(p, sel_nl, sizeof(sel_nl))) {
1850                     ldisc->send ("\r", 1);
1851                     p += sizeof(sel_nl);
1852                 }
1853                 q = p;
1854             }
1855         }
1856         get_clip(NULL, NULL);
1857     }
1858
1859     term_update();
1860 }
1861
1862 static void deselect (void) {
1863     selstate = NO_SELECTION;
1864     selstart = selend = scrtop;
1865 }
1866
1867 void term_deselect (void) {
1868     deselect();
1869     term_update();
1870 }