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