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