]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - terminal.c
b5b79e91d2dd445ca6c14542d29c029f25a68b7f
[PuTTY.git] / terminal.c
1 #include <windows.h>
2
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <ctype.h>
6
7 #include <time.h>
8 #include <assert.h>
9 #include "putty.h"
10 #include "tree234.h"
11
12 #define CL_ANSIMIN      0x0001  /* Codes in all ANSI like terminals. */
13 #define CL_VT100        0x0002  /* VT100 */
14 #define CL_VT100AVO     0x0004  /* VT100 +AVO; 132x24 (not 132x14) & attrs */
15 #define CL_VT102        0x0008  /* VT102 */
16 #define CL_VT220        0x0010  /* VT220 */
17 #define CL_VT320        0x0020  /* VT320 */
18 #define CL_VT420        0x0040  /* VT420 */
19 #define CL_VT510        0x0080  /* VT510, NB VT510 includes ANSI */
20 #define CL_VT340TEXT    0x0100  /* VT340 extensions that appear in the VT420 */
21 #define CL_SCOANSI      0x1000  /* SCOANSI not in ANSIMIN. */
22 #define CL_ANSI         0x2000  /* ANSI ECMA-48 not in the VT100..VT420 */
23 #define CL_OTHER        0x4000  /* Others, Xterm, linux, putty, dunno, etc */
24
25 #define TM_VT100        (CL_ANSIMIN|CL_VT100)
26 #define TM_VT100AVO     (TM_VT100|CL_VT100AVO)
27 #define TM_VT102        (TM_VT100AVO|CL_VT102)
28 #define TM_VT220        (TM_VT102|CL_VT220)
29 #define TM_VTXXX        (TM_VT220|CL_VT340TEXT|CL_VT510|CL_VT420|CL_VT320)
30 #define TM_SCOANSI      (CL_ANSIMIN|CL_SCOANSI)
31
32 #define TM_PUTTY        (0xFFFF)
33
34 #define compatibility(x) \
35     if ( ((CL_##x)&compatibility_level) == 0 ) {        \
36        termstate=TOPLEVEL;                              \
37        break;                                           \
38     }
39 #define compatibility2(x,y) \
40     if ( ((CL_##x|CL_##y)&compatibility_level) == 0 ) { \
41        termstate=TOPLEVEL;                              \
42        break;                                           \
43     }
44
45 #define has_compat(x) ( ((CL_##x)&compatibility_level) != 0 )
46
47 static int compatibility_level = TM_PUTTY;
48
49 static tree234 *scrollback;            /* lines scrolled off top of screen */
50 static tree234 *screen;                /* lines on primary screen */
51 static tree234 *alt_screen;            /* lines on alternate screen */
52 static int disptop;                    /* distance scrolled back (0 or -ve) */
53
54 static unsigned long *cpos;            /* cursor position (convenience) */
55
56 static unsigned long *disptext;        /* buffer of text on real screen */
57 static unsigned long *wanttext;        /* buffer of text we want on screen */
58
59 #define VBELL_TIMEOUT 100              /* millisecond len of visual bell */
60
61 struct beeptime {
62     struct beeptime *next;
63     long ticks;
64 };
65 static struct beeptime *beephead, *beeptail;
66 int nbeeps;
67 int beep_overloaded;
68 long lastbeep;
69
70 static unsigned char *selspace;        /* buffer for building selections in */
71
72 #define TSIZE (sizeof(unsigned long))
73 #define fix_cpos do { cpos = lineptr(curs.y) + curs.x; } while(0)
74
75 static unsigned long curr_attr, save_attr;
76 static unsigned long erase_char = ERASE_CHAR;
77
78 typedef struct {
79     int y, x;
80 } pos;
81 #define poslt(p1,p2) ( (p1).y < (p2).y || ( (p1).y == (p2).y && (p1).x < (p2).x ) )
82 #define posle(p1,p2) ( (p1).y < (p2).y || ( (p1).y == (p2).y && (p1).x <= (p2).x ) )
83 #define poseq(p1,p2) ( (p1).y == (p2).y && (p1).x == (p2).x )
84 #define posdiff(p1,p2) ( ((p2).y - (p1).y) * (cols+1) + (p2).x - (p1).x )
85 #define incpos(p) ( (p).x == cols ? ((p).x = 0, (p).y++, 1) : ((p).x++, 0) )
86 #define decpos(p) ( (p).x == 0 ? ((p).x = cols, (p).y--, 1) : ((p).x--, 0) )
87
88 static pos curs;                       /* cursor */
89 static pos savecurs;                   /* saved cursor position */
90 static int marg_t, marg_b;             /* scroll margins */
91 static int dec_om;                     /* DEC origin mode flag */
92 static int wrap, wrapnext;             /* wrap flags */
93 static int insert;                     /* insert-mode flag */
94 static int cset;                       /* 0 or 1: which char set */
95 static int save_cset, save_csattr;     /* saved with cursor position */
96 static int rvideo;                     /* global reverse video flag */
97 static int rvbell_timeout;             /* for ESC[?5hESC[?5l vbell */
98 static int cursor_on;                  /* cursor enabled flag */
99 static int reset_132;                  /* Flag ESC c resets to 80 cols */
100 static int use_bce;                    /* Use Background coloured erase */
101 static int blinker;                    /* When blinking is the cursor on ? */
102 static int tblinker;                   /* When the blinking text is on */
103 static int blink_is_real;              /* Actually blink blinking text */
104 static int term_echoing;               /* Does terminal want local echo? */
105 static int term_editing;               /* Does terminal want local edit? */
106
107 static unsigned long cset_attr[2];
108
109 /*
110  * Saved settings on the alternate screen.
111  */
112 static int alt_x, alt_y, alt_om, alt_wrap, alt_wnext, alt_ins, alt_cset;
113 static int alt_t, alt_b;
114 static int alt_which;
115
116 #define ARGS_MAX 32                    /* max # of esc sequence arguments */
117 #define ARG_DEFAULT 0                  /* if an arg isn't specified */
118 #define def(a,d) ( (a) == ARG_DEFAULT ? (d) : (a) )
119 static int esc_args[ARGS_MAX];
120 static int esc_nargs;
121 static int esc_query;
122 #define ANSI(x,y)       ((x)+((y)<<8))
123 #define ANSI_QUE(x)     ANSI(x,TRUE)
124
125 #define OSC_STR_MAX 2048
126 static int osc_strlen;
127 static char osc_string[OSC_STR_MAX+1];
128 static int osc_w;
129
130 static char id_string[1024] = "\033[?6c";
131
132 static unsigned char *tabs;
133
134 static enum {
135     TOPLEVEL,
136     SEEN_ESC,
137     SEEN_CSI,
138     SEEN_OSC,
139     SEEN_OSC_W,
140
141     DO_CTRLS,
142
143     IGNORE_NEXT,
144     SET_GL, SET_GR,
145     SEEN_OSC_P,
146     OSC_STRING, OSC_MAYBE_ST,
147     SEEN_ESCHASH,
148     VT52_ESC,
149     VT52_Y1,
150     VT52_Y2
151 } termstate;
152
153 static enum {
154     NO_SELECTION, ABOUT_TO, DRAGGING, SELECTED
155 } selstate;
156 static enum {
157     SM_CHAR, SM_WORD, SM_LINE
158 } selmode;
159 static pos selstart, selend, selanchor;
160
161 static short wordness[256] = {
162     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 */
163     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 */
164     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 */
165     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 */
166     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 */
167     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 */
168     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 */
169     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 */
170 };
171
172 static unsigned char sel_nl[] = SEL_NL;
173 static char * paste_buffer = 0;
174 static int paste_len, paste_pos, paste_hold;
175
176 /*
177  * Internal prototypes.
178  */
179 static void do_paint (Context, int);
180 static void erase_lots (int, int, int);
181 static void swap_screen (int);
182 static void update_sbar (void);
183 static void deselect (void);
184 /* log session to file stuff ... */
185 static FILE *lgfp = NULL;
186 static void logtraffic(unsigned char c, int logmode);
187
188 /*
189  * Retrieve a line of the screen or of the scrollback, according to
190  * whether the y coordinate is non-negative or negative
191  * (respectively).
192  */
193 unsigned long *lineptr(int y, int lineno) {
194     unsigned long *line, lineattrs;
195     tree234 *whichtree;
196     int i, treeindex, oldlen;
197
198     if (y >= 0) {
199         whichtree = screen;
200         treeindex = y;
201     } else {
202         whichtree = scrollback;
203         treeindex = y + count234(scrollback);
204     }
205     line = index234(whichtree, treeindex);
206
207     /* We assume that we don't screw up and retrieve something out of range. */
208     assert(line != NULL);
209
210     if (line[0] != cols) {
211         /*
212          * This line is the wrong length, which probably means it
213          * hasn't been accessed since a resize. Resize it now.
214          */
215         oldlen = line[0];
216         lineattrs = line[oldlen+1];
217         delpos234(whichtree, treeindex);
218         line = srealloc(line, TSIZE * (2+cols));
219         line[0] = cols;
220         for (i = oldlen; i < cols; i++)
221             line[i+1] = ERASE_CHAR;
222         line[cols+1] = lineattrs & LATTR_MODE;
223         addpos234(whichtree, line, treeindex);
224     }
225
226     return line+1;
227 }
228 #define lineptr(x) lineptr(x,__LINE__)
229 /*
230  * Set up power-on settings for the terminal.
231  */
232 static void power_on(void) {
233     curs.x = curs.y = alt_x = alt_y = savecurs.x = savecurs.y = 0;
234     alt_t = marg_t = 0;
235     if (rows != -1)
236         alt_b = marg_b = rows - 1;
237     else
238         alt_b = marg_b = 0;
239     if (cols != -1) {
240         int i;
241         for (i = 0; i < cols; i++)
242             tabs[i] = (i % 8 == 0 ? TRUE : FALSE);
243     }
244     alt_om = dec_om = cfg.dec_om;
245     alt_wnext = wrapnext = alt_ins = insert = FALSE;
246     alt_wrap = wrap = cfg.wrap_mode;
247     alt_cset = cset = 0;
248     cset_attr[0] = cset_attr[1] = ATTR_ASCII;
249     rvideo = 0;
250     in_vbell = FALSE;
251     cursor_on = 1;
252     save_attr = curr_attr = ATTR_DEFAULT;
253     term_editing = term_echoing = FALSE;
254     ldisc_send(NULL, 0);               /* cause ldisc to notice changes */
255     app_cursor_keys = cfg.app_cursor;
256     app_keypad_keys = cfg.app_keypad;
257     use_bce = cfg.bce;
258     blink_is_real = cfg.blinktext;
259     erase_char = ERASE_CHAR;
260     alt_which = 0;
261     {
262         int i;
263         for (i = 0; i < 256; i++)
264             wordness[i] = cfg.wordness[i];
265     }
266     if (screen) {
267         swap_screen (1);
268         erase_lots (FALSE, TRUE, TRUE);
269         swap_screen (0);
270         erase_lots (FALSE, TRUE, TRUE);
271     }
272 }
273
274 /*
275  * Force a screen update.
276  */
277 void term_update(void) {
278     Context ctx;
279     ctx = get_ctx();
280     if (ctx) {
281         if ( (seen_key_event && (cfg.scroll_on_key)) ||
282              (seen_disp_event && (cfg.scroll_on_disp)) ) {
283             disptop = 0;               /* return to main screen */
284             seen_disp_event = seen_key_event = 0;
285             update_sbar();
286         }
287         do_paint (ctx, TRUE);
288         sys_cursor(curs.x, curs.y - disptop);
289         free_ctx (ctx);
290     }
291 }
292
293 /*
294  * Same as power_on(), but an external function.
295  */
296 void term_pwron(void) {
297     power_on();
298     fix_cpos;
299     disptop = 0;
300     deselect();
301     term_update();
302 }
303
304 /*
305  * Clear the scrollback.
306  */
307 void term_clrsb(void) {
308     unsigned long *line;
309     disptop = 0;
310     while ((line = delpos234(scrollback, 0)) != NULL) {
311         sfree(line);
312     }
313     update_sbar();
314 }
315
316 /*
317  * Initialise the terminal.
318  */
319 void term_init(void) {
320     screen = alt_screen = scrollback = NULL;
321     disptop = 0;
322     disptext = wanttext = NULL;
323     tabs = NULL;
324     selspace = NULL;
325     deselect();
326     rows = cols = -1;
327     power_on();
328     beephead = beeptail = NULL;
329     nbeeps = 0;
330     lastbeep = FALSE;
331     beep_overloaded = FALSE;
332 }
333
334 /*
335  * Set up the terminal for a given size.
336  */
337 void term_size(int newrows, int newcols, int newsavelines) {
338     tree234 *newsb, *newscreen, *newalt;
339     unsigned long *newdisp, *newwant, *oldline, *line;
340     int i, j, ccols;
341     int sblen;
342     int save_alt_which = alt_which;
343
344     if (newrows == rows && newcols == cols && newsavelines == savelines)
345         return;                        /* nothing to do */
346
347     deselect();
348     swap_screen(0);
349
350     alt_t = marg_t = 0;
351     alt_b = marg_b = newrows - 1;
352
353     if (rows == -1) {
354         scrollback = newtree234(NULL);
355         screen = newtree234(NULL);
356         rows = 0;
357     }
358
359     /*
360      * Resize the screen and scrollback. We only need to shift
361      * lines around within our data structures, because lineptr()
362      * will take care of resizing each individual line if
363      * necessary. So:
364      * 
365      *  - If the new screen and the old screen differ in length, we
366      *    must shunt some lines in from the scrollback or out to
367      *    the scrollback.
368      * 
369      *  - If doing that fails to provide us with enough material to
370      *    fill the new screen (i.e. the number of rows needed in
371      *    the new screen exceeds the total number in the previous
372      *    screen+scrollback), we must invent some blank lines to
373      *    cover the gap.
374      * 
375      *  - Then, if the new scrollback length is less than the
376      *    amount of scrollback we actually have, we must throw some
377      *    away.
378      */
379     sblen = count234(scrollback);
380     /* Do this loop to expand the screen if newrows > rows */
381     for (i = rows; i < newrows; i++) {
382         if (sblen > 0) {
383             line = delpos234(scrollback, --sblen);
384         } else {
385             line = smalloc(TSIZE * (newcols+2));
386             line[0] = newcols;
387             for (j = 0; j <= newcols; j++)
388                 line[j+1] = ERASE_CHAR;
389         }
390         addpos234(screen, line, 0);
391     }
392     /* Do this loop to shrink the screen if newrows < rows */
393     for (i = newrows; i < rows; i++) {
394         line = delpos234(screen, 0);
395         addpos234(scrollback, line, sblen++);
396     }
397     assert(count234(screen) == newrows);
398     while (sblen > newsavelines) {
399         line = delpos234(scrollback, 0);
400         sfree(line);
401         sblen--;
402     }
403     assert(count234(scrollback) <= newsavelines);
404     disptop = 0;
405
406     newdisp = smalloc (newrows*(newcols+1)*TSIZE);
407     for (i=0; i<newrows*(newcols+1); i++)
408         newdisp[i] = ATTR_INVALID;
409     sfree (disptext);
410     disptext = newdisp;
411
412     newwant = smalloc (newrows*(newcols+1)*TSIZE);
413     for (i=0; i<newrows*(newcols+1); i++)
414         newwant[i] = ATTR_INVALID;
415     sfree (wanttext);
416     wanttext = newwant;
417
418     newalt = newtree234(NULL);
419     for (i=0; i<newrows; i++) {
420         line = smalloc(TSIZE * (newcols+2));
421         line[0] = newcols;
422         for (j = 0; j <= newcols; j++)
423             line[j+1] = erase_char;
424         addpos234(newalt, line, i);
425     }
426     if (alt_screen) {
427         while (NULL != (line = delpos234(alt_screen, 0)))
428             sfree(line);
429         freetree234(alt_screen);
430     }
431     alt_screen = newalt;
432
433     sfree (selspace);
434     selspace = smalloc ( (newrows+newsavelines) * (newcols+sizeof(sel_nl)) );
435
436     tabs = srealloc (tabs, newcols*sizeof(*tabs));
437     {
438         int i;
439         for (i = (cols > 0 ? cols : 0); i < newcols; i++)
440             tabs[i] = (i % 8 == 0 ? TRUE : FALSE);
441     }
442
443     if (rows > 0)
444         curs.y += newrows - rows;
445     if (curs.y < 0)
446         curs.y = 0;
447     if (curs.y >= newrows)
448         curs.y = newrows-1;
449     if (curs.x >= newcols)
450         curs.x = newcols-1;
451     alt_x = alt_y = 0;
452     wrapnext = alt_wnext = FALSE;
453
454     rows = newrows;
455     cols = newcols;
456     savelines = newsavelines;
457     fix_cpos;
458
459     swap_screen(save_alt_which);
460
461     update_sbar();
462     term_update();
463 }
464
465 /*
466  * Swap screens.
467  */
468 static void swap_screen (int which) {
469     int t;
470     tree234 *ttr;
471
472     if (which == alt_which)
473         return;
474
475     alt_which = which;
476
477     ttr = alt_screen; alt_screen = screen; screen = ttr;
478     t = curs.x; curs.x = alt_x; alt_x = t;
479     t = curs.y; curs.y = alt_y; alt_y = t;
480     t = marg_t; marg_t = alt_t; alt_t = t;
481     t = marg_b; marg_b = alt_b; alt_b = t;
482     t = dec_om; dec_om = alt_om; alt_om = t;
483     t = wrap; wrap = alt_wrap; alt_wrap = t;
484     t = wrapnext; wrapnext = alt_wnext; alt_wnext = t;
485     t = insert; insert = alt_ins; alt_ins = t;
486     t = cset; cset = alt_cset; alt_cset = t;
487
488     fix_cpos;
489 }
490
491 /*
492  * Update the scroll bar.
493  */
494 static void update_sbar(void) {
495     int nscroll;
496
497     nscroll = count234(scrollback);
498
499     set_sbar (nscroll + rows, nscroll + disptop, rows);
500 }
501
502 /*
503  * Check whether the region bounded by the two pointers intersects
504  * the scroll region, and de-select the on-screen selection if so.
505  */
506 static void check_selection (pos from, pos to) {
507     if (poslt(from, selend) && poslt(selstart, to))
508         deselect();
509 }
510
511 /*
512  * Scroll the screen. (`lines' is +ve for scrolling forward, -ve
513  * for backward.) `sb' is TRUE if the scrolling is permitted to
514  * affect the scrollback buffer.
515  * 
516  * NB this function invalidates all pointers into lines of the
517  * screen data structures. In particular, you MUST call fix_cpos
518  * after calling scroll() and before doing anything else that
519  * uses the cpos shortcut pointer.
520  */
521 static void scroll (int topline, int botline, int lines, int sb) {
522     unsigned long *line, *line2;
523     int i;
524
525     if (topline != 0 || alt_which != 0)
526         sb = FALSE;
527
528     if (lines < 0) {
529         while (lines < 0) {
530             line = delpos234(screen, botline);
531             for (i = 0; i < cols; i++)
532                 line[i+1] = erase_char;
533             line[cols+1] = 0;
534             addpos234(screen, line, topline);
535
536             if (selstart.y >= topline && selstart.y <= botline) {
537                 selstart.y++;
538                 if (selstart.y > botline) {
539                     selstart.y = botline;
540                     selstart.x = 0;
541                 }
542             }
543             if (selend.y >= topline && selend.y <= botline) {
544                 selend.y++;
545                 if (selend.y > botline) {
546                     selend.y = botline;
547                     selend.x = 0;
548                 }
549             }
550
551             lines++;
552         }
553     } else {
554         while (lines > 0) {
555             line = delpos234(screen, topline);
556             if (sb && savelines > 0) {
557                 int sblen = count234(scrollback);
558                 /*
559                  * We must add this line to the scrollback. We'll
560                  * remove a line from the top of the scrollback to
561                  * replace it, or allocate a new one if the
562                  * scrollback isn't full.
563                  */
564                 if (sblen == savelines) {
565                     sblen--, line2 = delpos234(scrollback, 0);
566                 } else {
567                     line2 = smalloc(TSIZE * (cols+2));
568                     line2[0] = cols;
569                 }
570                 addpos234(scrollback, line, sblen);
571                 line = line2;
572             }
573             for (i = 0; i < cols; i++)
574                 line[i+1] = erase_char;
575             line[cols+1] = 0;
576             addpos234(screen, line, botline);
577
578             if (selstart.y >= topline && selstart.y <= botline) {
579                 selstart.y--;
580                 if (selstart.y < topline) {
581                     selstart.y = topline;
582                     selstart.x = 0;
583                 }
584             }
585             if (selend.y >= topline && selend.y <= botline) {
586                 selend.y--;
587                 if (selend.y < topline) {
588                     selend.y = topline;
589                     selend.x = 0;
590                 }
591             }
592
593             lines--;
594         }
595     }
596 }
597
598 /*
599  * Move the cursor to a given position, clipping at boundaries. We
600  * may or may not want to clip at the scroll margin: marg_clip is 0
601  * not to, 1 to disallow _passing_ the margins, and 2 to disallow
602  * even _being_ outside the margins.
603  */
604 static void move (int x, int y, int marg_clip) {
605     if (x < 0)
606         x = 0;
607     if (x >= cols)
608         x = cols-1;
609     if (marg_clip) {
610         if ((curs.y >= marg_t || marg_clip == 2) && y < marg_t)
611             y = marg_t;
612         if ((curs.y <= marg_b || marg_clip == 2) && y > marg_b)
613             y = marg_b;
614     }
615     if (y < 0)
616         y = 0;
617     if (y >= rows)
618         y = rows-1;
619     curs.x = x;
620     curs.y = y;
621     fix_cpos;
622     wrapnext = FALSE;
623 }
624
625 /*
626  * Save or restore the cursor and SGR mode.
627  */
628 static void save_cursor(int save) {
629     if (save) {
630         savecurs = curs;
631         save_attr = curr_attr;
632         save_cset = cset;
633         save_csattr = cset_attr[cset];
634     } else {
635         curs = savecurs;
636         /* Make sure the window hasn't shrunk since the save */
637         if (curs.x >= cols) curs.x = cols-1;
638         if (curs.y >= rows) curs.y = rows-1;
639
640         curr_attr = save_attr;
641         cset = save_cset;
642         cset_attr[cset] = save_csattr;
643         fix_cpos;
644         if (use_bce) erase_char = (' ' |(curr_attr&(ATTR_FGMASK|ATTR_BGMASK)));
645     }
646 }
647
648 /*
649  * Erase a large portion of the screen: the whole screen, or the
650  * whole line, or parts thereof.
651  */
652 static void erase_lots (int line_only, int from_begin, int to_end) {
653     pos start, end;
654     int erase_lattr;
655     unsigned long *ldata;
656
657     if (line_only) {
658         start.y = curs.y;
659         start.x = 0;
660         end.y = curs.y + 1;
661         end.x = 0;
662         erase_lattr = FALSE;
663     } else {
664         start.y = 0;
665         start.x = 0;
666         end.y = rows;
667         end.x = 0;
668         erase_lattr = TRUE;
669     }
670     if (!from_begin) {
671         start = curs;
672     }
673     if (!to_end) {
674         end = curs;
675     }
676     check_selection (start, end);
677
678     /* Clear screen also forces a full window redraw, just in case. */
679     if (start.y == 0 && start.x == 0 && end.y == rows)
680        term_invalidate();
681
682     ldata = lineptr(start.y);
683     while (poslt(start, end)) {
684         if (start.y == cols && !erase_lattr)
685             ldata[start.x] &= ~ATTR_WRAPPED;
686         else
687             ldata[start.x] = erase_char;
688         if (incpos(start) && start.y < rows)
689             ldata = lineptr(start.y);
690     }
691 }
692
693 /*
694  * Insert or delete characters within the current line. n is +ve if
695  * insertion is desired, and -ve for deletion.
696  */
697 static void insch (int n) {
698     int dir = (n < 0 ? -1 : +1);
699     int m;
700     pos cursplus;
701     unsigned long *ldata;
702
703     n = (n < 0 ? -n : n);
704     if (n > cols - curs.x)
705         n = cols - curs.x;
706     m = cols - curs.x - n;
707     cursplus.y = curs.y;
708     cursplus.x = curs.x + n;
709     check_selection (curs, cursplus);
710     ldata = lineptr(curs.y);
711     if (dir < 0) {
712         memmove (ldata + curs.x, ldata + curs.x + n, m*TSIZE);
713         while (n--)
714             ldata[curs.x + m++] = erase_char;
715     } else {
716         memmove (ldata + curs.x + n, ldata + curs.x, m*TSIZE);
717         while (n--)
718             ldata[curs.x + n] = erase_char;
719     }
720 }
721
722 /*
723  * Toggle terminal mode `mode' to state `state'. (`query' indicates
724  * whether the mode is a DEC private one or a normal one.)
725  */
726 static void toggle_mode (int mode, int query, int state) {
727     long ticks;
728     if (query) switch (mode) {
729       case 1:                          /* application cursor keys */
730         app_cursor_keys = state;
731         break;
732       case 2:                          /* VT52 mode */
733         vt52_mode = !state;
734         break;
735       case 3:                          /* 80/132 columns */
736         deselect();
737         request_resize (state ? 132 : 80, rows, 1);
738         reset_132 = state;
739         break;
740       case 5:                          /* reverse video */
741         /*
742          * Toggle reverse video. If we receive an OFF within the
743          * visual bell timeout period after an ON, we trigger an
744          * effective visual bell, so that ESC[?5hESC[?5l will
745          * always be an actually _visible_ visual bell.
746          */
747         ticks = GetTickCount();
748         if (rvideo && !state &&        /* we're turning it off */
749             ticks < rvbell_timeout) {  /* and it's not long since it was turned on */
750             in_vbell = TRUE;           /* we may clear rvideo but we set in_vbell */
751             if (vbell_timeout < rvbell_timeout)   /* don't move vbell end forward */
752                 vbell_timeout = rvbell_timeout;   /* vbell end is at least then */
753         } else if (!rvideo && state) {
754             /* This is an ON, so we notice the time and save it. */
755             rvbell_timeout = ticks + VBELL_TIMEOUT;
756         }
757         rvideo = state;
758         seen_disp_event = TRUE;
759         if (state) term_update();
760         break;
761       case 6:                          /* DEC origin mode */
762         dec_om = state;
763         break;
764       case 7:                          /* auto wrap */
765         wrap = state;
766         break;
767       case 8:                          /* auto key repeat */
768         repeat_off = !state;
769         break;
770       case 10:                         /* set local edit mode */
771         term_editing = state;
772         ldisc_send(NULL, 0);           /* cause ldisc to notice changes */
773         break;
774       case 25:                         /* enable/disable cursor */
775         compatibility2(OTHER,VT220);
776         cursor_on = state;
777         seen_disp_event = TRUE;
778         break;
779       case 47:                         /* alternate screen */
780         compatibility(OTHER);
781         deselect();
782         swap_screen (state);
783         disptop = 0;
784         break;
785     } else switch (mode) {
786       case 4:                          /* set insert mode */
787         compatibility(VT102);
788         insert = state;
789         break;
790       case 12:                         /* set echo mode */
791         term_echoing = !state;
792         ldisc_send(NULL, 0);           /* cause ldisc to notice changes */
793         break;
794       case 20:                         /* Return sends ... */
795         cr_lf_return = state;
796         break;
797     }
798 }
799
800 /*
801  * Process an OSC sequence: set window title or icon name.
802  */
803 static void do_osc(void) {
804     if (osc_w) {
805         while (osc_strlen--)
806             wordness[(unsigned char)osc_string[osc_strlen]] = esc_args[0];
807     } else {
808         osc_string[osc_strlen] = '\0';
809         switch (esc_args[0]) {
810           case 0:
811           case 1:
812             set_icon (osc_string);
813             if (esc_args[0] == 1)
814                 break;
815             /* fall through: parameter 0 means set both */
816           case 2:
817           case 21:
818             set_title (osc_string);
819             break;
820         }
821     }
822 }
823
824 /*
825  * Remove everything currently in `inbuf' and stick it up on the
826  * in-memory display. There's a big state machine in here to
827  * process escape sequences...
828  */
829 void term_out(void) {
830     int c, inbuf_reap;
831
832     for(inbuf_reap = 0; inbuf_reap < inbuf_head; inbuf_reap++)
833     {
834         c = inbuf[inbuf_reap];
835
836         /*
837          * Optionally log the session traffic to a file. Useful for
838          * debugging and possibly also useful for actual logging.
839          */
840         logtraffic((unsigned char)c, LGTYP_DEBUG);
841
842         /* Note only VT220+ are 8-bit VT102 is seven bit, it shouldn't even
843          * be able to display 8-bit characters, but I'll let that go 'cause
844          * of i18n.
845          */
846         if( ( (c&0x60) == 0 || c == '\177') && 
847              termstate < DO_CTRLS &&
848             ( (c&0x80) == 0 || has_compat(VT220))) {
849             switch (c) {
850               case '\005':             /* terminal type query */
851                 /* Strictly speaking this is VT100 but a VT100 defaults to
852                  * no response. Other terminals respond at their option.
853                  *
854                  * Don't put a CR in the default string as this tends to
855                  * upset some weird software.
856                  *
857                  * An xterm returns "xterm" (5 characters)
858                  */
859                 compatibility(ANSIMIN);
860                 {
861                     char abuf[256], *s, *d;
862                     int state=0;
863                     for(s=cfg.answerback, d=abuf; *s; s++) {
864                         if (state)
865                         {
866                             if (*s >= 'a' && *s <= 'z')
867                                 *d++ = (*s - ('a'-1));
868                             else if ((*s >='@' && *s<='_') ||
869                                      *s == '?' || (*s&0x80))
870                                 *d++ = ('@'^*s);
871                             else if (*s == '~')
872                                 *d++ = '^';
873                             state = 0;
874                         }
875                         else if (*s == '^') {
876                             state = 1;
877                         }
878                         else
879                             *d++ = xlat_kbd2tty((unsigned char)*s);
880                     }
881                     ldisc_send (abuf, d-abuf);
882                 }
883                 break;
884               case '\007':
885                 {
886                     struct beeptime *newbeep;
887                     long ticks;
888
889                     ticks = GetTickCount();
890
891                     if (!beep_overloaded) {
892                         newbeep = smalloc(sizeof(struct beeptime));
893                         newbeep->ticks = ticks;
894                         newbeep->next = NULL;
895                         if (!beephead)
896                             beephead = newbeep;
897                         else
898                             beeptail->next = newbeep;
899                         beeptail = newbeep;
900                         nbeeps++;
901                     }
902
903                     /*
904                      * Throw out any beeps that happened more than
905                      * t seconds ago.
906                      */
907                     while (beephead &&
908                            beephead->ticks < ticks - cfg.bellovl_t) {
909                         struct beeptime *tmp = beephead;
910                         beephead = tmp->next;
911                         sfree(tmp);
912                         if (!beephead)
913                             beeptail = NULL;
914                         nbeeps--;
915                     }
916
917                     if (cfg.bellovl && beep_overloaded &&
918                         ticks-lastbeep >= cfg.bellovl_s) {
919                         /*
920                          * If we're currently overloaded and the
921                          * last beep was more than s seconds ago,
922                          * leave overload mode.
923                          */
924                         beep_overloaded = FALSE;
925                     } else if (cfg.bellovl && !beep_overloaded &&
926                                nbeeps >= cfg.bellovl_n) {
927                         /*
928                          * Now, if we have n or more beeps
929                          * remaining in the queue, go into overload
930                          * mode.
931                          */
932                         beep_overloaded = TRUE;
933                     }
934                     lastbeep = ticks;
935
936                     /*
937                      * Perform an actual beep if we're not overloaded.
938                      */
939                     if ((!cfg.bellovl || !beep_overloaded) && cfg.beep != 0) {
940                         if (cfg.beep != 2)
941                             beep(cfg.beep);
942                         else if(cfg.beep == 2) {
943                             in_vbell = TRUE;
944                             vbell_timeout = ticks + VBELL_TIMEOUT;
945                             term_update();
946                         }
947                     }
948                     disptop = 0;
949                 }
950                 break;
951               case '\b':
952                 if (curs.x == 0 && curs.y == 0)
953                     ;
954                 else if (curs.x == 0 && curs.y > 0)
955                     curs.x = cols-1, curs.y--;
956                 else if (wrapnext)
957                     wrapnext = FALSE;
958                 else
959                     curs.x--;
960                 fix_cpos;
961                 seen_disp_event = TRUE;
962                 break;
963               case '\016':
964                 compatibility(VT100);
965                 cset = 1;
966                 break;
967               case '\017':
968                 compatibility(VT100);
969                 cset = 0;
970                 break;
971               case '\033':
972                 if (vt52_mode) 
973                    termstate = VT52_ESC;
974                 else {
975                     compatibility(ANSIMIN);
976                     termstate = SEEN_ESC;
977                 }
978                 break;
979               case 0233:
980                 compatibility(VT220);
981                 termstate = SEEN_CSI;
982                 esc_nargs = 1;
983                 esc_args[0] = ARG_DEFAULT;
984                 esc_query = FALSE;
985                 break;
986               case 0235:
987                 compatibility(VT220);
988                 termstate = SEEN_OSC;
989                 esc_args[0] = 0;
990                 break;
991               case '\r':
992                 curs.x = 0;
993                 wrapnext = FALSE;
994                 fix_cpos;
995                 seen_disp_event = TRUE;
996                 paste_hold = 0;
997                 logtraffic((unsigned char)c,LGTYP_ASCII);
998                 break;
999               case '\013':
1000               case '\014':
1001                 compatibility(VT100);
1002               case '\n':
1003                 if (curs.y == marg_b)
1004                     scroll (marg_t, marg_b, 1, TRUE);
1005                 else if (curs.y < rows-1)
1006                     curs.y++;
1007                 if (cfg.lfhascr)
1008                     curs.x = 0;
1009                 fix_cpos;
1010                 wrapnext = FALSE;
1011                 seen_disp_event = 1;
1012                 paste_hold = 0;
1013                 logtraffic((unsigned char)c,LGTYP_ASCII);
1014                 break;
1015               case '\t':
1016                 {
1017                     pos old_curs = curs;
1018                     unsigned long *ldata = lineptr(curs.y);
1019
1020                     do {
1021                         curs.x++;
1022                     } while (curs.x < cols-1 && !tabs[curs.x]);
1023
1024                     if ((ldata[cols] & LATTR_MODE) != LATTR_NORM)
1025                     {
1026                         if (curs.x >= cols/2)
1027                             curs.x = cols/2-1;
1028                     }
1029                     else
1030                     {
1031                         if (curs.x >= cols)
1032                             curs.x = cols-1;
1033                     }
1034
1035                     fix_cpos;
1036                     check_selection (old_curs, curs);
1037                 }
1038                 seen_disp_event = TRUE;
1039                 break;
1040               case '\177': /* Destructive backspace
1041                               This does nothing on a real VT100 */
1042                 compatibility(OTHER);
1043                 if (curs.x && !wrapnext) curs.x--;
1044                 wrapnext = FALSE;
1045                 fix_cpos;
1046                 *cpos = (' ' | curr_attr | ATTR_ASCII);
1047                 break;
1048             }
1049         }
1050         else switch (termstate) {
1051           case TOPLEVEL:
1052             /* Only graphic characters get this far, ctrls are stripped above */
1053             if (wrapnext && wrap) {
1054                 cpos[1] |= ATTR_WRAPPED;
1055                 if (curs.y == marg_b)
1056                     scroll (marg_t, marg_b, 1, TRUE);
1057                 else if (curs.y < rows-1)
1058                     curs.y++;
1059                 curs.x = 0;
1060                 fix_cpos;
1061                 wrapnext = FALSE;
1062             }
1063             if (insert)
1064                 insch (1);
1065             if (selstate != NO_SELECTION) {
1066                 pos cursplus = curs;
1067                 incpos(cursplus);
1068                 check_selection (curs, cursplus);
1069             }
1070             switch (cset_attr[cset]) {
1071                 /*
1072                  * Linedraw characters are different from 'ESC ( B'
1073                  * only for a small range. For ones outside that
1074                  * range, make sure we use the same font as well as
1075                  * the same encoding.
1076                  */
1077             case ATTR_LINEDRW:
1078                 if (c<0x5f || c>0x7F)
1079                     *cpos++ = xlat_tty2scr((unsigned char)c) | curr_attr |
1080                               ATTR_ASCII;
1081                 else if (c==0x5F)
1082                     *cpos++ = ' ' | curr_attr | ATTR_ASCII;
1083                 else
1084                     *cpos++ = ((unsigned char)c) | curr_attr | ATTR_LINEDRW;
1085                 break;
1086             case ATTR_GBCHR:
1087                 /* If UK-ASCII, make the '#' a LineDraw Pound */
1088                 if (c == '#') {
1089                     *cpos++ = '}' | curr_attr | ATTR_LINEDRW;
1090                     break;
1091                 }
1092                 /*FALLTHROUGH*/
1093             default:
1094                 *cpos = xlat_tty2scr((unsigned char)c) | curr_attr |
1095                     (c <= 0x7F ? cset_attr[cset] : ATTR_ASCII);
1096                 logtraffic((unsigned char)c, LGTYP_ASCII);
1097                 cpos++;
1098                 break;
1099             }
1100             curs.x++;
1101             if (curs.x == cols) {
1102                 cpos--;
1103                 curs.x--;
1104                 wrapnext = TRUE;
1105             }
1106             seen_disp_event = 1;
1107             break;
1108
1109           case IGNORE_NEXT:
1110             termstate = TOPLEVEL;
1111             break;
1112           case OSC_MAYBE_ST:
1113             /*
1114              * This state is virtually identical to SEEN_ESC, with the
1115              * exception that we have an OSC sequence in the pipeline,
1116              * and _if_ we see a backslash, we process it.
1117              */
1118             if (c == '\\') {
1119                 do_osc();
1120                 termstate = TOPLEVEL;
1121                 break;
1122             }
1123             /* else fall through */
1124           case SEEN_ESC:
1125             termstate = TOPLEVEL;
1126             switch (c) {
1127               case ' ':                /* some weird sequence? */
1128                 compatibility(VT220);
1129                 termstate = IGNORE_NEXT;
1130                 break;
1131               case '[':                /* enter CSI mode */
1132                 termstate = SEEN_CSI;
1133                 esc_nargs = 1;
1134                 esc_args[0] = ARG_DEFAULT;
1135                 esc_query = FALSE;
1136                 break;
1137               case ']':                /* xterm escape sequences */
1138                 /* Compatibility is nasty here, xterm, linux, decterm yuk! */
1139                 compatibility(OTHER);
1140                 termstate = SEEN_OSC;
1141                 esc_args[0] = 0;
1142                 break;
1143               case '(':                /* should set GL */
1144                 compatibility(VT100);
1145                 termstate = SET_GL;
1146                 break;
1147               case ')':                /* should set GR */
1148                 compatibility(VT100);
1149                 termstate = SET_GR;
1150                 break;
1151               case '7':                /* save cursor */
1152                 compatibility(VT100);
1153                 save_cursor (TRUE);
1154                 break;
1155               case '8':                /* restore cursor */
1156                 compatibility(VT100);
1157                 save_cursor (FALSE);
1158                 seen_disp_event = TRUE;
1159                 break;
1160               case '=':
1161                 compatibility(VT100);
1162                 app_keypad_keys = TRUE;
1163                 break;
1164               case '>':
1165                 compatibility(VT100);
1166                 app_keypad_keys = FALSE;
1167                 break;
1168               case 'D':                /* exactly equivalent to LF */
1169                 compatibility(VT100);
1170                 if (curs.y == marg_b)
1171                     scroll (marg_t, marg_b, 1, TRUE);
1172                 else if (curs.y < rows-1)
1173                     curs.y++;
1174                 fix_cpos;
1175                 wrapnext = FALSE;
1176                 seen_disp_event = TRUE;
1177                 break;
1178               case 'E':                /* exactly equivalent to CR-LF */
1179                 compatibility(VT100);
1180                 curs.x = 0;
1181                 if (curs.y == marg_b)
1182                     scroll (marg_t, marg_b, 1, TRUE);
1183                 else if (curs.y < rows-1)
1184                     curs.y++;
1185                 fix_cpos;
1186                 wrapnext = FALSE;
1187                 seen_disp_event = TRUE;
1188                 break;
1189               case 'M':                /* reverse index - backwards LF */
1190                 compatibility(VT100);
1191                 if (curs.y == marg_t)
1192                     scroll (marg_t, marg_b, -1, TRUE);
1193                 else if (curs.y > 0)
1194                     curs.y--;
1195                 fix_cpos;
1196                 wrapnext = FALSE;
1197                 seen_disp_event = TRUE;
1198                 break;
1199               case 'Z':                /* terminal type query */
1200                 compatibility(VT100);
1201                 ldisc_send (id_string, strlen(id_string));
1202                 break;
1203               case 'c':                /* restore power-on settings */
1204                 compatibility(VT100);
1205                 power_on();
1206                 if (reset_132) {
1207                     request_resize (80, rows, 1);
1208                     reset_132 = 0;
1209                 }
1210                 fix_cpos;
1211                 disptop = 0;
1212                 seen_disp_event = TRUE;
1213                 break;
1214               case '#':                /* ESC # 8 fills screen with Es :-) */
1215                 compatibility(VT100);
1216                 termstate = SEEN_ESCHASH;
1217                 break;
1218               case 'H':                /* set a tab */
1219                 compatibility(VT100);
1220                 tabs[curs.x] = TRUE;
1221                 break;
1222             }
1223             break;
1224           case SEEN_CSI:
1225             termstate = TOPLEVEL;      /* default */
1226             if( isdigit(c) )
1227             {
1228                 if (esc_nargs <= ARGS_MAX) {
1229                     if (esc_args[esc_nargs-1] == ARG_DEFAULT)
1230                         esc_args[esc_nargs-1] = 0;
1231                     esc_args[esc_nargs-1] =
1232                         10 * esc_args[esc_nargs-1] + c - '0';
1233                 }
1234                 termstate = SEEN_CSI;
1235             }
1236             else if( c == ';' )
1237             {
1238                 if (++esc_nargs <= ARGS_MAX)
1239                     esc_args[esc_nargs-1] = ARG_DEFAULT;
1240                 termstate = SEEN_CSI;
1241             }
1242             else if( c < '@' )
1243             {
1244                 if( esc_query )     esc_query = -1;
1245                 else if( c == '?' ) esc_query = TRUE;
1246                 else                esc_query = c;
1247                 termstate = SEEN_CSI;
1248             }
1249             else switch (ANSI(c,esc_query)) {
1250               case 'A':                /* move up N lines */
1251                 move (curs.x, curs.y - def(esc_args[0], 1), 1);
1252                 seen_disp_event = TRUE;
1253                 break;
1254               case 'e':      /* move down N lines */
1255                 compatibility(ANSI);
1256               case 'B':
1257                 move (curs.x, curs.y + def(esc_args[0], 1), 1);
1258                 seen_disp_event = TRUE;
1259                 break;
1260               case 'a':      /* move right N cols */
1261                 compatibility(ANSI);
1262               case 'C':
1263                 move (curs.x + def(esc_args[0], 1), curs.y, 1);
1264                 seen_disp_event = TRUE;
1265                 break;
1266               case 'D':                /* move left N cols */
1267                 move (curs.x - def(esc_args[0], 1), curs.y, 1);
1268                 seen_disp_event = TRUE;
1269                 break;
1270               case 'E':                /* move down N lines and CR */
1271                 compatibility(ANSI);
1272                 move (0, curs.y + def(esc_args[0], 1), 1);
1273                 seen_disp_event = TRUE;
1274                 break;
1275               case 'F':                /* move up N lines and CR */
1276                 compatibility(ANSI);
1277                 move (0, curs.y - def(esc_args[0], 1), 1);
1278                 seen_disp_event = TRUE;
1279                 break;
1280               case 'G': case '`':      /* set horizontal posn */
1281                 compatibility(ANSI);
1282                 move (def(esc_args[0], 1) - 1, curs.y, 0);
1283                 seen_disp_event = TRUE;
1284                 break;
1285               case 'd':                /* set vertical posn */
1286                 compatibility(ANSI);
1287                 move (curs.x, (dec_om ? marg_t : 0) + def(esc_args[0], 1) - 1,
1288                       (dec_om ? 2 : 0));
1289                 seen_disp_event = TRUE;
1290                 break;
1291               case 'H': case 'f':      /* set horz and vert posns at once */
1292                 if (esc_nargs < 2)
1293                     esc_args[1] = ARG_DEFAULT;
1294                 move (def(esc_args[1], 1) - 1,
1295                       (dec_om ? marg_t : 0) + def(esc_args[0], 1) - 1,
1296                       (dec_om ? 2 : 0));
1297                 seen_disp_event = TRUE;
1298                 break;
1299               case 'J':                /* erase screen or parts of it */
1300                 {
1301                     unsigned int i = def(esc_args[0], 0) + 1;
1302                     if (i > 3)
1303                         i = 0;
1304                     erase_lots(FALSE, !!(i & 2), !!(i & 1));
1305                 }
1306                 disptop = 0;
1307                 seen_disp_event = TRUE;
1308                 break;
1309               case 'K':                /* erase line or parts of it */
1310                 {
1311                     unsigned int i = def(esc_args[0], 0) + 1;
1312                     if (i > 3)
1313                         i = 0;
1314                     erase_lots(TRUE, !!(i & 2), !!(i & 1));
1315                 }
1316                 seen_disp_event = TRUE;
1317                 break;
1318               case 'L':                /* insert lines */
1319                 compatibility(VT102);
1320                 if (curs.y <= marg_b)
1321                     scroll (curs.y, marg_b, -def(esc_args[0], 1), FALSE);
1322                 fix_cpos;
1323                 seen_disp_event = TRUE;
1324                 break;
1325               case 'M':                /* delete lines */
1326                 compatibility(VT102);
1327                 if (curs.y <= marg_b)
1328                     scroll (curs.y, marg_b, def(esc_args[0], 1), TRUE);
1329                 fix_cpos;
1330                 seen_disp_event = TRUE;
1331                 break;
1332               case '@':                /* insert chars */
1333                 /* XXX VTTEST says this is vt220, vt510 manual says vt102 */
1334                 compatibility(VT102);   
1335                 insch (def(esc_args[0], 1));
1336                 seen_disp_event = TRUE;
1337                 break;
1338               case 'P':                /* delete chars */
1339                 compatibility(VT102);   
1340                 insch (-def(esc_args[0], 1));
1341                 seen_disp_event = TRUE;
1342                 break;
1343               case 'c':                /* terminal type query */
1344                 compatibility(VT100);
1345                 /* This is the response for a VT102 */
1346                 ldisc_send (id_string, strlen(id_string));
1347                 break;
1348               case 'n':                /* cursor position query */
1349                 if (esc_args[0] == 6) {
1350                     char buf[32];
1351                     sprintf (buf, "\033[%d;%dR", curs.y + 1, curs.x + 1);
1352                     ldisc_send (buf, strlen(buf));
1353                 }
1354                 else if (esc_args[0] == 5) {
1355                     ldisc_send ("\033[0n", 4);
1356                 }
1357                 break;
1358               case 'h':                /* toggle modes to high */
1359               case ANSI_QUE('h'):
1360                 compatibility(VT100);
1361                 {
1362                     int i;
1363                     for (i=0; i<esc_nargs; i++)
1364                         toggle_mode (esc_args[i], esc_query, TRUE);
1365                 }
1366                 break;
1367               case 'l':                /* toggle modes to low */
1368               case ANSI_QUE('l'):
1369                 compatibility(VT100);
1370                 {
1371                     int i;
1372                     for (i=0; i<esc_nargs; i++)
1373                         toggle_mode (esc_args[i], esc_query, FALSE);
1374                 }
1375                 break;
1376               case 'g':                /* clear tabs */
1377                 compatibility(VT100);
1378                 if (esc_nargs == 1) {
1379                     if (esc_args[0] == 0) {
1380                         tabs[curs.x] = FALSE;
1381                     } else if (esc_args[0] == 3) {
1382                         int i;
1383                         for (i = 0; i < cols; i++)
1384                             tabs[i] = FALSE;
1385                     }
1386                 }
1387                 break;
1388               case 'r':                /* set scroll margins */
1389                 compatibility(VT100);
1390                 if (esc_nargs <= 2) {
1391                     int top, bot;
1392                     top = def(esc_args[0], 1) - 1;
1393                     bot = (esc_nargs <= 1 || esc_args[1] == 0 ? rows :
1394                            def(esc_args[1], rows)) - 1;
1395                     if (bot >= rows)
1396                         bot = rows-1;
1397                     /* VTTEST Bug 9 - if region is less than 2 lines
1398                      * don't change region.
1399                      */
1400                     if (bot-top > 0) {
1401                         marg_t = top;
1402                         marg_b = bot;
1403                         curs.x = 0;
1404                         /*
1405                          * I used to think the cursor should be
1406                          * placed at the top of the newly marginned
1407                          * area. Apparently not: VMS TPU falls over
1408                          * if so.
1409                          *
1410                          * Well actually it should for Origin mode - RDB
1411                          */
1412                         curs.y = (dec_om ? marg_t : 0);
1413                         fix_cpos;
1414                         seen_disp_event = TRUE;
1415                     }
1416                 }
1417                 break;
1418               case 'm':                /* set graphics rendition */
1419                 {
1420                     /* 
1421                      * A VT100 without the AVO only had one attribute, either
1422                      * underline or reverse video depending on the cursor type,
1423                      * this was selected by CSI 7m.
1424                      *
1425                      * case 2:
1426                      *  This is DIM on the VT100-AVO and VT102
1427                      * case 5:
1428                      *  This is BLINK on the VT100-AVO and VT102+
1429                      * case 8:
1430                      *  This is INVIS on the VT100-AVO and VT102
1431                      * case 21:
1432                      *  This like 22 disables BOLD, DIM and INVIS
1433                      *
1434                      * The ANSI colours appear on any terminal that has colour
1435                      * (obviously) but the interaction between sgr0 and the
1436                      * colours varies but is usually related to the background
1437                      * colour erase item.
1438                      * The interaction between colour attributes and the mono
1439                      * ones is also very implementation dependent.
1440                      *
1441                      * The 39 and 49 attributes are likely to be unimplemented.
1442                      */
1443                     int i;
1444                     for (i=0; i<esc_nargs; i++) {
1445                         switch (def(esc_args[i], 0)) {
1446                           case 0:      /* restore defaults */
1447                             curr_attr = ATTR_DEFAULT; break;
1448                           case 1:      /* enable bold */
1449                             compatibility(VT100AVO);
1450                             curr_attr |= ATTR_BOLD; break;
1451                           case 21:     /* (enable double underline) */
1452                             compatibility(OTHER);
1453                           case 4:      /* enable underline */
1454                             compatibility(VT100AVO);
1455                             curr_attr |= ATTR_UNDER; break;
1456                           case 5:      /* enable blink */
1457                             compatibility(VT100AVO);
1458                             curr_attr |= ATTR_BLINK; break;
1459                           case 7:      /* enable reverse video */
1460                             curr_attr |= ATTR_REVERSE; break;
1461                           case 22:     /* disable bold */
1462                             compatibility2(OTHER,VT220);
1463                             curr_attr &= ~ATTR_BOLD; break;
1464                           case 24:     /* disable underline */
1465                             compatibility2(OTHER,VT220);
1466                             curr_attr &= ~ATTR_UNDER; break;
1467                           case 25:     /* disable blink */
1468                             compatibility2(OTHER,VT220);
1469                             curr_attr &= ~ATTR_BLINK; break;
1470                           case 27:     /* disable reverse video */
1471                             compatibility2(OTHER,VT220);
1472                             curr_attr &= ~ATTR_REVERSE; break;
1473                           case 30: case 31: case 32: case 33:
1474                           case 34: case 35: case 36: case 37:
1475                             /* foreground */
1476                             curr_attr &= ~ATTR_FGMASK;
1477                             curr_attr |= (esc_args[i] - 30) << ATTR_FGSHIFT;
1478                             break;
1479                           case 39:     /* default-foreground */
1480                             curr_attr &= ~ATTR_FGMASK;
1481                             curr_attr |= ATTR_DEFFG;
1482                             break;
1483                           case 40: case 41: case 42: case 43:
1484                           case 44: case 45: case 46: case 47:
1485                             /* background */
1486                             curr_attr &= ~ATTR_BGMASK;
1487                             curr_attr |= (esc_args[i] - 40) << ATTR_BGSHIFT;
1488                             break;
1489                           case 49:     /* default-background */
1490                             curr_attr &= ~ATTR_BGMASK;
1491                             curr_attr |= ATTR_DEFBG;
1492                             break;
1493                         }
1494                     }
1495                     if (use_bce) 
1496                        erase_char = 
1497                             (' '|
1498                               (curr_attr&(ATTR_FGMASK|ATTR_BGMASK|ATTR_BLINK))
1499                             );
1500                 }
1501                 break;
1502               case 's':                /* save cursor */
1503                 save_cursor (TRUE);
1504                 break;
1505               case 'u':                /* restore cursor */
1506                 save_cursor (FALSE);
1507                 seen_disp_event = TRUE;
1508                 break;
1509               case 't':                /* set page size - ie window height */
1510                 /*
1511                  * VT340/VT420 sequence DECSLPP, DEC only allows values
1512                  *  24/25/36/48/72/144 other emulators (eg dtterm) use
1513                  * illegal values (eg first arg 1..9) for window changing 
1514                  * and reports.
1515                  */
1516                 compatibility(VT340TEXT);
1517                 if (esc_nargs<=1 && (esc_args[0]<1 || esc_args[0]>=24)) {
1518                     request_resize (cols, def(esc_args[0], 24), 0);
1519                     deselect();
1520                 }
1521                 break;
1522               case ANSI('|', '*'):
1523                 /* VT420 sequence DECSNLS
1524                  * Set number of lines on screen
1525                  * VT420 uses VGA like hardware and can support any size in
1526                  * reasonable range (24..49 AIUI) with no default specified.
1527                  */
1528                 compatibility(VT420);
1529                 if (esc_nargs==1 && esc_args[0]>0) {
1530                     request_resize (cols, def(esc_args[0], cfg.height), 0);
1531                     deselect();
1532                 }
1533                 break;
1534               case ANSI('|', '$'):
1535                 /* VT340/VT420 sequence DECSCPP
1536                  * Set number of columns per page
1537                  * Docs imply range is only 80 or 132, but I'll allow any.
1538                  */
1539                 compatibility(VT340TEXT);
1540                 if (esc_nargs<=1) {
1541                     request_resize (def(esc_args[0], cfg.width), rows, 0);
1542                     deselect();
1543                 }
1544                 break;
1545               case 'X':                /* write N spaces w/o moving cursor */
1546                 /* XXX VTTEST says this is vt220, vt510 manual says vt100 */
1547                 compatibility(ANSIMIN);
1548                 {
1549                     int n = def(esc_args[0], 1);
1550                     pos cursplus;
1551                     unsigned long *p = cpos;
1552                     if (n > cols - curs.x)
1553                         n = cols - curs.x;
1554                     cursplus = curs;
1555                     cursplus.x += n;
1556                     check_selection (curs, cursplus);
1557                     while (n--)
1558                         *p++ = erase_char;
1559                     seen_disp_event = TRUE;
1560                 }
1561                 break;
1562               case 'x':                /* report terminal characteristics */
1563                 compatibility(VT100);
1564                 {
1565                     char buf[32];
1566                     int i = def(esc_args[0], 0);
1567                     if (i == 0 || i == 1) {
1568                         strcpy (buf, "\033[2;1;1;112;112;1;0x");
1569                         buf[2] += i;
1570                         ldisc_send (buf, 20);
1571                     }
1572                 }
1573                 break;
1574               case ANSI('L','='):
1575                 compatibility(OTHER);
1576                 use_bce = (esc_args[0]<=0);
1577                 erase_char = ERASE_CHAR;
1578                 if (use_bce)
1579                     erase_char = (' '|(curr_attr&(ATTR_FGMASK|ATTR_BGMASK)));
1580                 break;
1581               case ANSI('E','='):
1582                 compatibility(OTHER);
1583                 blink_is_real = (esc_args[0]>=1);
1584                 break;
1585               case ANSI('p','"'):
1586                 /* Allow the host to make this emulator a 'perfect' VT102.
1587                  * This first appeared in the VT220, but we do need to get 
1588                  * back to PuTTY mode so I won't check it.
1589                  *
1590                  * The arg in 40..42 are a PuTTY extension.
1591                  * The 2nd arg, 8bit vs 7bit is not checked.
1592                  *
1593                  * Setting VT102 mode should also change the Fkeys to
1594                  * generate PF* codes as a real VT102 has no Fkeys.
1595                  * The VT220 does this, F11..F13 become ESC,BS,LF other Fkeys
1596                  * send nothing.
1597                  *
1598                  * Note ESC c will NOT change this!
1599                  */
1600
1601                 switch (esc_args[0]) {
1602                 case 61: compatibility_level &= ~TM_VTXXX;
1603                          compatibility_level |=  TM_VT102;      break;
1604                 case 62: compatibility_level &= ~TM_VTXXX;
1605                          compatibility_level |=  TM_VT220;      break;
1606
1607                 default: if( esc_args[0] > 60 && esc_args[0] < 70 )
1608                             compatibility_level |= TM_VTXXX;    
1609                          break;
1610
1611                 case 40: compatibility_level &=  TM_VTXXX;      break;
1612                 case 41: compatibility_level  =  TM_PUTTY;      break;
1613                 case 42: compatibility_level  =  TM_SCOANSI;    break;
1614
1615                 case ARG_DEFAULT: 
1616                          compatibility_level  =  TM_PUTTY;      break;
1617                 case 50: break;
1618                 }
1619
1620                 /* Change the response to CSI c */
1621                 if (esc_args[0] == 50) {
1622                    int i;
1623                    char lbuf[64];
1624                    strcpy(id_string, "\033[?");
1625                    for (i=1; i<esc_nargs; i++) {
1626                       if (i!=1) strcat(id_string, ";");
1627                       sprintf(lbuf, "%d", esc_args[i]);
1628                       strcat(id_string, lbuf);
1629                    }
1630                    strcat(id_string, "c");
1631                 }
1632
1633 #if 0
1634                 /* Is this a good idea ? 
1635                  * Well we should do a soft reset at this point ...
1636                  */
1637                 if (!has_compat(VT420) && has_compat(VT100)) {
1638                     if (reset_132) request_resize (132, 24, 1);
1639                     else           request_resize ( 80, 24, 1);
1640                 }
1641 #endif
1642                 break;
1643             }
1644             break;
1645           case SET_GL:
1646           case SET_GR:
1647             /* VT100 only here, checked above */
1648             switch (c) {
1649               case 'A':
1650                 cset_attr[termstate == SET_GL ? 0 : 1] = ATTR_GBCHR;
1651                 break;
1652               case '0':
1653                 cset_attr[termstate == SET_GL ? 0 : 1] = ATTR_LINEDRW;
1654                 break;
1655               case 'B':
1656               default:                 /* specifically, 'B' */
1657                 cset_attr[termstate == SET_GL ? 0 : 1] = ATTR_ASCII;
1658                 break;
1659             }
1660             if( !has_compat(VT220) || c != '%' )
1661                 termstate = TOPLEVEL;
1662             break;
1663           case SEEN_OSC:
1664             osc_w = FALSE;
1665             switch (c) {
1666               case 'P':                /* Linux palette sequence */
1667                 termstate = SEEN_OSC_P;
1668                 osc_strlen = 0;
1669                 break;
1670               case 'R':                /* Linux palette reset */
1671                 palette_reset();
1672                 term_invalidate();
1673                 termstate = TOPLEVEL;
1674                 break;
1675               case 'W':                /* word-set */
1676                 termstate = SEEN_OSC_W;
1677                 osc_w = TRUE;
1678                 break;
1679               case '0': case '1': case '2': case '3': case '4':
1680               case '5': case '6': case '7': case '8': case '9':
1681                 esc_args[0] = 10 * esc_args[0] + c - '0';
1682                 break;
1683               case 'L':
1684                 /*
1685                  * Grotty hack to support xterm and DECterm title
1686                  * sequences concurrently.
1687                  */
1688                 if (esc_args[0] == 2) {
1689                     esc_args[0] = 1;
1690                     break;
1691                 }
1692                 /* else fall through */
1693               default:
1694                 termstate = OSC_STRING;
1695                 osc_strlen = 0;
1696             }
1697             break;
1698           case OSC_STRING:
1699             /*
1700              * This OSC stuff is EVIL. It takes just one character to get into
1701              * sysline mode and it's not initially obvious how to get out.
1702              * So I've added CR and LF as string aborts.
1703              * This shouldn't effect compatibility as I believe embedded 
1704              * control characters are supposed to be interpreted (maybe?) 
1705              * and they don't display anything useful anyway.
1706              *
1707              * -- RDB
1708              */
1709             if (c == '\n' || c == '\r') {
1710                 termstate = TOPLEVEL;
1711             } else if (c == 0234 || c == '\007' ) {
1712                 /*
1713                  * These characters terminate the string; ST and BEL
1714                  * terminate the sequence and trigger instant
1715                  * processing of it, whereas ESC goes back to SEEN_ESC
1716                  * mode unless it is followed by \, in which case it is
1717                  * synonymous with ST in the first place.
1718                  */
1719                 do_osc();
1720                 termstate = TOPLEVEL;
1721             } else if (c == '\033')
1722                     termstate = OSC_MAYBE_ST;
1723             else if (osc_strlen < OSC_STR_MAX)
1724                 osc_string[osc_strlen++] = c;
1725             break;
1726           case SEEN_OSC_P:
1727             {
1728                 int max = (osc_strlen == 0 ? 21 : 16);
1729                 int val;
1730                 if (c >= '0' && c <= '9')
1731                     val = c - '0';
1732                 else if (c >= 'A' && c <= 'A'+max-10)
1733                     val = c - 'A' + 10;
1734                 else if (c >= 'a' && c <= 'a'+max-10)
1735                     val = c - 'a' + 10;
1736                 else
1737                     termstate = TOPLEVEL;
1738                 osc_string[osc_strlen++] = val;
1739                 if (osc_strlen >= 7) {
1740                     palette_set (osc_string[0],
1741                                  osc_string[1] * 16 + osc_string[2],
1742                                  osc_string[3] * 16 + osc_string[4],
1743                                  osc_string[5] * 16 + osc_string[6]);
1744                     term_invalidate();
1745                     termstate = TOPLEVEL;
1746                 }
1747             }
1748             break;
1749           case SEEN_OSC_W:
1750             switch (c) {
1751               case '0': case '1': case '2': case '3': case '4':
1752               case '5': case '6': case '7': case '8': case '9':
1753                 esc_args[0] = 10 * esc_args[0] + c - '0';
1754                 break;
1755               default:
1756                 termstate = OSC_STRING;
1757                 osc_strlen = 0;
1758             }
1759             break;
1760           case SEEN_ESCHASH:
1761             {
1762                 unsigned long nlattr;
1763                 unsigned long *ldata;
1764                 int i, j;
1765                 pos scrtop, scrbot;
1766
1767                 switch (c) {
1768                 case '8':
1769                     for (i = 0; i < rows; i++) {
1770                         ldata = lineptr(i);
1771                         for (j = 0; j < cols; j++)
1772                             ldata[j] = ATTR_DEFAULT | 'E';
1773                         ldata[cols] = 0;
1774                     }
1775                     disptop = 0;
1776                     seen_disp_event = TRUE;
1777                     scrtop.x = scrtop.y = 0;
1778                     scrbot.x = 0; scrbot.y = rows;
1779                     check_selection (scrtop, scrbot);
1780                     break;
1781
1782                 case '3': nlattr = LATTR_TOP; goto lattr_common;
1783                 case '4': nlattr = LATTR_BOT; goto lattr_common;
1784                 case '5': nlattr = LATTR_NORM; goto lattr_common;
1785                 case '6': nlattr = LATTR_WIDE;
1786                     lattr_common:
1787
1788                     ldata = lineptr(curs.y);
1789                     ldata[cols] &= ~LATTR_MODE;
1790                     ldata[cols] |=  nlattr;
1791                 }
1792             }
1793             termstate = TOPLEVEL;
1794             break;
1795           case VT52_ESC:
1796             termstate = TOPLEVEL;
1797             seen_disp_event = TRUE;
1798             switch (c) {
1799               case 'A':
1800                 move (curs.x, curs.y - 1, 1);
1801                 break;
1802               case 'B':
1803                 move (curs.x, curs.y + 1, 1);
1804                 break;
1805               case 'C':
1806                 move (curs.x + 1, curs.y, 1);
1807                 break;
1808               case 'D':
1809                 move (curs.x - 1, curs.y, 1);
1810                 break;
1811               case 'F':
1812                 cset_attr[cset=0] = ATTR_LINEDRW;
1813                 break;
1814               case 'G':
1815                 cset_attr[cset=0] = ATTR_ASCII;
1816                 break;
1817               case 'H':
1818                 move (0, 0, 0);
1819                 break;
1820               case 'I':
1821                 if (curs.y == 0)
1822                     scroll (0, rows-1, -1, TRUE);
1823                 else if (curs.y > 0)
1824                     curs.y--;
1825                 fix_cpos;
1826                 wrapnext = FALSE;
1827                 break;
1828               case 'J':
1829                 erase_lots(FALSE, FALSE, TRUE);
1830                 disptop = 0;
1831                 break;
1832               case 'K':
1833                 erase_lots(TRUE, FALSE, TRUE);
1834                 break;
1835               case 'V':
1836                 /* XXX Print cursor line */
1837                 break;
1838               case 'W':
1839                 /* XXX Start controller mode */
1840                 break;
1841               case 'X':
1842                 /* XXX Stop controller mode */
1843                 break;
1844               case 'Y':
1845                 termstate = VT52_Y1;
1846                 break;
1847               case 'Z':
1848                 ldisc_send ("\033/Z", 3);
1849                 break;
1850               case '=':
1851                 app_keypad_keys = TRUE;
1852                 break;
1853               case '>':
1854                 app_keypad_keys = FALSE;
1855                 break;
1856               case '<':
1857                 /* XXX This should switch to VT100 mode not current or default
1858                  *     VT mode. But this will only have effect in a VT220+
1859                  *     emulation.
1860                  */
1861                 vt52_mode = FALSE;
1862                 break;
1863               case '^':
1864                 /* XXX Enter auto print mode */
1865                 break;
1866               case '_':
1867                 /* XXX Exit auto print mode */
1868                 break;
1869               case ']':
1870                 /* XXX Print screen */
1871                 break;
1872             }
1873             break;
1874           case VT52_Y1:
1875             termstate = VT52_Y2;
1876             move(curs.x, c-' ', 0);
1877             break;
1878           case VT52_Y2:
1879             termstate = TOPLEVEL;
1880             move(c-' ', curs.y, 0);
1881             break;
1882         }
1883         if (selstate != NO_SELECTION) {
1884             pos cursplus = curs;
1885             incpos(cursplus);
1886             check_selection (curs, cursplus);
1887         }
1888     }
1889     inbuf_head = 0;
1890 }
1891
1892 /*
1893  * Compare two lines to determine whether they are sufficiently
1894  * alike to scroll-optimise one to the other. Return the degree of
1895  * similarity.
1896  */
1897 static int linecmp (unsigned long *a, unsigned long *b) {
1898     int i, n;
1899
1900     for (i=n=0; i < cols; i++)
1901         n += (*a++ == *b++);
1902     return n;
1903 }
1904
1905 /*
1906  * Given a context, update the window. Out of paranoia, we don't
1907  * allow WM_PAINT responses to do scrolling optimisations.
1908  */
1909 static void do_paint (Context ctx, int may_optimise) {
1910     int i, j, start, our_curs_y;
1911     unsigned long attr, rv, cursor;
1912     pos scrpos;
1913     char ch[1024];
1914     long ticks;
1915
1916     /*
1917      * Check the visual bell state.
1918      */
1919     if (in_vbell) {
1920         ticks = GetTickCount();
1921         if (ticks - vbell_timeout >= 0)
1922             in_vbell = FALSE;
1923     }
1924
1925     /* Depends on:
1926      * screen array, disptop, scrtop,
1927      * selection, rv, 
1928      * cfg.blinkpc, blink_is_real, tblinker, 
1929      * curs.y, curs.x, blinker, cfg.blink_cur, cursor_on, has_focus
1930      */
1931     if (cursor_on) {
1932         if (has_focus) {
1933             if (blinker || !cfg.blink_cur)
1934                 cursor = ATTR_ACTCURS;
1935             else
1936                 cursor = 0;
1937         }
1938         else
1939             cursor = ATTR_PASCURS;
1940         if (wrapnext)
1941             cursor |= ATTR_RIGHTCURS;
1942     }
1943     else
1944         cursor = 0;
1945     rv = (!rvideo ^ !in_vbell ? ATTR_REVERSE : 0);
1946     our_curs_y = curs.y - disptop;
1947
1948     for (i=0; i<rows; i++) {
1949         unsigned long *ldata;
1950         int lattr;
1951         scrpos.y = i + disptop;
1952         ldata = lineptr(scrpos.y);
1953         lattr = (ldata[cols] & LATTR_MODE);
1954         for (j=0; j<=cols; j++) {
1955             unsigned long d = ldata[j];
1956             int idx = i*(cols+1)+j;
1957             scrpos.x = j;
1958             
1959             wanttext[idx] = lattr | (((d &~ ATTR_WRAPPED) ^ rv
1960                                       ^ (posle(selstart, scrpos) &&
1961                                          poslt(scrpos, selend) ?
1962                                          ATTR_REVERSE : 0)) |
1963                                      (i==our_curs_y && j==curs.x ? cursor : 0));
1964             if (blink_is_real) {
1965                 if (has_focus && tblinker && (wanttext[idx]&ATTR_BLINK) )
1966                 {
1967                     wanttext[idx] &= ATTR_MASK;
1968                     wanttext[idx] += ' ';
1969                 }
1970                 wanttext[idx] &= ~ATTR_BLINK;
1971             }
1972         }
1973     }
1974
1975     /*
1976      * We would perform scrolling optimisations in here, if they
1977      * didn't have a nasty tendency to cause the whole sodding
1978      * program to hang for a second at speed-critical moments.
1979      * We'll leave it well alone...
1980      */
1981
1982     for (i=0; i<rows; i++) {
1983         int idx = i*(cols+1);
1984         int lattr = (wanttext[idx+cols] & LATTR_MODE);
1985         start = -1;
1986         for (j=0; j<=cols; j++,idx++) {
1987             unsigned long t = wanttext[idx];
1988             int needs_update = (j < cols && t != disptext[idx]);
1989             int keep_going = (start != -1 && needs_update &&
1990                               (t & ATTR_MASK) == attr &&
1991                               j-start < sizeof(ch));
1992             if (start != -1 && !keep_going) {
1993                 do_text (ctx, start, i, ch, j-start, attr, lattr);
1994                 start = -1;
1995             }
1996             if (needs_update) {
1997                 if (start == -1) {
1998                     start = j;
1999                     attr = t & ATTR_MASK;
2000                 }
2001                 ch[j-start] = (char) (t & CHAR_MASK);
2002             }
2003             disptext[idx] = t;
2004         }
2005     }
2006 }
2007
2008 /*
2009  * Flick the switch that says if blinking things should be shown or hidden.
2010  */
2011
2012 void term_blink(int flg) {
2013     static long last_blink = 0;
2014     static long last_tblink = 0;
2015     long now, blink_diff;
2016
2017     now = GetTickCount();
2018     blink_diff = now-last_tblink;
2019
2020     /* Make sure the text blinks no more than 2Hz */
2021     if (blink_diff<0 || blink_diff>450)
2022     {
2023         last_tblink = now;
2024         tblinker = !tblinker;
2025     }
2026
2027     if (flg) {
2028         blinker = 1;
2029         last_blink = now;
2030         return;
2031     } 
2032
2033     blink_diff = now-last_blink;
2034
2035     /* Make sure the cursor blinks no faster than GetCaretBlinkTime() */
2036     if (blink_diff>=0 && blink_diff<(long)GetCaretBlinkTime())
2037        return;
2038  
2039     last_blink = now;
2040     blinker = !blinker;
2041 }
2042
2043 /*
2044  * Invalidate the whole screen so it will be repainted in full.
2045  */
2046 void term_invalidate(void) {
2047     int i;
2048
2049     for (i=0; i<rows*(cols+1); i++)
2050         disptext[i] = ATTR_INVALID;
2051 }
2052
2053 /*
2054  * Paint the window in response to a WM_PAINT message.
2055  */
2056 void term_paint (Context ctx, int l, int t, int r, int b) {
2057     int i, j, left, top, right, bottom;
2058
2059     left = l / font_width;
2060     right = (r - 1) / font_width;
2061     top = t / font_height;
2062     bottom = (b - 1) / font_height;
2063     for (i = top; i <= bottom && i < rows ; i++)
2064     {
2065         if ( (disptext[i*(cols+1)+cols]&LATTR_MODE) == LATTR_NORM)
2066             for (j = left; j <= right && j < cols ; j++)
2067                 disptext[i*(cols+1)+j] = ATTR_INVALID;
2068         else
2069             for (j = left/2; j <= right/2+1 && j < cols ; j++)
2070                 disptext[i*(cols+1)+j] = ATTR_INVALID;
2071     }
2072
2073     /* This should happen soon enough, also for some reason it sometimes 
2074      * fails to actually do anything when re-sizing ... painting the wrong
2075      * window perhaps ?
2076     do_paint (ctx, FALSE);
2077     */
2078 }
2079
2080 /*
2081  * Attempt to scroll the scrollback. The second parameter gives the
2082  * position we want to scroll to; the first is +1 to denote that
2083  * this position is relative to the beginning of the scrollback, -1
2084  * to denote it is relative to the end, and 0 to denote that it is
2085  * relative to the current position.
2086  */
2087 void term_scroll (int rel, int where) {
2088     int sbtop = -count234(scrollback);
2089
2090     disptop = (rel < 0 ? 0 :
2091                rel > 0 ? sbtop : disptop) + where;
2092     if (disptop < sbtop)
2093         disptop = sbtop;
2094     if (disptop > 0)
2095         disptop = 0;
2096     update_sbar();
2097     term_update();
2098 }
2099
2100 static void clipme(pos top, pos bottom, char *workbuf) {
2101     char *wbptr;                /* where next char goes within workbuf */
2102     int wblen = 0;              /* workbuf len */
2103     int buflen;                 /* amount of memory allocated to workbuf */
2104
2105     if ( workbuf != NULL ) {    /* user supplied buffer? */
2106         buflen = -1;            /* assume buffer passed in is big enough */
2107         wbptr = workbuf;        /* start filling here */
2108     }
2109     else
2110         buflen = 0;             /* No data is available yet */
2111
2112     while (poslt(top, bottom)) {
2113         int nl = FALSE;
2114         unsigned long *ldata = lineptr(top.y);
2115         pos nlpos;
2116
2117         nlpos.y = top.y;
2118         nlpos.x = cols;
2119
2120         if (!(ldata[cols] & ATTR_WRAPPED)) {
2121             while ((ldata[nlpos.x-1] & CHAR_MASK) == 0x20 && poslt(top, nlpos))
2122                 decpos(nlpos);
2123             if (poslt(nlpos, bottom))
2124                 nl = TRUE;
2125         }
2126         while (poslt(top, bottom) && poslt(top, nlpos)) {
2127             int ch = (ldata[top.x] & CHAR_MASK);
2128             int set = (ldata[top.x] & CSET_MASK);
2129
2130             /* VT Specials -> ISO8859-1 for Cut&Paste */
2131             static const unsigned char poorman2[] =
2132 "* # HTFFCRLF\xB0 \xB1 NLVT+ + + + + - - - - - + + + + | <=>=PI!=\xA3 \xB7 ";
2133
2134             if (set && !cfg.rawcnp) {
2135                 if (set == ATTR_LINEDRW && ch >= 0x60 && ch < 0x7F) {
2136                     int x;
2137                     if ((x = poorman2[2*(ch-0x60)+1]) == ' ')
2138                         x = 0;
2139                     ch = (x<<8) + poorman2[2*(ch-0x60)];
2140                 }
2141             }
2142
2143             while(ch != 0) {
2144                 if (cfg.rawcnp || !!(ch&0xE0)) {
2145                     if ( wblen == buflen )
2146                     {
2147                         workbuf = srealloc(workbuf, buflen += 100);
2148                         wbptr = workbuf + wblen;
2149                     }
2150                     wblen++;
2151                     *wbptr++ = (unsigned char) ch;
2152                 }
2153                 ch>>=8;
2154             }
2155             top.x++;
2156         }
2157         if (nl) {
2158             int i;
2159             for (i=0; i<sizeof(sel_nl); i++)
2160             {
2161                 if ( wblen == buflen )
2162                 {
2163                     workbuf = srealloc(workbuf, buflen += 100);
2164                     wbptr = workbuf + wblen;
2165                 }
2166                 wblen++;
2167                 *wbptr++ = sel_nl[i];
2168             }
2169         }
2170         top.y++;
2171         top.x = 0;
2172     }
2173     write_clip (workbuf, wblen, FALSE); /* transfer to clipboard */
2174     if ( buflen > 0 )   /* indicates we allocated this buffer */
2175         sfree(workbuf);
2176
2177 }
2178 void term_copyall (void) {
2179     pos top;
2180     top.y = -count234(scrollback);
2181     top.x = 0;
2182     clipme(top, curs, NULL /* dynamic allocation */);
2183 }
2184
2185 /*
2186  * Spread the selection outwards according to the selection mode.
2187  */
2188 static pos sel_spread_half (pos p, int dir) {
2189     unsigned long *ldata;
2190     short wvalue;
2191
2192     ldata = lineptr(p.y);
2193
2194     switch (selmode) {
2195       case SM_CHAR:
2196         /*
2197          * In this mode, every character is a separate unit, except
2198          * for runs of spaces at the end of a non-wrapping line.
2199          */
2200         if (!(ldata[cols] & ATTR_WRAPPED)) {
2201             unsigned long *q = ldata+cols;
2202             while (q > ldata && (q[-1] & CHAR_MASK) == 0x20)
2203                 q--;
2204             if (q == ldata+cols)
2205                 q--;
2206             if (p.x >= q-ldata)
2207                 p.x = (dir == -1 ? q-ldata : cols - 1);
2208         }
2209         break;
2210       case SM_WORD:
2211         /*
2212          * In this mode, the units are maximal runs of characters
2213          * whose `wordness' has the same value.
2214          */
2215         wvalue = wordness[ldata[p.x] & CHAR_MASK];
2216         if (dir == +1) {
2217             while (p.x < cols && wordness[ldata[p.x+1] & CHAR_MASK] == wvalue)
2218                 p.x++;
2219         } else {
2220             while (p.x > 0 && wordness[ldata[p.x-1] & CHAR_MASK] == wvalue)
2221                 p.x--;
2222         }
2223         break;
2224       case SM_LINE:
2225         /*
2226          * In this mode, every line is a unit.
2227          */
2228         p.x = (dir == -1 ? 0 : cols - 1);
2229         break;
2230     }
2231     return p;
2232 }
2233
2234 static void sel_spread (void) {
2235     selstart = sel_spread_half (selstart, -1);
2236     decpos(selend);
2237     selend = sel_spread_half (selend, +1);
2238     incpos(selend);
2239 }
2240
2241 void term_mouse (Mouse_Button b, Mouse_Action a, int x, int y) {
2242     pos selpoint;
2243     unsigned long *ldata;
2244     
2245     if (y<0) y = 0;
2246     if (y>=rows) y = rows-1;
2247     if (x<0) {
2248         if (y > 0) {
2249             x = cols-1;
2250             y--;
2251         } else
2252             x = 0;
2253     }
2254     if (x>=cols) x = cols-1;
2255
2256     selpoint.y = y + disptop;
2257     selpoint.x = x;
2258     ldata = lineptr(selpoint.y);
2259     if ((ldata[cols]&LATTR_MODE) != LATTR_NORM)
2260         selpoint.x /= 2;
2261
2262     if (b == MB_SELECT && a == MA_CLICK) {
2263         deselect();
2264         selstate = ABOUT_TO;
2265         selanchor = selpoint;
2266         selmode = SM_CHAR;
2267     } else if (b == MB_SELECT && (a == MA_2CLK || a == MA_3CLK)) {
2268         deselect();
2269         selmode = (a == MA_2CLK ? SM_WORD : SM_LINE);
2270         selstate = DRAGGING;
2271         selstart = selanchor = selpoint;
2272         selend = selstart;
2273         incpos(selend);
2274         sel_spread();
2275     } else if ((b == MB_SELECT && a == MA_DRAG) ||
2276                (b == MB_EXTEND && a != MA_RELEASE)) {
2277         if (selstate == ABOUT_TO && poseq(selanchor, selpoint))
2278             return;
2279         if (b == MB_EXTEND && a != MA_DRAG && selstate == SELECTED) {
2280             if (posdiff(selpoint,selstart) < posdiff(selend,selstart)/2) {
2281                 selanchor = selend;
2282                 decpos(selanchor);
2283             } else {
2284                 selanchor = selstart;
2285             }
2286             selstate = DRAGGING;
2287         }
2288         if (selstate != ABOUT_TO && selstate != DRAGGING)
2289             selanchor = selpoint;
2290         selstate = DRAGGING;
2291         if (poslt(selpoint, selanchor)) {
2292             selstart = selpoint;
2293             selend = selanchor;
2294             incpos(selend);
2295         } else {
2296             selstart = selanchor;
2297             selend = selpoint;
2298             incpos(selend);
2299         }
2300         sel_spread();
2301     } else if ((b == MB_SELECT || b == MB_EXTEND) && a == MA_RELEASE) {
2302         if (selstate == DRAGGING) {
2303             /*
2304              * We've completed a selection. We now transfer the
2305              * data to the clipboard.
2306              */
2307             clipme(selstart, selend, selspace);
2308             selstate = SELECTED;
2309         } else
2310             selstate = NO_SELECTION;
2311     } else if (b == MB_PASTE && (a==MA_CLICK || a==MA_2CLK || a==MA_3CLK)) {
2312         char *data;
2313         int len;
2314
2315         get_clip((void **) &data, &len);
2316         if (data) {
2317             char *p, *q;
2318
2319             if (paste_buffer) sfree(paste_buffer);
2320             paste_pos = paste_hold = paste_len = 0;
2321             paste_buffer = smalloc(len);
2322
2323             p = q = data;
2324             while (p < data+len) {
2325                 while (p < data+len &&
2326                        !(p <= data+len-sizeof(sel_nl) &&
2327                          !memcmp(p, sel_nl, sizeof(sel_nl))))
2328                     p++;
2329
2330                 {
2331                     int i;
2332                     unsigned char c;
2333                     for(i=0;i<p-q;i++)
2334                     {
2335                         c=xlat_kbd2tty(q[i]);
2336                         paste_buffer[paste_len++] = c;
2337                     }
2338                 }
2339
2340                 if (p <= data+len-sizeof(sel_nl) &&
2341                     !memcmp(p, sel_nl, sizeof(sel_nl))) {
2342                     paste_buffer[paste_len++] = '\r';
2343                     p += sizeof(sel_nl);
2344                 }
2345                 q = p;
2346             }
2347
2348             /* Assume a small paste will be OK in one go. */
2349             if (paste_len<256) {
2350                 ldisc_send (paste_buffer, paste_len);
2351                 if (paste_buffer) sfree(paste_buffer);
2352                 paste_buffer = 0;
2353                 paste_pos = paste_hold = paste_len = 0;
2354             }
2355         }
2356         get_clip(NULL, NULL);
2357     }
2358
2359     term_update();
2360 }
2361
2362 void term_nopaste() {
2363     if(paste_len == 0) return;
2364     sfree(paste_buffer);
2365     paste_buffer = 0;
2366     paste_len = 0;
2367 }
2368
2369 void term_paste() {
2370     static long last_paste = 0;
2371     long now, paste_diff;
2372
2373     if(paste_len == 0) return;
2374
2375     /* Don't wait forever to paste */
2376     if(paste_hold) {
2377         now = GetTickCount();
2378         paste_diff = now-last_paste;
2379         if (paste_diff>=0 && paste_diff<450)
2380             return;
2381     }
2382     paste_hold = 0;
2383
2384     while(paste_pos<paste_len)
2385     {
2386         int n = 0;
2387         while (n + paste_pos < paste_len) {
2388             if (paste_buffer[paste_pos + n++] == '\r')
2389                 break;
2390         }
2391         ldisc_send (paste_buffer+paste_pos, n);
2392         paste_pos += n;
2393
2394         if (paste_pos < paste_len) {
2395             paste_hold = 1;
2396             return;
2397         }
2398     }
2399     sfree(paste_buffer);
2400     paste_buffer = 0;
2401     paste_len = 0;
2402 }
2403
2404 static void deselect (void) {
2405     selstate = NO_SELECTION;
2406     selstart.x = selstart.y = selend.x = selend.y = 0;
2407 }
2408
2409 void term_deselect (void) {
2410     deselect();
2411     term_update();
2412 }
2413
2414 int term_ldisc(int option) {
2415     if (option == LD_ECHO) return term_echoing;
2416     if (option == LD_EDIT) return term_editing;
2417     return FALSE;
2418 }
2419
2420 /*
2421  * from_backend(), to get data from the backend for the terminal.
2422  */
2423 void from_backend(int is_stderr, char *data, int len) {
2424     while (len--) {
2425         if (inbuf_head >= INBUF_SIZE)
2426             term_out();
2427         inbuf[inbuf_head++] = *data++;
2428     }
2429 }
2430
2431 /*
2432  * Log session traffic.
2433  */
2434 void logtraffic(unsigned char c, int logmode) {
2435     if (cfg.logtype > 0) {
2436         if (cfg.logtype == logmode) {
2437             /* deferred open file from pgm start? */
2438             if (!lgfp) logfopen();
2439             if (lgfp) fputc (c, lgfp);
2440         }
2441     }
2442 }
2443
2444 /* open log file append/overwrite mode */
2445 void logfopen(void) {
2446     char buf[256];
2447     time_t t;
2448     struct tm *tm;
2449     char writemod[4];
2450
2451     if (!cfg.logtype)
2452         return;
2453     sprintf (writemod, "wb");          /* default to rewrite */
2454     lgfp = fopen(cfg.logfilename, "r");  /* file already present? */
2455     if (lgfp) {
2456         int i;
2457         fclose(lgfp);
2458         i = askappend(cfg.logfilename);
2459         if (i == 1)
2460             writemod[0] = 'a';         /* set append mode */
2461         else if (i == 0) {             /* cancelled */
2462             lgfp = NULL;
2463             cfg.logtype = 0;           /* disable logging */
2464             return;
2465         }
2466     }
2467
2468     lgfp = fopen(cfg.logfilename, writemod);
2469     if (lgfp) { /* enter into event log */
2470         sprintf(buf, "%s session log (%s mode) to file : ",
2471                 (writemod[0] == 'a') ? "Appending" : "Writing new",
2472                 (cfg.logtype == LGTYP_ASCII ? "ASCII" :
2473                  cfg.logtype == LGTYP_DEBUG ? "raw" : "<ukwn>")  );
2474         /* Make sure we do not exceed the output buffer size */
2475         strncat (buf, cfg.logfilename, 128);
2476         buf[strlen(buf)] = '\0';
2477         logevent(buf);
2478
2479         /* --- write header line iinto log file */
2480         fputs ("=~=~=~=~=~=~=~=~=~=~=~= PuTTY log ", lgfp);
2481         time(&t);
2482         tm = localtime(&t);
2483         strftime(buf, 24, "%Y.%m.%d %H:%M:%S", tm);
2484         fputs (buf, lgfp);
2485         fputs (" =~=~=~=~=~=~=~=~=~=~=~=\r\n", lgfp);
2486     }
2487 }
2488
2489 void logfclose (void) {
2490     if (lgfp) { fclose(lgfp); lgfp = NULL; }
2491 }