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