]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - terminal.c
Introduced wrapper macros snew(), snewn() and sresize() for the
[PuTTY.git] / terminal.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <ctype.h>
4
5 #include <time.h>
6 #include <assert.h>
7 #include "putty.h"
8 #include "terminal.h"
9
10 #define poslt(p1,p2) ( (p1).y < (p2).y || ( (p1).y == (p2).y && (p1).x < (p2).x ) )
11 #define posle(p1,p2) ( (p1).y < (p2).y || ( (p1).y == (p2).y && (p1).x <= (p2).x ) )
12 #define poseq(p1,p2) ( (p1).y == (p2).y && (p1).x == (p2).x )
13 #define posdiff(p1,p2) ( ((p1).y - (p2).y) * (term->cols+1) + (p1).x - (p2).x )
14
15 /* Product-order comparisons for rectangular block selection. */
16 #define posPlt(p1,p2) ( (p1).y <= (p2).y && (p1).x < (p2).x )
17 #define posPle(p1,p2) ( (p1).y <= (p2).y && (p1).x <= (p2).x )
18
19 #define incpos(p) ( (p).x == term->cols ? ((p).x = 0, (p).y++, 1) : ((p).x++, 0) )
20 #define decpos(p) ( (p).x == 0 ? ((p).x = term->cols, (p).y--, 1) : ((p).x--, 0) )
21
22 #define VT52_PLUS
23
24 #define CL_ANSIMIN      0x0001         /* Codes in all ANSI like terminals. */
25 #define CL_VT100        0x0002         /* VT100 */
26 #define CL_VT100AVO     0x0004         /* VT100 +AVO; 132x24 (not 132x14) & attrs */
27 #define CL_VT102        0x0008         /* VT102 */
28 #define CL_VT220        0x0010         /* VT220 */
29 #define CL_VT320        0x0020         /* VT320 */
30 #define CL_VT420        0x0040         /* VT420 */
31 #define CL_VT510        0x0080         /* VT510, NB VT510 includes ANSI */
32 #define CL_VT340TEXT    0x0100         /* VT340 extensions that appear in the VT420 */
33 #define CL_SCOANSI      0x1000         /* SCOANSI not in ANSIMIN. */
34 #define CL_ANSI         0x2000         /* ANSI ECMA-48 not in the VT100..VT420 */
35 #define CL_OTHER        0x4000         /* Others, Xterm, linux, putty, dunno, etc */
36
37 #define TM_VT100        (CL_ANSIMIN|CL_VT100)
38 #define TM_VT100AVO     (TM_VT100|CL_VT100AVO)
39 #define TM_VT102        (TM_VT100AVO|CL_VT102)
40 #define TM_VT220        (TM_VT102|CL_VT220)
41 #define TM_VTXXX        (TM_VT220|CL_VT340TEXT|CL_VT510|CL_VT420|CL_VT320)
42 #define TM_SCOANSI      (CL_ANSIMIN|CL_SCOANSI)
43
44 #define TM_PUTTY        (0xFFFF)
45
46 #define compatibility(x) \
47     if ( ((CL_##x)&term->compatibility_level) == 0 ) {  \
48        term->termstate=TOPLEVEL;                        \
49        break;                                           \
50     }
51 #define compatibility2(x,y) \
52     if ( ((CL_##x|CL_##y)&term->compatibility_level) == 0 ) { \
53        term->termstate=TOPLEVEL;                        \
54        break;                                           \
55     }
56
57 #define has_compat(x) ( ((CL_##x)&term->compatibility_level) != 0 )
58
59 #define sel_nl_sz  (sizeof(sel_nl)/sizeof(wchar_t))
60 const wchar_t sel_nl[] = SEL_NL;
61
62 /*
63  * Fetch the character at a particular position in a line array,
64  * for purposes of `wordtype'. The reason this isn't just a simple
65  * array reference is that if the character we find is UCSWIDE,
66  * then we must look one space further to the left.
67  */
68 #define UCSGET(a, x) \
69     ( (x)>0 && ((a)[(x)] & (CHAR_MASK | CSET_MASK)) == UCSWIDE ? \
70         (a)[(x)-1] : (a)[(x)] )
71
72 /*
73  * Internal prototypes.
74  */
75 static unsigned long *resizeline(unsigned long *, int);
76 static unsigned long *lineptr(Terminal *, int, int);
77 static void do_paint(Terminal *, Context, int);
78 static void erase_lots(Terminal *, int, int, int);
79 static void swap_screen(Terminal *, int, int, int);
80 static void update_sbar(Terminal *);
81 static void deselect(Terminal *);
82 static void term_print_finish(Terminal *);
83 #ifdef OPTIMISE_SCROLL
84 static void scroll_display(Terminal *, int, int, int);
85 #endif /* OPTIMISE_SCROLL */
86
87 /*
88  * Resize a line to make it `cols' columns wide.
89  */
90 static unsigned long *resizeline(unsigned long *line, int cols)
91 {
92     int i, oldlen;
93     unsigned long lineattrs;
94
95     if (line[0] != (unsigned long)cols) {
96         /*
97          * This line is the wrong length, which probably means it
98          * hasn't been accessed since a resize. Resize it now.
99          */
100         oldlen = line[0];
101         lineattrs = line[oldlen + 1];
102         line = sresize(line, 2 + cols, TTYPE);
103         line[0] = cols;
104         for (i = oldlen; i < cols; i++)
105             line[i + 1] = ERASE_CHAR;
106         line[cols + 1] = lineattrs & LATTR_MODE;
107     }
108
109     return line;
110 }
111
112 /*
113  * Get the number of lines in the scrollback.
114  */
115 static int sblines(Terminal *term)
116 {
117     int sblines = count234(term->scrollback);
118     if (term->cfg.erase_to_scrollback &&
119         term->alt_which && term->alt_screen) {
120             sblines += term->alt_sblines;
121     }
122     return sblines;
123 }
124
125 /*
126  * Retrieve a line of the screen or of the scrollback, according to
127  * whether the y coordinate is non-negative or negative
128  * (respectively).
129  */
130 static unsigned long *lineptr(Terminal *term, int y, int lineno)
131 {
132     unsigned long *line, *newline;
133     tree234 *whichtree;
134     int treeindex;
135
136     if (y >= 0) {
137         whichtree = term->screen;
138         treeindex = y;
139     } else {
140         int altlines = 0;
141         if (term->cfg.erase_to_scrollback &&
142             term->alt_which && term->alt_screen) {
143             altlines = term->alt_sblines;
144         }
145         if (y < -altlines) {
146             whichtree = term->scrollback;
147             treeindex = y + altlines + count234(term->scrollback);
148         } else {
149             whichtree = term->alt_screen;
150             treeindex = y + term->alt_sblines;
151             /* treeindex = y + count234(term->alt_screen); */
152         }
153     }
154     line = index234(whichtree, treeindex);
155
156     /* We assume that we don't screw up and retrieve something out of range. */
157     assert(line != NULL);
158
159     newline = resizeline(line, term->cols);
160     if (newline != line) {
161         delpos234(whichtree, treeindex);
162         addpos234(whichtree, newline, treeindex);
163         line = newline;
164     }
165
166     return line + 1;
167 }
168
169 #define lineptr(x) lineptr(term,x,__LINE__)
170
171 /*
172  * Set up power-on settings for the terminal.
173  */
174 static void power_on(Terminal *term)
175 {
176     term->curs.x = term->curs.y = 0;
177     term->alt_x = term->alt_y = 0;
178     term->savecurs.x = term->savecurs.y = 0;
179     term->alt_t = term->marg_t = 0;
180     if (term->rows != -1)
181         term->alt_b = term->marg_b = term->rows - 1;
182     else
183         term->alt_b = term->marg_b = 0;
184     if (term->cols != -1) {
185         int i;
186         for (i = 0; i < term->cols; i++)
187             term->tabs[i] = (i % 8 == 0 ? TRUE : FALSE);
188     }
189     term->alt_om = term->dec_om = term->cfg.dec_om;
190     term->alt_ins = term->insert = FALSE;
191     term->alt_wnext = term->wrapnext = term->save_wnext = FALSE;
192     term->alt_wrap = term->wrap = term->cfg.wrap_mode;
193     term->alt_cset = term->cset = term->save_cset = 0;
194     term->alt_utf = term->utf = term->save_utf = 0;
195     term->utf_state = 0;
196     term->alt_sco_acs = term->sco_acs = term->save_sco_acs = 0;
197     term->cset_attr[0] = term->cset_attr[1] = term->save_csattr = ATTR_ASCII;
198     term->rvideo = 0;
199     term->in_vbell = FALSE;
200     term->cursor_on = 1;
201     term->big_cursor = 0;
202     term->save_attr = term->curr_attr = ATTR_DEFAULT;
203     term->term_editing = term->term_echoing = FALSE;
204     term->app_cursor_keys = term->cfg.app_cursor;
205     term->app_keypad_keys = term->cfg.app_keypad;
206     term->use_bce = term->cfg.bce;
207     term->blink_is_real = term->cfg.blinktext;
208     term->erase_char = ERASE_CHAR;
209     term->alt_which = 0;
210     term_print_finish(term);
211     {
212         int i;
213         for (i = 0; i < 256; i++)
214             term->wordness[i] = term->cfg.wordness[i];
215     }
216     if (term->screen) {
217         swap_screen(term, 1, FALSE, FALSE);
218         erase_lots(term, FALSE, TRUE, TRUE);
219         swap_screen(term, 0, FALSE, FALSE);
220         erase_lots(term, FALSE, TRUE, TRUE);
221     }
222 }
223
224 /*
225  * Force a screen update.
226  */
227 void term_update(Terminal *term)
228 {
229     Context ctx;
230     ctx = get_ctx(term->frontend);
231     if (ctx) {
232         int need_sbar_update = term->seen_disp_event;
233         if (term->seen_disp_event && term->cfg.scroll_on_disp) {
234             term->disptop = 0;         /* return to main screen */
235             term->seen_disp_event = 0;
236             need_sbar_update = TRUE;
237         }
238         if (need_sbar_update)
239             update_sbar(term);
240         do_paint(term, ctx, TRUE);
241         sys_cursor(term->frontend, term->curs.x, term->curs.y - term->disptop);
242         free_ctx(ctx);
243     }
244 }
245
246 /*
247  * Called from front end when a keypress occurs, to trigger
248  * anything magical that needs to happen in that situation.
249  */
250 void term_seen_key_event(Terminal *term)
251 {
252     /*
253      * On any keypress, clear the bell overload mechanism
254      * completely, on the grounds that large numbers of
255      * beeps coming from deliberate key action are likely
256      * to be intended (e.g. beeps from filename completion
257      * blocking repeatedly).
258      */
259     term->beep_overloaded = FALSE;
260     while (term->beephead) {
261         struct beeptime *tmp = term->beephead;
262         term->beephead = tmp->next;
263         sfree(tmp);
264     }
265     term->beeptail = NULL;
266     term->nbeeps = 0;
267
268     /*
269      * Reset the scrollback on keypress, if we're doing that.
270      */
271     if (term->cfg.scroll_on_key) {
272         term->disptop = 0;             /* return to main screen */
273         term->seen_disp_event = 1;
274     }
275 }
276
277 /*
278  * Same as power_on(), but an external function.
279  */
280 void term_pwron(Terminal *term)
281 {
282     power_on(term);
283     if (term->ldisc)                   /* cause ldisc to notice changes */
284         ldisc_send(term->ldisc, NULL, 0, 0);
285     fix_cpos;
286     term->disptop = 0;
287     deselect(term);
288     term_update(term);
289 }
290
291 /*
292  * When the user reconfigures us, we need to check the forbidden-
293  * alternate-screen config option, disable raw mouse mode if the
294  * user has disabled mouse reporting, and abandon a print job if
295  * the user has disabled printing.
296  */
297 void term_reconfig(Terminal *term, Config *cfg)
298 {
299     /*
300      * Before adopting the new config, check all those terminal
301      * settings which control power-on defaults; and if they've
302      * changed, we will modify the current state as well as the
303      * default one. The full list is: Auto wrap mode, DEC Origin
304      * Mode, BCE, blinking text, character classes.
305      */
306     int reset_wrap, reset_decom, reset_bce, reset_blink, reset_charclass;
307     int i;
308
309     reset_wrap = (term->cfg.wrap_mode != cfg->wrap_mode);
310     reset_decom = (term->cfg.dec_om != cfg->dec_om);
311     reset_bce = (term->cfg.bce != cfg->bce);
312     reset_blink = (term->cfg.blinktext != cfg->blinktext);
313     reset_charclass = 0;
314     for (i = 0; i < lenof(term->cfg.wordness); i++)
315         if (term->cfg.wordness[i] != cfg->wordness[i])
316             reset_charclass = 1;
317
318     term->cfg = *cfg;                  /* STRUCTURE COPY */
319
320     if (reset_wrap)
321         term->alt_wrap = term->wrap = term->cfg.wrap_mode;
322     if (reset_decom)
323         term->alt_om = term->dec_om = term->cfg.dec_om;
324     if (reset_bce)
325         term->use_bce = term->cfg.bce;
326     if (reset_blink)
327         term->blink_is_real = term->cfg.blinktext;
328     if (reset_charclass)
329         for (i = 0; i < 256; i++)
330             term->wordness[i] = term->cfg.wordness[i];
331
332     if (term->cfg.no_alt_screen)
333         swap_screen(term, 0, FALSE, FALSE);
334     if (term->cfg.no_mouse_rep) {
335         term->xterm_mouse = 0;
336         set_raw_mouse_mode(term->frontend, 0);
337     }
338     if (term->cfg.no_remote_charset) {
339         term->cset_attr[0] = term->cset_attr[1] = ATTR_ASCII;
340         term->sco_acs = term->alt_sco_acs = 0;
341         term->utf = 0;
342     }
343     if (!*term->cfg.printer) {
344         term_print_finish(term);
345     }
346 }
347
348 /*
349  * Clear the scrollback.
350  */
351 void term_clrsb(Terminal *term)
352 {
353     unsigned long *line;
354     term->disptop = 0;
355     while ((line = delpos234(term->scrollback, 0)) != NULL) {
356         sfree(line);
357     }
358     term->tempsblines = 0;
359     term->alt_sblines = 0;
360     update_sbar(term);
361 }
362
363 /*
364  * Initialise the terminal.
365  */
366 Terminal *term_init(Config *mycfg, struct unicode_data *ucsdata,
367                     void *frontend)
368 {
369     Terminal *term;
370
371     /*
372      * Allocate a new Terminal structure and initialise the fields
373      * that need it.
374      */
375     term = snew(Terminal);
376     term->frontend = frontend;
377     term->ucsdata = ucsdata;
378     term->cfg = *mycfg;                /* STRUCTURE COPY */
379     term->logctx = NULL;
380     term->compatibility_level = TM_PUTTY;
381     strcpy(term->id_string, "\033[?6c");
382     term->last_blink = term->last_tblink = 0;
383     term->paste_buffer = NULL;
384     term->paste_len = 0;
385     term->last_paste = 0;
386     bufchain_init(&term->inbuf);
387     bufchain_init(&term->printer_buf);
388     term->printing = term->only_printing = FALSE;
389     term->print_job = NULL;
390     term->vt52_mode = FALSE;
391     term->cr_lf_return = FALSE;
392     term->seen_disp_event = FALSE;
393     term->xterm_mouse = term->mouse_is_down = FALSE;
394     term->reset_132 = FALSE;
395     term->blinker = term->tblinker = 0;
396     term->has_focus = 1;
397     term->repeat_off = FALSE;
398     term->termstate = TOPLEVEL;
399     term->selstate = NO_SELECTION;
400     term->curstype = 0;
401
402     term->screen = term->alt_screen = term->scrollback = NULL;
403     term->tempsblines = 0;
404     term->alt_sblines = 0;
405     term->disptop = 0;
406     term->disptext = term->dispcurs = NULL;
407     term->tabs = NULL;
408     deselect(term);
409     term->rows = term->cols = -1;
410     power_on(term);
411     term->beephead = term->beeptail = NULL;
412 #ifdef OPTIMISE_SCROLL
413     term->scrollhead = term->scrolltail = NULL;
414 #endif /* OPTIMISE_SCROLL */
415     term->nbeeps = 0;
416     term->lastbeep = FALSE;
417     term->beep_overloaded = FALSE;
418     term->attr_mask = 0xffffffff;
419     term->resize_fn = NULL;
420     term->resize_ctx = NULL;
421
422     return term;
423 }
424
425 void term_free(Terminal *term)
426 {
427     unsigned long *line;
428     struct beeptime *beep;
429
430     while ((line = delpos234(term->scrollback, 0)) != NULL)
431         sfree(line);
432     freetree234(term->scrollback);
433     while ((line = delpos234(term->screen, 0)) != NULL)
434         sfree(line);
435     freetree234(term->screen);
436     while ((line = delpos234(term->alt_screen, 0)) != NULL)
437         sfree(line);
438     freetree234(term->alt_screen);
439     sfree(term->disptext);
440     while (term->beephead) {
441         beep = term->beephead;
442         term->beephead = beep->next;
443         sfree(beep);
444     }
445     bufchain_clear(&term->inbuf);
446     if(term->print_job)
447         printer_finish_job(term->print_job);
448     bufchain_clear(&term->printer_buf);
449     sfree(term->paste_buffer);
450     sfree(term);
451 }
452
453 /*
454  * Set up the terminal for a given size.
455  */
456 void term_size(Terminal *term, int newrows, int newcols, int newsavelines)
457 {
458     tree234 *newalt;
459     unsigned long *newdisp, *line;
460     int i, j;
461     int sblen;
462     int save_alt_which = term->alt_which;
463
464     if (newrows == term->rows && newcols == term->cols &&
465         newsavelines == term->savelines)
466         return;                        /* nothing to do */
467
468     deselect(term);
469     swap_screen(term, 0, FALSE, FALSE);
470
471     term->alt_t = term->marg_t = 0;
472     term->alt_b = term->marg_b = newrows - 1;
473
474     if (term->rows == -1) {
475         term->scrollback = newtree234(NULL);
476         term->screen = newtree234(NULL);
477         term->tempsblines = 0;
478         term->rows = 0;
479     }
480
481     /*
482      * Resize the screen and scrollback. We only need to shift
483      * lines around within our data structures, because lineptr()
484      * will take care of resizing each individual line if
485      * necessary. So:
486      * 
487      *  - If the new screen is longer, we shunt lines in from temporary
488      *    scrollback if possible, otherwise we add new blank lines at
489      *    the bottom.
490      *
491      *  - If the new screen is shorter, we remove any blank lines at
492      *    the bottom if possible, otherwise shunt lines above the cursor
493      *    to scrollback if possible, otherwise delete lines below the
494      *    cursor.
495      * 
496      *  - Then, if the new scrollback length is less than the
497      *    amount of scrollback we actually have, we must throw some
498      *    away.
499      */
500     sblen = count234(term->scrollback);
501     /* Do this loop to expand the screen if newrows > rows */
502     assert(term->rows == count234(term->screen));
503     while (term->rows < newrows) {
504         if (term->tempsblines > 0) {
505             /* Insert a line from the scrollback at the top of the screen. */
506             assert(sblen >= term->tempsblines);
507             line = delpos234(term->scrollback, --sblen);
508             term->tempsblines -= 1;
509             addpos234(term->screen, line, 0);
510             term->curs.y += 1;
511             term->savecurs.y += 1;
512         } else {
513             /* Add a new blank line at the bottom of the screen. */
514             line = snewn(newcols + 2, TTYPE);
515             line[0] = newcols;
516             for (j = 0; j < newcols; j++)
517                 line[j + 1] = ERASE_CHAR;
518             line[newcols + 1] = LATTR_NORM;
519             addpos234(term->screen, line, count234(term->screen));
520         }
521         term->rows += 1;
522     }
523     /* Do this loop to shrink the screen if newrows < rows */
524     while (term->rows > newrows) {
525         if (term->curs.y < term->rows - 1) {
526             /* delete bottom row, unless it contains the cursor */
527             sfree(delpos234(term->screen, term->rows - 1));
528         } else {
529             /* push top row to scrollback */
530             line = delpos234(term->screen, 0);
531             addpos234(term->scrollback, line, sblen++);
532             term->tempsblines += 1;
533             term->curs.y -= 1;
534             term->savecurs.y -= 1;
535         }
536         term->rows -= 1;
537     }
538     assert(term->rows == newrows);
539     assert(count234(term->screen) == newrows);
540
541     /* Delete any excess lines from the scrollback. */
542     while (sblen > newsavelines) {
543         line = delpos234(term->scrollback, 0);
544         sfree(line);
545         sblen--;
546     }
547     if (sblen < term->tempsblines)
548         term->tempsblines = sblen;
549     assert(count234(term->scrollback) <= newsavelines);
550     assert(count234(term->scrollback) >= term->tempsblines);
551     term->disptop = 0;
552
553     /* Make a new displayed text buffer. */
554     newdisp = snewn(newrows * (newcols + 1), TTYPE);
555     for (i = 0; i < newrows * (newcols + 1); i++)
556         newdisp[i] = ATTR_INVALID;
557     sfree(term->disptext);
558     term->disptext = newdisp;
559     term->dispcurs = NULL;
560
561     /* Make a new alternate screen. */
562     newalt = newtree234(NULL);
563     for (i = 0; i < newrows; i++) {
564         line = snewn(newcols + 2, TTYPE);
565         line[0] = newcols;
566         for (j = 0; j < newcols; j++)
567             line[j + 1] = term->erase_char;
568         line[newcols + 1] = LATTR_NORM;
569         addpos234(newalt, line, i);
570     }
571     if (term->alt_screen) {
572         while (NULL != (line = delpos234(term->alt_screen, 0)))
573             sfree(line);
574         freetree234(term->alt_screen);
575     }
576     term->alt_screen = newalt;
577     term->alt_sblines = 0;
578
579     term->tabs = sresize(term->tabs, newcols, unsigned char);
580     {
581         int i;
582         for (i = (term->cols > 0 ? term->cols : 0); i < newcols; i++)
583             term->tabs[i] = (i % 8 == 0 ? TRUE : FALSE);
584     }
585
586     /* Check that the cursor positions are still valid. */
587     if (term->savecurs.y < 0)
588         term->savecurs.y = 0;
589     if (term->savecurs.y >= newrows)
590         term->savecurs.y = newrows - 1;
591     if (term->curs.y < 0)
592         term->curs.y = 0;
593     if (term->curs.y >= newrows)
594         term->curs.y = newrows - 1;
595     if (term->curs.x >= newcols)
596         term->curs.x = newcols - 1;
597     term->alt_x = term->alt_y = 0;
598     term->wrapnext = term->alt_wnext = FALSE;
599
600     term->rows = newrows;
601     term->cols = newcols;
602     term->savelines = newsavelines;
603     fix_cpos;
604
605     swap_screen(term, save_alt_which, FALSE, FALSE);
606
607     update_sbar(term);
608     term_update(term);
609     if (term->resize_fn)
610         term->resize_fn(term->resize_ctx, term->cols, term->rows);
611 }
612
613 /*
614  * Hand a function and context pointer to the terminal which it can
615  * use to notify a back end of resizes.
616  */
617 void term_provide_resize_fn(Terminal *term,
618                             void (*resize_fn)(void *, int, int),
619                             void *resize_ctx)
620 {
621     term->resize_fn = resize_fn;
622     term->resize_ctx = resize_ctx;
623     if (term->cols > 0 && term->rows > 0)
624         resize_fn(resize_ctx, term->cols, term->rows);
625 }
626
627 /* Find the bottom line on the screen that has any content.
628  * If only the top line has content, returns 0.
629  * If no lines have content, return -1.
630  */ 
631 static int find_last_nonempty_line(Terminal * term, tree234 * screen)
632 {
633     int i;
634     for (i = count234(screen) - 1; i >= 0; i--) {
635         unsigned long *line = index234(screen, i);
636         int j;
637         int cols = line[0];
638         for (j = 0; j < cols; j++) {
639             if (line[j + 1] != term->erase_char) break;
640         }
641         if (j != cols) break;
642     }
643     return i;
644 }
645
646 /*
647  * Swap screens. If `reset' is TRUE and we have been asked to
648  * switch to the alternate screen, we must bring most of its
649  * configuration from the main screen and erase the contents of the
650  * alternate screen completely. (This is even true if we're already
651  * on it! Blame xterm.)
652  */
653 static void swap_screen(Terminal *term, int which, int reset, int keep_cur_pos)
654 {
655     int t;
656     tree234 *ttr;
657
658     if (!which)
659         reset = FALSE;                 /* do no weird resetting if which==0 */
660
661     if (which != term->alt_which) {
662         term->alt_which = which;
663
664         ttr = term->alt_screen;
665         term->alt_screen = term->screen;
666         term->screen = ttr;
667         term->alt_sblines = find_last_nonempty_line(term, term->alt_screen) + 1;
668         t = term->curs.x;
669         if (!reset && !keep_cur_pos)
670             term->curs.x = term->alt_x;
671         term->alt_x = t;
672         t = term->curs.y;
673         if (!reset && !keep_cur_pos)
674             term->curs.y = term->alt_y;
675         term->alt_y = t;
676         t = term->marg_t;
677         if (!reset) term->marg_t = term->alt_t;
678         term->alt_t = t;
679         t = term->marg_b;
680         if (!reset) term->marg_b = term->alt_b;
681         term->alt_b = t;
682         t = term->dec_om;
683         if (!reset) term->dec_om = term->alt_om;
684         term->alt_om = t;
685         t = term->wrap;
686         if (!reset) term->wrap = term->alt_wrap;
687         term->alt_wrap = t;
688         t = term->wrapnext;
689         if (!reset) term->wrapnext = term->alt_wnext;
690         term->alt_wnext = t;
691         t = term->insert;
692         if (!reset) term->insert = term->alt_ins;
693         term->alt_ins = t;
694         t = term->cset;
695         if (!reset) term->cset = term->alt_cset;
696         term->alt_cset = t;
697         t = term->utf;
698         if (!reset) term->utf = term->alt_utf;
699         term->alt_utf = t;
700         t = term->sco_acs;
701         if (!reset) term->sco_acs = term->alt_sco_acs;
702         term->alt_sco_acs = t;
703     }
704
705     if (reset && term->screen) {
706         /*
707          * Yes, this _is_ supposed to honour background-colour-erase.
708          */
709         erase_lots(term, FALSE, TRUE, TRUE);
710     }
711
712     /*
713      * This might not be possible if we're called during
714      * initialisation.
715      */
716     if (term->screen)
717         fix_cpos;
718 }
719
720 /*
721  * Update the scroll bar.
722  */
723 static void update_sbar(Terminal *term)
724 {
725     int nscroll = sblines(term);
726     set_sbar(term->frontend, nscroll + term->rows,
727              nscroll + term->disptop, term->rows);
728 }
729
730 /*
731  * Check whether the region bounded by the two pointers intersects
732  * the scroll region, and de-select the on-screen selection if so.
733  */
734 static void check_selection(Terminal *term, pos from, pos to)
735 {
736     if (poslt(from, term->selend) && poslt(term->selstart, to))
737         deselect(term);
738 }
739
740 /*
741  * Scroll the screen. (`lines' is +ve for scrolling forward, -ve
742  * for backward.) `sb' is TRUE if the scrolling is permitted to
743  * affect the scrollback buffer.
744  * 
745  * NB this function invalidates all pointers into lines of the
746  * screen data structures. In particular, you MUST call fix_cpos
747  * after calling scroll() and before doing anything else that
748  * uses the cpos shortcut pointer.
749  */
750 static void scroll(Terminal *term, int topline, int botline, int lines, int sb)
751 {
752     unsigned long *line, *line2;
753     int i, seltop, olddisptop, shift;
754
755     if (topline != 0 || term->alt_which != 0)
756         sb = FALSE;
757
758     olddisptop = term->disptop;
759     shift = lines;
760     if (lines < 0) {
761         while (lines < 0) {
762             line = delpos234(term->screen, botline);
763             line = resizeline(line, term->cols);
764             for (i = 0; i < term->cols; i++)
765                 line[i + 1] = term->erase_char;
766             line[term->cols + 1] = 0;
767             addpos234(term->screen, line, topline);
768
769             if (term->selstart.y >= topline && term->selstart.y <= botline) {
770                 term->selstart.y++;
771                 if (term->selstart.y > botline) {
772                     term->selstart.y = botline + 1;
773                     term->selstart.x = 0;
774                 }
775             }
776             if (term->selend.y >= topline && term->selend.y <= botline) {
777                 term->selend.y++;
778                 if (term->selend.y > botline) {
779                     term->selend.y = botline + 1;
780                     term->selend.x = 0;
781                 }
782             }
783
784             lines++;
785         }
786     } else {
787         while (lines > 0) {
788             line = delpos234(term->screen, topline);
789             if (sb && term->savelines > 0) {
790                 int sblen = count234(term->scrollback);
791                 /*
792                  * We must add this line to the scrollback. We'll
793                  * remove a line from the top of the scrollback to
794                  * replace it, or allocate a new one if the
795                  * scrollback isn't full.
796                  */
797                 if (sblen == term->savelines) {
798                     sblen--, line2 = delpos234(term->scrollback, 0);
799                 } else {
800                     line2 = snewn(term->cols + 2, TTYPE);
801                     line2[0] = term->cols;
802                     term->tempsblines += 1;
803                 }
804                 addpos234(term->scrollback, line, sblen);
805                 line = line2;
806
807                 /*
808                  * If the user is currently looking at part of the
809                  * scrollback, and they haven't enabled any options
810                  * that are going to reset the scrollback as a
811                  * result of this movement, then the chances are
812                  * they'd like to keep looking at the same line. So
813                  * we move their viewpoint at the same rate as the
814                  * scroll, at least until their viewpoint hits the
815                  * top end of the scrollback buffer, at which point
816                  * we don't have the choice any more.
817                  * 
818                  * Thanks to Jan Holmen Holsten for the idea and
819                  * initial implementation.
820                  */
821                 if (term->disptop > -term->savelines && term->disptop < 0)
822                     term->disptop--;
823             }
824             line = resizeline(line, term->cols);
825             for (i = 0; i < term->cols; i++)
826                 line[i + 1] = term->erase_char;
827             line[term->cols + 1] = LATTR_NORM;
828             addpos234(term->screen, line, botline);
829
830             /*
831              * If the selection endpoints move into the scrollback,
832              * we keep them moving until they hit the top. However,
833              * of course, if the line _hasn't_ moved into the
834              * scrollback then we don't do this, and cut them off
835              * at the top of the scroll region.
836              * 
837              * This applies to selstart and selend (for an existing
838              * selection), and also selanchor (for one being
839              * selected as we speak).
840              */
841             seltop = sb ? -term->savelines : topline;
842
843             if (term->selstart.y >= seltop &&
844                 term->selstart.y <= botline) {
845                 term->selstart.y--;
846                 if (term->selstart.y < seltop) {
847                     term->selstart.y = seltop;
848                     term->selstart.x = 0;
849                 }
850             }
851             if (term->selend.y >= seltop && term->selend.y <= botline) {
852                 term->selend.y--;
853                 if (term->selend.y < seltop) {
854                     term->selend.y = seltop;
855                     term->selend.x = 0;
856                 }
857             }
858             if (term->selanchor.y >= seltop && term->selanchor.y <= botline) {
859                 term->selanchor.y--;
860                 if (term->selanchor.y < seltop) {
861                     term->selanchor.y = seltop;
862                     term->selanchor.x = 0;
863                 }
864             }
865
866             lines--;
867         }
868     }
869 #ifdef OPTIMISE_SCROLL
870     shift += term->disptop - olddisptop;
871     if (shift < term->rows && shift > -term->rows && shift != 0)
872         scroll_display(term, topline, botline, shift);
873 #endif /* OPTIMISE_SCROLL */
874 }
875
876 #ifdef OPTIMISE_SCROLL
877 /*
878  * Add a scroll of a region on the screen into the pending scroll list.
879  * `lines' is +ve for scrolling forward, -ve for backward.
880  *
881  * If the scroll is on the same area as the last scroll in the list,
882  * merge them.
883  */
884 static void save_scroll(Terminal *term, int topline, int botline, int lines)
885 {
886     struct scrollregion *newscroll;
887     if (term->scrolltail &&
888         term->scrolltail->topline == topline && 
889         term->scrolltail->botline == botline) {
890         term->scrolltail->lines += lines;
891     } else {
892         newscroll = snew(struct scrollregion);
893         newscroll->topline = topline;
894         newscroll->botline = botline;
895         newscroll->lines = lines;
896         newscroll->next = NULL;
897
898         if (!term->scrollhead)
899             term->scrollhead = newscroll;
900         else
901             term->scrolltail->next = newscroll;
902         term->scrolltail = newscroll;
903     }
904 }
905
906 /*
907  * Scroll the physical display, and our conception of it in disptext.
908  */
909 static void scroll_display(Terminal *term, int topline, int botline, int lines)
910 {
911     unsigned long *start, *end;
912     int distance, size, i;
913
914     start = term->disptext + topline * (term->cols + 1);
915     end = term->disptext + (botline + 1) * (term->cols + 1);
916     distance = (lines > 0 ? lines : -lines) * (term->cols + 1);
917     size = end - start - distance;
918     if (lines > 0) {
919         memmove(start, start + distance, size * TSIZE);
920         if (term->dispcurs >= start + distance &&
921             term->dispcurs <= start + distance + size)
922             term->dispcurs -= distance;
923         for (i = 0; i < distance; i++)
924             (start + size)[i] |= ATTR_INVALID;
925     } else {
926         memmove(start + distance, start, size * TSIZE);
927         if (term->dispcurs >= start && term->dispcurs <= start + size)
928             term->dispcurs += distance;
929         for (i = 0; i < distance; i++)
930             start[i] |= ATTR_INVALID;
931     }
932     save_scroll(term, topline, botline, lines);
933 }
934 #endif /* OPTIMISE_SCROLL */
935
936 /*
937  * Move the cursor to a given position, clipping at boundaries. We
938  * may or may not want to clip at the scroll margin: marg_clip is 0
939  * not to, 1 to disallow _passing_ the margins, and 2 to disallow
940  * even _being_ outside the margins.
941  */
942 static void move(Terminal *term, int x, int y, int marg_clip)
943 {
944     if (x < 0)
945         x = 0;
946     if (x >= term->cols)
947         x = term->cols - 1;
948     if (marg_clip) {
949         if ((term->curs.y >= term->marg_t || marg_clip == 2) &&
950             y < term->marg_t)
951             y = term->marg_t;
952         if ((term->curs.y <= term->marg_b || marg_clip == 2) &&
953             y > term->marg_b)
954             y = term->marg_b;
955     }
956     if (y < 0)
957         y = 0;
958     if (y >= term->rows)
959         y = term->rows - 1;
960     term->curs.x = x;
961     term->curs.y = y;
962     fix_cpos;
963     term->wrapnext = FALSE;
964 }
965
966 /*
967  * Save or restore the cursor and SGR mode.
968  */
969 static void save_cursor(Terminal *term, int save)
970 {
971     if (save) {
972         term->savecurs = term->curs;
973         term->save_attr = term->curr_attr;
974         term->save_cset = term->cset;
975         term->save_utf = term->utf;
976         term->save_wnext = term->wrapnext;
977         term->save_csattr = term->cset_attr[term->cset];
978         term->save_sco_acs = term->sco_acs;
979     } else {
980         term->curs = term->savecurs;
981         /* Make sure the window hasn't shrunk since the save */
982         if (term->curs.x >= term->cols)
983             term->curs.x = term->cols - 1;
984         if (term->curs.y >= term->rows)
985             term->curs.y = term->rows - 1;
986
987         term->curr_attr = term->save_attr;
988         term->cset = term->save_cset;
989         term->utf = term->save_utf;
990         term->wrapnext = term->save_wnext;
991         /*
992          * wrapnext might reset to False if the x position is no
993          * longer at the rightmost edge.
994          */
995         if (term->wrapnext && term->curs.x < term->cols-1)
996             term->wrapnext = FALSE;
997         term->cset_attr[term->cset] = term->save_csattr;
998         term->sco_acs = term->save_sco_acs;
999         fix_cpos;
1000         if (term->use_bce)
1001             term->erase_char = (' ' | ATTR_ASCII |
1002                                 (term->curr_attr &
1003                                  (ATTR_FGMASK | ATTR_BGMASK)));
1004     }
1005 }
1006
1007 /*
1008  * This function is called before doing _anything_ which affects
1009  * only part of a line of text. It is used to mark the boundary
1010  * between two character positions, and it indicates that some sort
1011  * of effect is going to happen on only one side of that boundary.
1012  * 
1013  * The effect of this function is to check whether a CJK
1014  * double-width character is straddling the boundary, and to remove
1015  * it and replace it with two spaces if so. (Of course, one or
1016  * other of those spaces is then likely to be replaced with
1017  * something else again, as a result of whatever happens next.)
1018  * 
1019  * Also, if the boundary is at the right-hand _edge_ of the screen,
1020  * it implies something deliberate is being done to the rightmost
1021  * column position; hence we must clear LATTR_WRAPPED2.
1022  * 
1023  * The input to the function is the coordinates of the _second_
1024  * character of the pair.
1025  */
1026 static void check_boundary(Terminal *term, int x, int y)
1027 {
1028     unsigned long *ldata;
1029
1030     /* Validate input coordinates, just in case. */
1031     if (x == 0 || x > term->cols)
1032         return;
1033
1034     ldata = lineptr(y);
1035     if (x == term->cols) {
1036         ldata[x] &= ~LATTR_WRAPPED2;
1037     } else {
1038         if ((ldata[x] & (CHAR_MASK | CSET_MASK)) == UCSWIDE) {
1039             ldata[x-1] = ldata[x] =
1040                 (ldata[x-1] &~ (CHAR_MASK | CSET_MASK)) | ATTR_ASCII | ' ';
1041         }
1042     }
1043 }
1044
1045 /*
1046  * Erase a large portion of the screen: the whole screen, or the
1047  * whole line, or parts thereof.
1048  */
1049 static void erase_lots(Terminal *term,
1050                        int line_only, int from_begin, int to_end)
1051 {
1052     pos start, end;
1053     int erase_lattr;
1054     int erasing_lines_from_top = 0;
1055
1056     if (line_only) {
1057         start.y = term->curs.y;
1058         start.x = 0;
1059         end.y = term->curs.y + 1;
1060         end.x = 0;
1061         erase_lattr = FALSE;
1062     } else {
1063         start.y = 0;
1064         start.x = 0;
1065         end.y = term->rows;
1066         end.x = 0;
1067         erase_lattr = TRUE;
1068     }
1069     if (!from_begin) {
1070         start = term->curs;
1071     }
1072     if (!to_end) {
1073         end = term->curs;
1074         incpos(end);
1075     }
1076     if (!from_begin || !to_end)
1077         check_boundary(term, term->curs.x, term->curs.y);
1078     check_selection(term, start, end);
1079
1080     /* Clear screen also forces a full window redraw, just in case. */
1081     if (start.y == 0 && start.x == 0 && end.y == term->rows)
1082         term_invalidate(term);
1083
1084     /* Lines scrolled away shouldn't be brought back on if the terminal
1085      * resizes. */
1086     if (start.y == 0 && start.x == 0 && end.x == 0 && erase_lattr)
1087         erasing_lines_from_top = 1;
1088
1089     if (term->cfg.erase_to_scrollback && erasing_lines_from_top) {
1090         /* If it's a whole number of lines, starting at the top, and
1091          * we're fully erasing them, erase by scrolling and keep the
1092          * lines in the scrollback. */
1093         int scrolllines = end.y;
1094         if (end.y == term->rows) {
1095             /* Shrink until we find a non-empty row.*/
1096             scrolllines = find_last_nonempty_line(term, term->screen) + 1;
1097         }
1098         if (scrolllines > 0)
1099             scroll(term, 0, scrolllines - 1, scrolllines, TRUE);
1100         fix_cpos;
1101     } else {
1102         unsigned long *ldata = lineptr(start.y);
1103         while (poslt(start, end)) {
1104             if (start.x == term->cols) {
1105                 if (!erase_lattr)
1106                     ldata[start.x] &= ~(LATTR_WRAPPED | LATTR_WRAPPED2);
1107                 else
1108                     ldata[start.x] = LATTR_NORM;
1109             } else {
1110                 ldata[start.x] = term->erase_char;
1111             }
1112             if (incpos(start) && start.y < term->rows)
1113                 ldata = lineptr(start.y);
1114         }
1115     }
1116
1117     /* After an erase of lines from the top of the screen, we shouldn't
1118      * bring the lines back again if the terminal enlarges (since the user or
1119      * application has explictly thrown them away). */
1120     if (erasing_lines_from_top && !(term->alt_which))
1121         term->tempsblines = 0;
1122 }
1123
1124 /*
1125  * Insert or delete characters within the current line. n is +ve if
1126  * insertion is desired, and -ve for deletion.
1127  */
1128 static void insch(Terminal *term, int n)
1129 {
1130     int dir = (n < 0 ? -1 : +1);
1131     int m;
1132     pos cursplus;
1133     unsigned long *ldata;
1134
1135     n = (n < 0 ? -n : n);
1136     if (n > term->cols - term->curs.x)
1137         n = term->cols - term->curs.x;
1138     m = term->cols - term->curs.x - n;
1139     cursplus.y = term->curs.y;
1140     cursplus.x = term->curs.x + n;
1141     check_selection(term, term->curs, cursplus);
1142     check_boundary(term, term->curs.x, term->curs.y);
1143     if (dir < 0)
1144         check_boundary(term, term->curs.x + n, term->curs.y);
1145     ldata = lineptr(term->curs.y);
1146     if (dir < 0) {
1147         memmove(ldata + term->curs.x, ldata + term->curs.x + n, m * TSIZE);
1148         while (n--)
1149             ldata[term->curs.x + m++] = term->erase_char;
1150     } else {
1151         memmove(ldata + term->curs.x + n, ldata + term->curs.x, m * TSIZE);
1152         while (n--)
1153             ldata[term->curs.x + n] = term->erase_char;
1154     }
1155 }
1156
1157 /*
1158  * Toggle terminal mode `mode' to state `state'. (`query' indicates
1159  * whether the mode is a DEC private one or a normal one.)
1160  */
1161 static void toggle_mode(Terminal *term, int mode, int query, int state)
1162 {
1163     unsigned long ticks;
1164
1165     if (query)
1166         switch (mode) {
1167           case 1:                      /* application cursor keys */
1168             term->app_cursor_keys = state;
1169             break;
1170           case 2:                      /* VT52 mode */
1171             term->vt52_mode = !state;
1172             if (term->vt52_mode) {
1173                 term->blink_is_real = FALSE;
1174                 term->vt52_bold = FALSE;
1175             } else {
1176                 term->blink_is_real = term->cfg.blinktext;
1177             }
1178             break;
1179           case 3:                      /* 80/132 columns */
1180             deselect(term);
1181             if (!term->cfg.no_remote_resize)
1182                 request_resize(term->frontend, state ? 132 : 80, term->rows);
1183             term->reset_132 = state;
1184             term->alt_t = term->marg_t = 0;
1185             term->alt_b = term->marg_b = term->rows - 1;
1186             move(term, 0, 0, 0);
1187             erase_lots(term, FALSE, TRUE, TRUE);
1188             break;
1189           case 5:                      /* reverse video */
1190             /*
1191              * Toggle reverse video. If we receive an OFF within the
1192              * visual bell timeout period after an ON, we trigger an
1193              * effective visual bell, so that ESC[?5hESC[?5l will
1194              * always be an actually _visible_ visual bell.
1195              */
1196             ticks = GETTICKCOUNT();
1197             /* turn off a previous vbell to avoid inconsistencies */
1198             if (ticks - term->vbell_startpoint >= VBELL_TIMEOUT)
1199                 term->in_vbell = FALSE;
1200             if (term->rvideo && !state &&    /* we're turning it off... */
1201                 (ticks - term->rvbell_startpoint) < VBELL_TIMEOUT) {/*...soon*/
1202                 /* If there's no vbell timeout already, or this one lasts
1203                  * longer, replace vbell_timeout with ours. */
1204                 if (!term->in_vbell ||
1205                     (term->rvbell_startpoint - term->vbell_startpoint <
1206                      VBELL_TIMEOUT))
1207                     term->vbell_startpoint = term->rvbell_startpoint;
1208                 term->in_vbell = TRUE; /* may clear rvideo but set in_vbell */
1209             } else if (!term->rvideo && state) {
1210                 /* This is an ON, so we notice the time and save it. */
1211                 term->rvbell_startpoint = ticks;
1212             }
1213             term->rvideo = state;
1214             term->seen_disp_event = TRUE;
1215             if (state)
1216                 term_update(term);
1217             break;
1218           case 6:                      /* DEC origin mode */
1219             term->dec_om = state;
1220             break;
1221           case 7:                      /* auto wrap */
1222             term->wrap = state;
1223             break;
1224           case 8:                      /* auto key repeat */
1225             term->repeat_off = !state;
1226             break;
1227           case 10:                     /* set local edit mode */
1228             term->term_editing = state;
1229             if (term->ldisc)           /* cause ldisc to notice changes */
1230                 ldisc_send(term->ldisc, NULL, 0, 0);
1231             break;
1232           case 25:                     /* enable/disable cursor */
1233             compatibility2(OTHER, VT220);
1234             term->cursor_on = state;
1235             term->seen_disp_event = TRUE;
1236             break;
1237           case 47:                     /* alternate screen */
1238             compatibility(OTHER);
1239             deselect(term);
1240             swap_screen(term, term->cfg.no_alt_screen ? 0 : state, FALSE, FALSE);
1241             term->disptop = 0;
1242             break;
1243           case 1000:                   /* xterm mouse 1 */
1244             term->xterm_mouse = state ? 1 : 0;
1245             set_raw_mouse_mode(term->frontend, state);
1246             break;
1247           case 1002:                   /* xterm mouse 2 */
1248             term->xterm_mouse = state ? 2 : 0;
1249             set_raw_mouse_mode(term->frontend, state);
1250             break;
1251           case 1047:                   /* alternate screen */
1252             compatibility(OTHER);
1253             deselect(term);
1254             swap_screen(term, term->cfg.no_alt_screen ? 0 : state, TRUE, TRUE);
1255             term->disptop = 0;
1256             break;
1257           case 1048:                   /* save/restore cursor */
1258             save_cursor(term, state);
1259             if (!state) term->seen_disp_event = TRUE;
1260             break;
1261           case 1049:                   /* cursor & alternate screen */
1262             if (state)
1263                 save_cursor(term, state);
1264             if (!state) term->seen_disp_event = TRUE;
1265             compatibility(OTHER);
1266             deselect(term);
1267             swap_screen(term, term->cfg.no_alt_screen ? 0 : state, TRUE, FALSE);
1268             if (!state)
1269                 save_cursor(term, state);
1270             term->disptop = 0;
1271             break;
1272     } else
1273         switch (mode) {
1274           case 4:                      /* set insert mode */
1275             compatibility(VT102);
1276             term->insert = state;
1277             break;
1278           case 12:                     /* set echo mode */
1279             term->term_echoing = !state;
1280             if (term->ldisc)           /* cause ldisc to notice changes */
1281                 ldisc_send(term->ldisc, NULL, 0, 0);
1282             break;
1283           case 20:                     /* Return sends ... */
1284             term->cr_lf_return = state;
1285             break;
1286           case 34:                     /* Make cursor BIG */
1287             compatibility2(OTHER, VT220);
1288             term->big_cursor = !state;
1289         }
1290 }
1291
1292 /*
1293  * Process an OSC sequence: set window title or icon name.
1294  */
1295 static void do_osc(Terminal *term)
1296 {
1297     if (term->osc_w) {
1298         while (term->osc_strlen--)
1299             term->wordness[(unsigned char)
1300                 term->osc_string[term->osc_strlen]] = term->esc_args[0];
1301     } else {
1302         term->osc_string[term->osc_strlen] = '\0';
1303         switch (term->esc_args[0]) {
1304           case 0:
1305           case 1:
1306             if (!term->cfg.no_remote_wintitle)
1307                 set_icon(term->frontend, term->osc_string);
1308             if (term->esc_args[0] == 1)
1309                 break;
1310             /* fall through: parameter 0 means set both */
1311           case 2:
1312           case 21:
1313             if (!term->cfg.no_remote_wintitle)
1314                 set_title(term->frontend, term->osc_string);
1315             break;
1316         }
1317     }
1318 }
1319
1320 /*
1321  * ANSI printing routines.
1322  */
1323 static void term_print_setup(Terminal *term)
1324 {
1325     bufchain_clear(&term->printer_buf);
1326     term->print_job = printer_start_job(term->cfg.printer);
1327 }
1328 static void term_print_flush(Terminal *term)
1329 {
1330     void *data;
1331     int len;
1332     int size;
1333     while ((size = bufchain_size(&term->printer_buf)) > 5) {
1334         bufchain_prefix(&term->printer_buf, &data, &len);
1335         if (len > size-5)
1336             len = size-5;
1337         printer_job_data(term->print_job, data, len);
1338         bufchain_consume(&term->printer_buf, len);
1339     }
1340 }
1341 static void term_print_finish(Terminal *term)
1342 {
1343     void *data;
1344     int len, size;
1345     char c;
1346
1347     if (!term->printing && !term->only_printing)
1348         return;                        /* we need do nothing */
1349
1350     term_print_flush(term);
1351     while ((size = bufchain_size(&term->printer_buf)) > 0) {
1352         bufchain_prefix(&term->printer_buf, &data, &len);
1353         c = *(char *)data;
1354         if (c == '\033' || c == '\233') {
1355             bufchain_consume(&term->printer_buf, size);
1356             break;
1357         } else {
1358             printer_job_data(term->print_job, &c, 1);
1359             bufchain_consume(&term->printer_buf, 1);
1360         }
1361     }
1362     printer_finish_job(term->print_job);
1363     term->print_job = NULL;
1364     term->printing = term->only_printing = FALSE;
1365 }
1366
1367 /*
1368  * Remove everything currently in `inbuf' and stick it up on the
1369  * in-memory display. There's a big state machine in here to
1370  * process escape sequences...
1371  */
1372 void term_out(Terminal *term)
1373 {
1374     int c, unget;
1375     unsigned char localbuf[256], *chars;
1376     int nchars = 0;
1377
1378     unget = -1;
1379
1380     chars = NULL;                      /* placate compiler warnings */
1381     while (nchars > 0 || bufchain_size(&term->inbuf) > 0) {
1382         if (unget == -1) {
1383             if (nchars == 0) {
1384                 void *ret;
1385                 bufchain_prefix(&term->inbuf, &ret, &nchars);
1386                 if (nchars > sizeof(localbuf))
1387                     nchars = sizeof(localbuf);
1388                 memcpy(localbuf, ret, nchars);
1389                 bufchain_consume(&term->inbuf, nchars);
1390                 chars = localbuf;
1391                 assert(chars != NULL);
1392             }
1393             c = *chars++;
1394             nchars--;
1395
1396             /*
1397              * Optionally log the session traffic to a file. Useful for
1398              * debugging and possibly also useful for actual logging.
1399              */
1400             if (term->cfg.logtype == LGTYP_DEBUG && term->logctx)
1401                 logtraffic(term->logctx, (unsigned char) c, LGTYP_DEBUG);
1402         } else {
1403             c = unget;
1404             unget = -1;
1405         }
1406
1407         /* Note only VT220+ are 8-bit VT102 is seven bit, it shouldn't even
1408          * be able to display 8-bit characters, but I'll let that go 'cause
1409          * of i18n.
1410          */
1411
1412         /*
1413          * If we're printing, add the character to the printer
1414          * buffer.
1415          */
1416         if (term->printing) {
1417             bufchain_add(&term->printer_buf, &c, 1);
1418
1419             /*
1420              * If we're in print-only mode, we use a much simpler
1421              * state machine designed only to recognise the ESC[4i
1422              * termination sequence.
1423              */
1424             if (term->only_printing) {
1425                 if (c == '\033')
1426                     term->print_state = 1;
1427                 else if (c == (unsigned char)'\233')
1428                     term->print_state = 2;
1429                 else if (c == '[' && term->print_state == 1)
1430                     term->print_state = 2;
1431                 else if (c == '4' && term->print_state == 2)
1432                     term->print_state = 3;
1433                 else if (c == 'i' && term->print_state == 3)
1434                     term->print_state = 4;
1435                 else
1436                     term->print_state = 0;
1437                 if (term->print_state == 4) {
1438                     term_print_finish(term);
1439                 }
1440                 continue;
1441             }
1442         }
1443
1444         /* First see about all those translations. */
1445         if (term->termstate == TOPLEVEL) {
1446             if (in_utf(term))
1447                 switch (term->utf_state) {
1448                   case 0:
1449                     if (c < 0x80) {
1450                         /* UTF-8 must be stateless so we ignore iso2022. */
1451                         if (term->ucsdata->unitab_ctrl[c] != 0xFF) 
1452                              c = term->ucsdata->unitab_ctrl[c];
1453                         else c = ((unsigned char)c) | ATTR_ASCII;
1454                         break;
1455                     } else if ((c & 0xe0) == 0xc0) {
1456                         term->utf_size = term->utf_state = 1;
1457                         term->utf_char = (c & 0x1f);
1458                     } else if ((c & 0xf0) == 0xe0) {
1459                         term->utf_size = term->utf_state = 2;
1460                         term->utf_char = (c & 0x0f);
1461                     } else if ((c & 0xf8) == 0xf0) {
1462                         term->utf_size = term->utf_state = 3;
1463                         term->utf_char = (c & 0x07);
1464                     } else if ((c & 0xfc) == 0xf8) {
1465                         term->utf_size = term->utf_state = 4;
1466                         term->utf_char = (c & 0x03);
1467                     } else if ((c & 0xfe) == 0xfc) {
1468                         term->utf_size = term->utf_state = 5;
1469                         term->utf_char = (c & 0x01);
1470                     } else {
1471                         c = UCSERR;
1472                         break;
1473                     }
1474                     continue;
1475                   case 1:
1476                   case 2:
1477                   case 3:
1478                   case 4:
1479                   case 5:
1480                     if ((c & 0xC0) != 0x80) {
1481                         unget = c;
1482                         c = UCSERR;
1483                         term->utf_state = 0;
1484                         break;
1485                     }
1486                     term->utf_char = (term->utf_char << 6) | (c & 0x3f);
1487                     if (--term->utf_state)
1488                         continue;
1489
1490                     c = term->utf_char;
1491
1492                     /* Is somebody trying to be evil! */
1493                     if (c < 0x80 ||
1494                         (c < 0x800 && term->utf_size >= 2) ||
1495                         (c < 0x10000 && term->utf_size >= 3) ||
1496                         (c < 0x200000 && term->utf_size >= 4) ||
1497                         (c < 0x4000000 && term->utf_size >= 5))
1498                         c = UCSERR;
1499
1500                     /* Unicode line separator and paragraph separator are CR-LF */
1501                     if (c == 0x2028 || c == 0x2029)
1502                         c = 0x85;
1503
1504                     /* High controls are probably a Baaad idea too. */
1505                     if (c < 0xA0)
1506                         c = 0xFFFD;
1507
1508                     /* The UTF-16 surrogates are not nice either. */
1509                     /*       The standard give the option of decoding these: 
1510                      *       I don't want to! */
1511                     if (c >= 0xD800 && c < 0xE000)
1512                         c = UCSERR;
1513
1514                     /* ISO 10646 characters now limited to UTF-16 range. */
1515                     if (c > 0x10FFFF)
1516                         c = UCSERR;
1517
1518                     /* This is currently a TagPhobic application.. */
1519                     if (c >= 0xE0000 && c <= 0xE007F)
1520                         continue;
1521
1522                     /* U+FEFF is best seen as a null. */
1523                     if (c == 0xFEFF)
1524                         continue;
1525                     /* But U+FFFE is an error. */
1526                     if (c == 0xFFFE || c == 0xFFFF)
1527                         c = UCSERR;
1528
1529                     /* Oops this is a 16bit implementation */
1530                     if (c >= 0x10000)
1531                         c = 0xFFFD;
1532                     break;
1533             }
1534             /* Are we in the nasty ACS mode? Note: no sco in utf mode. */
1535             else if(term->sco_acs && 
1536                     (c!='\033' && c!='\012' && c!='\015' && c!='\b'))
1537             {
1538                if (term->sco_acs == 2) c |= 0x80;
1539                c |= ATTR_SCOACS;
1540             } else {
1541                 switch (term->cset_attr[term->cset]) {
1542                     /* 
1543                      * Linedraw characters are different from 'ESC ( B'
1544                      * only for a small range. For ones outside that
1545                      * range, make sure we use the same font as well as
1546                      * the same encoding.
1547                      */
1548                   case ATTR_LINEDRW:
1549                     if (term->ucsdata->unitab_ctrl[c] != 0xFF)
1550                         c = term->ucsdata->unitab_ctrl[c];
1551                     else
1552                         c = ((unsigned char) c) | ATTR_LINEDRW;
1553                     break;
1554
1555                   case ATTR_GBCHR:
1556                     /* If UK-ASCII, make the '#' a LineDraw Pound */
1557                     if (c == '#') {
1558                         c = '}' | ATTR_LINEDRW;
1559                         break;
1560                     }
1561                   /*FALLTHROUGH*/ case ATTR_ASCII:
1562                     if (term->ucsdata->unitab_ctrl[c] != 0xFF)
1563                         c = term->ucsdata->unitab_ctrl[c];
1564                     else
1565                         c = ((unsigned char) c) | ATTR_ASCII;
1566                     break;
1567                 case ATTR_SCOACS:
1568                     if (c>=' ') c = ((unsigned char)c) | ATTR_SCOACS;
1569                     break;
1570                 }
1571             }
1572         }
1573
1574         /* How about C1 controls ? */
1575         if ((c & -32) == 0x80 && term->termstate < DO_CTRLS &&
1576             !term->vt52_mode && has_compat(VT220)) {
1577             term->termstate = SEEN_ESC;
1578             term->esc_query = FALSE;
1579             c = '@' + (c & 0x1F);
1580         }
1581
1582         /* Or the GL control. */
1583         if (c == '\177' && term->termstate < DO_CTRLS && has_compat(OTHER)) {
1584             if (term->curs.x && !term->wrapnext)
1585                 term->curs.x--;
1586             term->wrapnext = FALSE;
1587             fix_cpos;
1588             if (!term->cfg.no_dbackspace)    /* destructive bksp might be disabled */
1589                 *term->cpos = (' ' | term->curr_attr | ATTR_ASCII);
1590         } else
1591             /* Or normal C0 controls. */
1592         if ((c & -32) == 0 && term->termstate < DO_CTRLS) {
1593             switch (c) {
1594               case '\005':             /* terminal type query */
1595                 /* Strictly speaking this is VT100 but a VT100 defaults to
1596                  * no response. Other terminals respond at their option.
1597                  *
1598                  * Don't put a CR in the default string as this tends to
1599                  * upset some weird software.
1600                  *
1601                  * An xterm returns "xterm" (5 characters)
1602                  */
1603                 compatibility(ANSIMIN);
1604                 if (term->ldisc) {
1605                     char abuf[256], *s, *d;
1606                     int state = 0;
1607                     for (s = term->cfg.answerback, d = abuf; *s; s++) {
1608                         if (state) {
1609                             if (*s >= 'a' && *s <= 'z')
1610                                 *d++ = (*s - ('a' - 1));
1611                             else if ((*s >= '@' && *s <= '_') ||
1612                                      *s == '?' || (*s & 0x80))
1613                                 *d++ = ('@' ^ *s);
1614                             else if (*s == '~')
1615                                 *d++ = '^';
1616                             state = 0;
1617                         } else if (*s == '^') {
1618                             state = 1;
1619                         } else
1620                             *d++ = *s;
1621                     }
1622                     lpage_send(term->ldisc, DEFAULT_CODEPAGE,
1623                                abuf, d - abuf, 0);
1624                 }
1625                 break;
1626               case '\007':
1627                 {
1628                     struct beeptime *newbeep;
1629                     unsigned long ticks;
1630
1631                     ticks = GETTICKCOUNT();
1632
1633                     if (!term->beep_overloaded) {
1634                         newbeep = snew(struct beeptime);
1635                         newbeep->ticks = ticks;
1636                         newbeep->next = NULL;
1637                         if (!term->beephead)
1638                             term->beephead = newbeep;
1639                         else
1640                             term->beeptail->next = newbeep;
1641                         term->beeptail = newbeep;
1642                         term->nbeeps++;
1643                     }
1644
1645                     /*
1646                      * Throw out any beeps that happened more than
1647                      * t seconds ago.
1648                      */
1649                     while (term->beephead &&
1650                            term->beephead->ticks < ticks - term->cfg.bellovl_t) {
1651                         struct beeptime *tmp = term->beephead;
1652                         term->beephead = tmp->next;
1653                         sfree(tmp);
1654                         if (!term->beephead)
1655                             term->beeptail = NULL;
1656                         term->nbeeps--;
1657                     }
1658
1659                     if (term->cfg.bellovl && term->beep_overloaded &&
1660                         ticks - term->lastbeep >= (unsigned)term->cfg.bellovl_s) {
1661                         /*
1662                          * If we're currently overloaded and the
1663                          * last beep was more than s seconds ago,
1664                          * leave overload mode.
1665                          */
1666                         term->beep_overloaded = FALSE;
1667                     } else if (term->cfg.bellovl && !term->beep_overloaded &&
1668                                term->nbeeps >= term->cfg.bellovl_n) {
1669                         /*
1670                          * Now, if we have n or more beeps
1671                          * remaining in the queue, go into overload
1672                          * mode.
1673                          */
1674                         term->beep_overloaded = TRUE;
1675                     }
1676                     term->lastbeep = ticks;
1677
1678                     /*
1679                      * Perform an actual beep if we're not overloaded.
1680                      */
1681                     if (!term->cfg.bellovl || !term->beep_overloaded) {
1682                         beep(term->frontend, term->cfg.beep);
1683                         if (term->cfg.beep == BELL_VISUAL) {
1684                             term->in_vbell = TRUE;
1685                             term->vbell_startpoint = ticks;
1686                             term_update(term);
1687                         }
1688                     }
1689                     term->disptop = 0;
1690                 }
1691                 break;
1692               case '\b':
1693                 if (term->curs.x == 0 &&
1694                     (term->curs.y == 0 || term->wrap == 0))
1695                     /* do nothing */ ;
1696                 else if (term->curs.x == 0 && term->curs.y > 0)
1697                     term->curs.x = term->cols - 1, term->curs.y--;
1698                 else if (term->wrapnext)
1699                     term->wrapnext = FALSE;
1700                 else
1701                     term->curs.x--;
1702                 fix_cpos;
1703                 term->seen_disp_event = TRUE;
1704                 break;
1705               case '\016':
1706                 compatibility(VT100);
1707                 term->cset = 1;
1708                 break;
1709               case '\017':
1710                 compatibility(VT100);
1711                 term->cset = 0;
1712                 break;
1713               case '\033':
1714                 if (term->vt52_mode)
1715                     term->termstate = VT52_ESC;
1716                 else {
1717                     compatibility(ANSIMIN);
1718                     term->termstate = SEEN_ESC;
1719                     term->esc_query = FALSE;
1720                 }
1721                 break;
1722               case '\015':
1723                 term->curs.x = 0;
1724                 term->wrapnext = FALSE;
1725                 fix_cpos;
1726                 term->seen_disp_event = TRUE;
1727                 term->paste_hold = 0;
1728                 if (term->logctx)
1729                     logtraffic(term->logctx, (unsigned char) c, LGTYP_ASCII);
1730                 break;
1731               case '\014':
1732                 if (has_compat(SCOANSI)) {
1733                     move(term, 0, 0, 0);
1734                     erase_lots(term, FALSE, FALSE, TRUE);
1735                     term->disptop = 0;
1736                     term->wrapnext = FALSE;
1737                     term->seen_disp_event = 1;
1738                     break;
1739                 }
1740               case '\013':
1741                 compatibility(VT100);
1742               case '\012':
1743                 if (term->curs.y == term->marg_b)
1744                     scroll(term, term->marg_t, term->marg_b, 1, TRUE);
1745                 else if (term->curs.y < term->rows - 1)
1746                     term->curs.y++;
1747                 if (term->cfg.lfhascr)
1748                     term->curs.x = 0;
1749                 fix_cpos;
1750                 term->wrapnext = FALSE;
1751                 term->seen_disp_event = 1;
1752                 term->paste_hold = 0;
1753                 if (term->logctx)
1754                     logtraffic(term->logctx, (unsigned char) c, LGTYP_ASCII);
1755                 break;
1756               case '\t':
1757                 {
1758                     pos old_curs = term->curs;
1759                     unsigned long *ldata = lineptr(term->curs.y);
1760
1761                     do {
1762                         term->curs.x++;
1763                     } while (term->curs.x < term->cols - 1 &&
1764                              !term->tabs[term->curs.x]);
1765
1766                     if ((ldata[term->cols] & LATTR_MODE) != LATTR_NORM) {
1767                         if (term->curs.x >= term->cols / 2)
1768                             term->curs.x = term->cols / 2 - 1;
1769                     } else {
1770                         if (term->curs.x >= term->cols)
1771                             term->curs.x = term->cols - 1;
1772                     }
1773
1774                     fix_cpos;
1775                     check_selection(term, old_curs, term->curs);
1776                 }
1777                 term->seen_disp_event = TRUE;
1778                 break;
1779             }
1780         } else
1781             switch (term->termstate) {
1782               case TOPLEVEL:
1783                 /* Only graphic characters get this far;
1784                  * ctrls are stripped above */
1785                 if (term->wrapnext && term->wrap) {
1786                     term->cpos[1] |= LATTR_WRAPPED;
1787                     if (term->curs.y == term->marg_b)
1788                         scroll(term, term->marg_t, term->marg_b, 1, TRUE);
1789                     else if (term->curs.y < term->rows - 1)
1790                         term->curs.y++;
1791                     term->curs.x = 0;
1792                     fix_cpos;
1793                     term->wrapnext = FALSE;
1794                 }
1795                 if (term->insert)
1796                     insch(term, 1);
1797                 if (term->selstate != NO_SELECTION) {
1798                     pos cursplus = term->curs;
1799                     incpos(cursplus);
1800                     check_selection(term, term->curs, cursplus);
1801                 }
1802                 if (((c & CSET_MASK) == ATTR_ASCII || (c & CSET_MASK) == 0) &&
1803                     term->logctx)
1804                     logtraffic(term->logctx, (unsigned char) c, LGTYP_ASCII);
1805                 {
1806                     int width = 0;
1807                     if (DIRECT_CHAR(c))
1808                         width = 1;
1809                     if (!width)
1810                         width = wcwidth((wchar_t) c);
1811                     switch (width) {
1812                       case 2:
1813                         /*
1814                          * If we're about to display a double-width
1815                          * character starting in the rightmost
1816                          * column, then we do something special
1817                          * instead. We must print a space in the
1818                          * last column of the screen, then wrap;
1819                          * and we also set LATTR_WRAPPED2 which
1820                          * instructs subsequent cut-and-pasting not
1821                          * only to splice this line to the one
1822                          * after it, but to ignore the space in the
1823                          * last character position as well.
1824                          * (Because what was actually output to the
1825                          * terminal was presumably just a sequence
1826                          * of CJK characters, and we don't want a
1827                          * space to be pasted in the middle of
1828                          * those just because they had the
1829                          * misfortune to start in the wrong parity
1830                          * column. xterm concurs.)
1831                          */
1832                         check_boundary(term, term->curs.x, term->curs.y);
1833                         check_boundary(term, term->curs.x+2, term->curs.y);
1834                         if (term->curs.x == term->cols-1) {
1835                             *term->cpos++ = ATTR_ASCII | ' ' | term->curr_attr;
1836                             *term->cpos |= LATTR_WRAPPED | LATTR_WRAPPED2;
1837                             if (term->curs.y == term->marg_b)
1838                                 scroll(term, term->marg_t, term->marg_b,
1839                                        1, TRUE);
1840                             else if (term->curs.y < term->rows - 1)
1841                                 term->curs.y++;
1842                             term->curs.x = 0;
1843                             fix_cpos;
1844                             /* Now we must check_boundary again, of course. */
1845                             check_boundary(term, term->curs.x, term->curs.y);
1846                             check_boundary(term, term->curs.x+2, term->curs.y);
1847                         }
1848                         *term->cpos++ = c | term->curr_attr;
1849                         *term->cpos++ = UCSWIDE | term->curr_attr;
1850                         term->curs.x++;
1851                         break;
1852                       case 1:
1853                         check_boundary(term, term->curs.x, term->curs.y);
1854                         check_boundary(term, term->curs.x+1, term->curs.y);
1855                         *term->cpos++ = c | term->curr_attr;
1856                         break;
1857                       default:
1858                         continue;
1859                     }
1860                 }
1861                 term->curs.x++;
1862                 if (term->curs.x == term->cols) {
1863                     term->cpos--;
1864                     term->curs.x--;
1865                     term->wrapnext = TRUE;
1866                     if (term->wrap && term->vt52_mode) {
1867                         term->cpos[1] |= LATTR_WRAPPED;
1868                         if (term->curs.y == term->marg_b)
1869                             scroll(term, term->marg_t, term->marg_b, 1, TRUE);
1870                         else if (term->curs.y < term->rows - 1)
1871                             term->curs.y++;
1872                         term->curs.x = 0;
1873                         fix_cpos;
1874                         term->wrapnext = FALSE;
1875                     }
1876                 }
1877                 term->seen_disp_event = 1;
1878                 break;
1879
1880               case OSC_MAYBE_ST:
1881                 /*
1882                  * This state is virtually identical to SEEN_ESC, with the
1883                  * exception that we have an OSC sequence in the pipeline,
1884                  * and _if_ we see a backslash, we process it.
1885                  */
1886                 if (c == '\\') {
1887                     do_osc(term);
1888                     term->termstate = TOPLEVEL;
1889                     break;
1890                 }
1891                 /* else fall through */
1892               case SEEN_ESC:
1893                 if (c >= ' ' && c <= '/') {
1894                     if (term->esc_query)
1895                         term->esc_query = -1;
1896                     else
1897                         term->esc_query = c;
1898                     break;
1899                 }
1900                 term->termstate = TOPLEVEL;
1901                 switch (ANSI(c, term->esc_query)) {
1902                   case '[':            /* enter CSI mode */
1903                     term->termstate = SEEN_CSI;
1904                     term->esc_nargs = 1;
1905                     term->esc_args[0] = ARG_DEFAULT;
1906                     term->esc_query = FALSE;
1907                     break;
1908                   case ']':            /* xterm escape sequences */
1909                     /* Compatibility is nasty here, xterm, linux, decterm yuk! */
1910                     compatibility(OTHER);
1911                     term->termstate = SEEN_OSC;
1912                     term->esc_args[0] = 0;
1913                     break;
1914                   case '7':            /* save cursor */
1915                     compatibility(VT100);
1916                     save_cursor(term, TRUE);
1917                     break;
1918                   case '8':            /* restore cursor */
1919                     compatibility(VT100);
1920                     save_cursor(term, FALSE);
1921                     term->seen_disp_event = TRUE;
1922                     break;
1923                   case '=':
1924                     compatibility(VT100);
1925                     term->app_keypad_keys = TRUE;
1926                     break;
1927                   case '>':
1928                     compatibility(VT100);
1929                     term->app_keypad_keys = FALSE;
1930                     break;
1931                   case 'D':            /* exactly equivalent to LF */
1932                     compatibility(VT100);
1933                     if (term->curs.y == term->marg_b)
1934                         scroll(term, term->marg_t, term->marg_b, 1, TRUE);
1935                     else if (term->curs.y < term->rows - 1)
1936                         term->curs.y++;
1937                     fix_cpos;
1938                     term->wrapnext = FALSE;
1939                     term->seen_disp_event = TRUE;
1940                     break;
1941                   case 'E':            /* exactly equivalent to CR-LF */
1942                     compatibility(VT100);
1943                     term->curs.x = 0;
1944                     if (term->curs.y == term->marg_b)
1945                         scroll(term, term->marg_t, term->marg_b, 1, TRUE);
1946                     else if (term->curs.y < term->rows - 1)
1947                         term->curs.y++;
1948                     fix_cpos;
1949                     term->wrapnext = FALSE;
1950                     term->seen_disp_event = TRUE;
1951                     break;
1952                   case 'M':            /* reverse index - backwards LF */
1953                     compatibility(VT100);
1954                     if (term->curs.y == term->marg_t)
1955                         scroll(term, term->marg_t, term->marg_b, -1, TRUE);
1956                     else if (term->curs.y > 0)
1957                         term->curs.y--;
1958                     fix_cpos;
1959                     term->wrapnext = FALSE;
1960                     term->seen_disp_event = TRUE;
1961                     break;
1962                   case 'Z':            /* terminal type query */
1963                     compatibility(VT100);
1964                     if (term->ldisc)
1965                         ldisc_send(term->ldisc, term->id_string,
1966                                    strlen(term->id_string), 0);
1967                     break;
1968                   case 'c':            /* restore power-on settings */
1969                     compatibility(VT100);
1970                     power_on(term);
1971                     if (term->ldisc)   /* cause ldisc to notice changes */
1972                         ldisc_send(term->ldisc, NULL, 0, 0);
1973                     if (term->reset_132) {
1974                         if (!term->cfg.no_remote_resize)
1975                             request_resize(term->frontend, 80, term->rows);
1976                         term->reset_132 = 0;
1977                     }
1978                     fix_cpos;
1979                     term->disptop = 0;
1980                     term->seen_disp_event = TRUE;
1981                     break;
1982                   case 'H':            /* set a tab */
1983                     compatibility(VT100);
1984                     term->tabs[term->curs.x] = TRUE;
1985                     break;
1986
1987                   case ANSI('8', '#'):  /* ESC # 8 fills screen with Es :-) */
1988                     compatibility(VT100);
1989                     {
1990                         unsigned long *ldata;
1991                         int i, j;
1992                         pos scrtop, scrbot;
1993
1994                         for (i = 0; i < term->rows; i++) {
1995                             ldata = lineptr(i);
1996                             for (j = 0; j < term->cols; j++)
1997                                 ldata[j] = ATTR_DEFAULT | 'E';
1998                             ldata[term->cols] = 0;
1999                         }
2000                         term->disptop = 0;
2001                         term->seen_disp_event = TRUE;
2002                         scrtop.x = scrtop.y = 0;
2003                         scrbot.x = 0;
2004                         scrbot.y = term->rows;
2005                         check_selection(term, scrtop, scrbot);
2006                     }
2007                     break;
2008
2009                   case ANSI('3', '#'):
2010                   case ANSI('4', '#'):
2011                   case ANSI('5', '#'):
2012                   case ANSI('6', '#'):
2013                     compatibility(VT100);
2014                     {
2015                         unsigned long nlattr;
2016                         unsigned long *ldata;
2017                         switch (ANSI(c, term->esc_query)) {
2018                           case ANSI('3', '#'):
2019                             nlattr = LATTR_TOP;
2020                             break;
2021                           case ANSI('4', '#'):
2022                             nlattr = LATTR_BOT;
2023                             break;
2024                           case ANSI('5', '#'):
2025                             nlattr = LATTR_NORM;
2026                             break;
2027                           default: /* spiritually case ANSI('6', '#'): */
2028                             nlattr = LATTR_WIDE;
2029                             break;
2030                         }
2031                         ldata = lineptr(term->curs.y);
2032                         ldata[term->cols] &= ~LATTR_MODE;
2033                         ldata[term->cols] |= nlattr;
2034                     }
2035                     break;
2036
2037                   case ANSI('A', '('):
2038                     compatibility(VT100);
2039                     if (!term->cfg.no_remote_charset)
2040                         term->cset_attr[0] = ATTR_GBCHR;
2041                     break;
2042                   case ANSI('B', '('):
2043                     compatibility(VT100);
2044                     if (!term->cfg.no_remote_charset)
2045                         term->cset_attr[0] = ATTR_ASCII;
2046                     break;
2047                   case ANSI('0', '('):
2048                     compatibility(VT100);
2049                     if (!term->cfg.no_remote_charset)
2050                         term->cset_attr[0] = ATTR_LINEDRW;
2051                     break;
2052                   case ANSI('U', '('): 
2053                     compatibility(OTHER);
2054                     if (!term->cfg.no_remote_charset)
2055                         term->cset_attr[0] = ATTR_SCOACS; 
2056                     break;
2057
2058                   case ANSI('A', ')'):
2059                     compatibility(VT100);
2060                     if (!term->cfg.no_remote_charset)
2061                         term->cset_attr[1] = ATTR_GBCHR;
2062                     break;
2063                   case ANSI('B', ')'):
2064                     compatibility(VT100);
2065                     if (!term->cfg.no_remote_charset)
2066                         term->cset_attr[1] = ATTR_ASCII;
2067                     break;
2068                   case ANSI('0', ')'):
2069                     compatibility(VT100);
2070                     if (!term->cfg.no_remote_charset)
2071                         term->cset_attr[1] = ATTR_LINEDRW;
2072                     break;
2073                   case ANSI('U', ')'): 
2074                     compatibility(OTHER);
2075                     if (!term->cfg.no_remote_charset)
2076                         term->cset_attr[1] = ATTR_SCOACS; 
2077                     break;
2078
2079                   case ANSI('8', '%'):  /* Old Linux code */
2080                   case ANSI('G', '%'):
2081                     compatibility(OTHER);
2082                     if (!term->cfg.no_remote_charset)
2083                         term->utf = 1;
2084                     break;
2085                   case ANSI('@', '%'):
2086                     compatibility(OTHER);
2087                     if (!term->cfg.no_remote_charset)
2088                         term->utf = 0;
2089                     break;
2090                 }
2091                 break;
2092               case SEEN_CSI:
2093                 term->termstate = TOPLEVEL;  /* default */
2094                 if (isdigit(c)) {
2095                     if (term->esc_nargs <= ARGS_MAX) {
2096                         if (term->esc_args[term->esc_nargs - 1] == ARG_DEFAULT)
2097                             term->esc_args[term->esc_nargs - 1] = 0;
2098                         term->esc_args[term->esc_nargs - 1] =
2099                             10 * term->esc_args[term->esc_nargs - 1] + c - '0';
2100                     }
2101                     term->termstate = SEEN_CSI;
2102                 } else if (c == ';') {
2103                     if (++term->esc_nargs <= ARGS_MAX)
2104                         term->esc_args[term->esc_nargs - 1] = ARG_DEFAULT;
2105                     term->termstate = SEEN_CSI;
2106                 } else if (c < '@') {
2107                     if (term->esc_query)
2108                         term->esc_query = -1;
2109                     else if (c == '?')
2110                         term->esc_query = TRUE;
2111                     else
2112                         term->esc_query = c;
2113                     term->termstate = SEEN_CSI;
2114                 } else
2115                     switch (ANSI(c, term->esc_query)) {
2116                       case 'A':       /* move up N lines */
2117                         move(term, term->curs.x,
2118                              term->curs.y - def(term->esc_args[0], 1), 1);
2119                         term->seen_disp_event = TRUE;
2120                         break;
2121                       case 'e':       /* move down N lines */
2122                         compatibility(ANSI);
2123                         /* FALLTHROUGH */
2124                       case 'B':
2125                         move(term, term->curs.x,
2126                              term->curs.y + def(term->esc_args[0], 1), 1);
2127                         term->seen_disp_event = TRUE;
2128                         break;
2129                       case ANSI('c', '>'):      /* report xterm version */
2130                         compatibility(OTHER);
2131                         /* this reports xterm version 136 so that VIM can
2132                            use the drag messages from the mouse reporting */
2133                         if (term->ldisc)
2134                             ldisc_send(term->ldisc, "\033[>0;136;0c", 11, 0);
2135                         break;
2136                       case 'a':       /* move right N cols */
2137                         compatibility(ANSI);
2138                         /* FALLTHROUGH */
2139                       case 'C':
2140                         move(term, term->curs.x + def(term->esc_args[0], 1),
2141                              term->curs.y, 1);
2142                         term->seen_disp_event = TRUE;
2143                         break;
2144                       case 'D':       /* move left N cols */
2145                         move(term, term->curs.x - def(term->esc_args[0], 1),
2146                              term->curs.y, 1);
2147                         term->seen_disp_event = TRUE;
2148                         break;
2149                       case 'E':       /* move down N lines and CR */
2150                         compatibility(ANSI);
2151                         move(term, 0,
2152                              term->curs.y + def(term->esc_args[0], 1), 1);
2153                         term->seen_disp_event = TRUE;
2154                         break;
2155                       case 'F':       /* move up N lines and CR */
2156                         compatibility(ANSI);
2157                         move(term, 0,
2158                              term->curs.y - def(term->esc_args[0], 1), 1);
2159                         term->seen_disp_event = TRUE;
2160                         break;
2161                       case 'G':
2162                       case '`':       /* set horizontal posn */
2163                         compatibility(ANSI);
2164                         move(term, def(term->esc_args[0], 1) - 1,
2165                              term->curs.y, 0);
2166                         term->seen_disp_event = TRUE;
2167                         break;
2168                       case 'd':       /* set vertical posn */
2169                         compatibility(ANSI);
2170                         move(term, term->curs.x,
2171                              ((term->dec_om ? term->marg_t : 0) +
2172                               def(term->esc_args[0], 1) - 1),
2173                              (term->dec_om ? 2 : 0));
2174                         term->seen_disp_event = TRUE;
2175                         break;
2176                       case 'H':
2177                       case 'f':       /* set horz and vert posns at once */
2178                         if (term->esc_nargs < 2)
2179                             term->esc_args[1] = ARG_DEFAULT;
2180                         move(term, def(term->esc_args[1], 1) - 1,
2181                              ((term->dec_om ? term->marg_t : 0) +
2182                               def(term->esc_args[0], 1) - 1),
2183                              (term->dec_om ? 2 : 0));
2184                         term->seen_disp_event = TRUE;
2185                         break;
2186                       case 'J':       /* erase screen or parts of it */
2187                         {
2188                             unsigned int i = def(term->esc_args[0], 0) + 1;
2189                             if (i > 3)
2190                                 i = 0;
2191                             erase_lots(term, FALSE, !!(i & 2), !!(i & 1));
2192                         }
2193                         term->disptop = 0;
2194                         term->seen_disp_event = TRUE;
2195                         break;
2196                       case 'K':       /* erase line or parts of it */
2197                         {
2198                             unsigned int i = def(term->esc_args[0], 0) + 1;
2199                             if (i > 3)
2200                                 i = 0;
2201                             erase_lots(term, TRUE, !!(i & 2), !!(i & 1));
2202                         }
2203                         term->seen_disp_event = TRUE;
2204                         break;
2205                       case 'L':       /* insert lines */
2206                         compatibility(VT102);
2207                         if (term->curs.y <= term->marg_b)
2208                             scroll(term, term->curs.y, term->marg_b,
2209                                    -def(term->esc_args[0], 1), FALSE);
2210                         fix_cpos;
2211                         term->seen_disp_event = TRUE;
2212                         break;
2213                       case 'M':       /* delete lines */
2214                         compatibility(VT102);
2215                         if (term->curs.y <= term->marg_b)
2216                             scroll(term, term->curs.y, term->marg_b,
2217                                    def(term->esc_args[0], 1),
2218                                    TRUE);
2219                         fix_cpos;
2220                         term->seen_disp_event = TRUE;
2221                         break;
2222                       case '@':       /* insert chars */
2223                         /* XXX VTTEST says this is vt220, vt510 manual says vt102 */
2224                         compatibility(VT102);
2225                         insch(term, def(term->esc_args[0], 1));
2226                         term->seen_disp_event = TRUE;
2227                         break;
2228                       case 'P':       /* delete chars */
2229                         compatibility(VT102);
2230                         insch(term, -def(term->esc_args[0], 1));
2231                         term->seen_disp_event = TRUE;
2232                         break;
2233                       case 'c':       /* terminal type query */
2234                         compatibility(VT100);
2235                         /* This is the response for a VT102 */
2236                         if (term->ldisc)
2237                             ldisc_send(term->ldisc, term->id_string,
2238                                        strlen(term->id_string), 0);
2239                         break;
2240                       case 'n':       /* cursor position query */
2241                         if (term->ldisc) {
2242                             if (term->esc_args[0] == 6) {
2243                                 char buf[32];
2244                                 sprintf(buf, "\033[%d;%dR", term->curs.y + 1,
2245                                         term->curs.x + 1);
2246                                 ldisc_send(term->ldisc, buf, strlen(buf), 0);
2247                             } else if (term->esc_args[0] == 5) {
2248                                 ldisc_send(term->ldisc, "\033[0n", 4, 0);
2249                             }
2250                         }
2251                         break;
2252                       case 'h':       /* toggle modes to high */
2253                       case ANSI_QUE('h'):
2254                         compatibility(VT100);
2255                         {
2256                             int i;
2257                             for (i = 0; i < term->esc_nargs; i++)
2258                                 toggle_mode(term, term->esc_args[i],
2259                                             term->esc_query, TRUE);
2260                         }
2261                         break;
2262                       case 'i':
2263                       case ANSI_QUE('i'):
2264                         compatibility(VT100);
2265                         {
2266                             if (term->esc_nargs != 1) break;
2267                             if (term->esc_args[0] == 5 && *term->cfg.printer) {
2268                                 term->printing = TRUE;
2269                                 term->only_printing = !term->esc_query;
2270                                 term->print_state = 0;
2271                                 term_print_setup(term);
2272                             } else if (term->esc_args[0] == 4 &&
2273                                        term->printing) {
2274                                 term_print_finish(term);
2275                             }
2276                         }
2277                         break;                  
2278                       case 'l':       /* toggle modes to low */
2279                       case ANSI_QUE('l'):
2280                         compatibility(VT100);
2281                         {
2282                             int i;
2283                             for (i = 0; i < term->esc_nargs; i++)
2284                                 toggle_mode(term, term->esc_args[i],
2285                                             term->esc_query, FALSE);
2286                         }
2287                         break;
2288                       case 'g':       /* clear tabs */
2289                         compatibility(VT100);
2290                         if (term->esc_nargs == 1) {
2291                             if (term->esc_args[0] == 0) {
2292                                 term->tabs[term->curs.x] = FALSE;
2293                             } else if (term->esc_args[0] == 3) {
2294                                 int i;
2295                                 for (i = 0; i < term->cols; i++)
2296                                     term->tabs[i] = FALSE;
2297                             }
2298                         }
2299                         break;
2300                       case 'r':       /* set scroll margins */
2301                         compatibility(VT100);
2302                         if (term->esc_nargs <= 2) {
2303                             int top, bot;
2304                             top = def(term->esc_args[0], 1) - 1;
2305                             bot = (term->esc_nargs <= 1
2306                                    || term->esc_args[1] == 0 ?
2307                                    term->rows :
2308                                    def(term->esc_args[1], term->rows)) - 1;
2309                             if (bot >= term->rows)
2310                                 bot = term->rows - 1;
2311                             /* VTTEST Bug 9 - if region is less than 2 lines
2312                              * don't change region.
2313                              */
2314                             if (bot - top > 0) {
2315                                 term->marg_t = top;
2316                                 term->marg_b = bot;
2317                                 term->curs.x = 0;
2318                                 /*
2319                                  * I used to think the cursor should be
2320                                  * placed at the top of the newly marginned
2321                                  * area. Apparently not: VMS TPU falls over
2322                                  * if so.
2323                                  *
2324                                  * Well actually it should for
2325                                  * Origin mode - RDB
2326                                  */
2327                                 term->curs.y = (term->dec_om ?
2328                                                 term->marg_t : 0);
2329                                 fix_cpos;
2330                                 term->seen_disp_event = TRUE;
2331                             }
2332                         }
2333                         break;
2334                       case 'm':       /* set graphics rendition */
2335                         {
2336                             /* 
2337                              * A VT100 without the AVO only had one
2338                              * attribute, either underline or
2339                              * reverse video depending on the
2340                              * cursor type, this was selected by
2341                              * CSI 7m.
2342                              *
2343                              * case 2:
2344                              *  This is sometimes DIM, eg on the
2345                              *  GIGI and Linux
2346                              * case 8:
2347                              *  This is sometimes INVIS various ANSI.
2348                              * case 21:
2349                              *  This like 22 disables BOLD, DIM and INVIS
2350                              *
2351                              * The ANSI colours appear on any
2352                              * terminal that has colour (obviously)
2353                              * but the interaction between sgr0 and
2354                              * the colours varies but is usually
2355                              * related to the background colour
2356                              * erase item. The interaction between
2357                              * colour attributes and the mono ones
2358                              * is also very implementation
2359                              * dependent.
2360                              *
2361                              * The 39 and 49 attributes are likely
2362                              * to be unimplemented.
2363                              */
2364                             int i;
2365                             for (i = 0; i < term->esc_nargs; i++) {
2366                                 switch (def(term->esc_args[i], 0)) {
2367                                   case 0:       /* restore defaults */
2368                                     term->curr_attr = ATTR_DEFAULT;
2369                                     break;
2370                                   case 1:       /* enable bold */
2371                                     compatibility(VT100AVO);
2372                                     term->curr_attr |= ATTR_BOLD;
2373                                     break;
2374                                   case 21:      /* (enable double underline) */
2375                                     compatibility(OTHER);
2376                                   case 4:       /* enable underline */
2377                                     compatibility(VT100AVO);
2378                                     term->curr_attr |= ATTR_UNDER;
2379                                     break;
2380                                   case 5:       /* enable blink */
2381                                     compatibility(VT100AVO);
2382                                     term->curr_attr |= ATTR_BLINK;
2383                                     break;
2384                                   case 7:       /* enable reverse video */
2385                                     term->curr_attr |= ATTR_REVERSE;
2386                                     break;
2387                                   case 10:      /* SCO acs off */
2388                                     compatibility(SCOANSI);
2389                                     if (term->cfg.no_remote_charset) break;
2390                                     term->sco_acs = 0; break;
2391                                   case 11:      /* SCO acs on */
2392                                     compatibility(SCOANSI);
2393                                     if (term->cfg.no_remote_charset) break;
2394                                     term->sco_acs = 1; break;
2395                                   case 12:      /* SCO acs on, |0x80 */
2396                                     compatibility(SCOANSI);
2397                                     if (term->cfg.no_remote_charset) break;
2398                                     term->sco_acs = 2; break;
2399                                   case 22:      /* disable bold */
2400                                     compatibility2(OTHER, VT220);
2401                                     term->curr_attr &= ~ATTR_BOLD;
2402                                     break;
2403                                   case 24:      /* disable underline */
2404                                     compatibility2(OTHER, VT220);
2405                                     term->curr_attr &= ~ATTR_UNDER;
2406                                     break;
2407                                   case 25:      /* disable blink */
2408                                     compatibility2(OTHER, VT220);
2409                                     term->curr_attr &= ~ATTR_BLINK;
2410                                     break;
2411                                   case 27:      /* disable reverse video */
2412                                     compatibility2(OTHER, VT220);
2413                                     term->curr_attr &= ~ATTR_REVERSE;
2414                                     break;
2415                                   case 30:
2416                                   case 31:
2417                                   case 32:
2418                                   case 33:
2419                                   case 34:
2420                                   case 35:
2421                                   case 36:
2422                                   case 37:
2423                                     /* foreground */
2424                                     term->curr_attr &= ~ATTR_FGMASK;
2425                                     term->curr_attr |=
2426                                         (term->esc_args[i] - 30)<<ATTR_FGSHIFT;
2427                                     break;
2428                                   case 90:
2429                                   case 91:
2430                                   case 92:
2431                                   case 93:
2432                                   case 94:
2433                                   case 95:
2434                                   case 96:
2435                                   case 97:
2436                                     /* xterm-style bright foreground */
2437                                     term->curr_attr &= ~ATTR_FGMASK;
2438                                     term->curr_attr |=
2439                                         ((term->esc_args[i] - 90 + 16)
2440                                          << ATTR_FGSHIFT);
2441                                     break;
2442                                   case 39:      /* default-foreground */
2443                                     term->curr_attr &= ~ATTR_FGMASK;
2444                                     term->curr_attr |= ATTR_DEFFG;
2445                                     break;
2446                                   case 40:
2447                                   case 41:
2448                                   case 42:
2449                                   case 43:
2450                                   case 44:
2451                                   case 45:
2452                                   case 46:
2453                                   case 47:
2454                                     /* background */
2455                                     term->curr_attr &= ~ATTR_BGMASK;
2456                                     term->curr_attr |=
2457                                         (term->esc_args[i] - 40)<<ATTR_BGSHIFT;
2458                                     break;
2459                                   case 100:
2460                                   case 101:
2461                                   case 102:
2462                                   case 103:
2463                                   case 104:
2464                                   case 105:
2465                                   case 106:
2466                                   case 107:
2467                                     /* xterm-style bright background */
2468                                     term->curr_attr &= ~ATTR_BGMASK;
2469                                     term->curr_attr |=
2470                                         ((term->esc_args[i] - 100 + 16)
2471                                          << ATTR_BGSHIFT);
2472                                     break;
2473                                   case 49:      /* default-background */
2474                                     term->curr_attr &= ~ATTR_BGMASK;
2475                                     term->curr_attr |= ATTR_DEFBG;
2476                                     break;
2477                                 }
2478                             }
2479                             if (term->use_bce)
2480                                 term->erase_char = (' ' | ATTR_ASCII |
2481                                                     (term->curr_attr & 
2482                                                      (ATTR_FGMASK |
2483                                                       ATTR_BGMASK)));
2484                         }
2485                         break;
2486                       case 's':       /* save cursor */
2487                         save_cursor(term, TRUE);
2488                         break;
2489                       case 'u':       /* restore cursor */
2490                         save_cursor(term, FALSE);
2491                         term->seen_disp_event = TRUE;
2492                         break;
2493                       case 't':       /* set page size - ie window height */
2494                         /*
2495                          * VT340/VT420 sequence DECSLPP, DEC only allows values
2496                          *  24/25/36/48/72/144 other emulators (eg dtterm) use
2497                          * illegal values (eg first arg 1..9) for window changing 
2498                          * and reports.
2499                          */
2500                         if (term->esc_nargs <= 1
2501                             && (term->esc_args[0] < 1 ||
2502                                 term->esc_args[0] >= 24)) {
2503                             compatibility(VT340TEXT);
2504                             if (!term->cfg.no_remote_resize)
2505                                 request_resize(term->frontend, term->cols,
2506                                                def(term->esc_args[0], 24));
2507                             deselect(term);
2508                         } else if (term->esc_nargs >= 1 &&
2509                                    term->esc_args[0] >= 1 &&
2510                                    term->esc_args[0] < 24) {
2511                             compatibility(OTHER);
2512
2513                             switch (term->esc_args[0]) {
2514                                 int x, y, len;
2515                                 char buf[80], *p;
2516                               case 1:
2517                                 set_iconic(term->frontend, FALSE);
2518                                 break;
2519                               case 2:
2520                                 set_iconic(term->frontend, TRUE);
2521                                 break;
2522                               case 3:
2523                                 if (term->esc_nargs >= 3) {
2524                                     if (!term->cfg.no_remote_resize)
2525                                         move_window(term->frontend,
2526                                                     def(term->esc_args[1], 0),
2527                                                     def(term->esc_args[2], 0));
2528                                 }
2529                                 break;
2530                               case 4:
2531                                 /* We should resize the window to a given
2532                                  * size in pixels here, but currently our
2533                                  * resizing code isn't healthy enough to
2534                                  * manage it. */
2535                                 break;
2536                               case 5:
2537                                 /* move to top */
2538                                 set_zorder(term->frontend, TRUE);
2539                                 break;
2540                               case 6:
2541                                 /* move to bottom */
2542                                 set_zorder(term->frontend, FALSE);
2543                                 break;
2544                               case 7:
2545                                 refresh_window(term->frontend);
2546                                 break;
2547                               case 8:
2548                                 if (term->esc_nargs >= 3) {
2549                                     if (!term->cfg.no_remote_resize)
2550                                         request_resize(term->frontend,
2551                                                        def(term->esc_args[2], term->cfg.width),
2552                                                        def(term->esc_args[1], term->cfg.height));
2553                                 }
2554                                 break;
2555                               case 9:
2556                                 if (term->esc_nargs >= 2)
2557                                     set_zoomed(term->frontend,
2558                                                term->esc_args[1] ?
2559                                                TRUE : FALSE);
2560                                 break;
2561                               case 11:
2562                                 if (term->ldisc)
2563                                     ldisc_send(term->ldisc,
2564                                                is_iconic(term->frontend) ?
2565                                                "\033[1t" : "\033[2t", 4, 0);
2566                                 break;
2567                               case 13:
2568                                 if (term->ldisc) {
2569                                     get_window_pos(term->frontend, &x, &y);
2570                                     len = sprintf(buf, "\033[3;%d;%dt", x, y);
2571                                     ldisc_send(term->ldisc, buf, len, 0);
2572                                 }
2573                                 break;
2574                               case 14:
2575                                 if (term->ldisc) {
2576                                     get_window_pixels(term->frontend, &x, &y);
2577                                     len = sprintf(buf, "\033[4;%d;%dt", x, y);
2578                                     ldisc_send(term->ldisc, buf, len, 0);
2579                                 }
2580                                 break;
2581                               case 18:
2582                                 if (term->ldisc) {
2583                                     len = sprintf(buf, "\033[8;%d;%dt",
2584                                                   term->rows, term->cols);
2585                                     ldisc_send(term->ldisc, buf, len, 0);
2586                                 }
2587                                 break;
2588                               case 19:
2589                                 /*
2590                                  * Hmmm. Strictly speaking we
2591                                  * should return `the size of the
2592                                  * screen in characters', but
2593                                  * that's not easy: (a) window
2594                                  * furniture being what it is it's
2595                                  * hard to compute, and (b) in
2596                                  * resize-font mode maximising the
2597                                  * window wouldn't change the
2598                                  * number of characters. *shrug*. I
2599                                  * think we'll ignore it for the
2600                                  * moment and see if anyone
2601                                  * complains, and then ask them
2602                                  * what they would like it to do.
2603                                  */
2604                                 break;
2605                               case 20:
2606                                 if (term->ldisc) {
2607                                     p = get_window_title(term->frontend, TRUE);
2608                                     len = strlen(p);
2609                                     ldisc_send(term->ldisc, "\033]L", 3, 0);
2610                                     ldisc_send(term->ldisc, p, len, 0);
2611                                     ldisc_send(term->ldisc, "\033\\", 2, 0);
2612                                 }
2613                                 break;
2614                               case 21:
2615                                 if (term->ldisc) {
2616                                     p = get_window_title(term->frontend,FALSE);
2617                                     len = strlen(p);
2618                                     ldisc_send(term->ldisc, "\033]l", 3, 0);
2619                                     ldisc_send(term->ldisc, p, len, 0);
2620                                     ldisc_send(term->ldisc, "\033\\", 2, 0);
2621                                 }
2622                                 break;
2623                             }
2624                         }
2625                         break;
2626                       case 'S':
2627                         compatibility(SCOANSI);
2628                         scroll(term, term->marg_t, term->marg_b,
2629                                def(term->esc_args[0], 1), TRUE);
2630                         fix_cpos;
2631                         term->wrapnext = FALSE;
2632                         term->seen_disp_event = TRUE;
2633                         break;
2634                       case 'T':
2635                         compatibility(SCOANSI);
2636                         scroll(term, term->marg_t, term->marg_b,
2637                                -def(term->esc_args[0], 1), TRUE);
2638                         fix_cpos;
2639                         term->wrapnext = FALSE;
2640                         term->seen_disp_event = TRUE;
2641                         break;
2642                       case ANSI('|', '*'):
2643                         /* VT420 sequence DECSNLS
2644                          * Set number of lines on screen
2645                          * VT420 uses VGA like hardware and can support any size in
2646                          * reasonable range (24..49 AIUI) with no default specified.
2647                          */
2648                         compatibility(VT420);
2649                         if (term->esc_nargs == 1 && term->esc_args[0] > 0) {
2650                             if (!term->cfg.no_remote_resize)
2651                                 request_resize(term->frontend, term->cols,
2652                                                def(term->esc_args[0],
2653                                                    term->cfg.height));
2654                             deselect(term);
2655                         }
2656                         break;
2657                       case ANSI('|', '$'):
2658                         /* VT340/VT420 sequence DECSCPP
2659                          * Set number of columns per page
2660                          * Docs imply range is only 80 or 132, but I'll allow any.
2661                          */
2662                         compatibility(VT340TEXT);
2663                         if (term->esc_nargs <= 1) {
2664                             if (!term->cfg.no_remote_resize)
2665                                 request_resize(term->frontend,
2666                                                def(term->esc_args[0],
2667                                                    term->cfg.width), term->rows);
2668                             deselect(term);
2669                         }
2670                         break;
2671                       case 'X':       /* write N spaces w/o moving cursor */
2672                         /* XXX VTTEST says this is vt220, vt510 manual says vt100 */
2673                         compatibility(ANSIMIN);
2674                         {
2675                             int n = def(term->esc_args[0], 1);
2676                             pos cursplus;
2677                             unsigned long *p = term->cpos;
2678                             if (n > term->cols - term->curs.x)
2679                                 n = term->cols - term->curs.x;
2680                             cursplus = term->curs;
2681                             cursplus.x += n;
2682                             check_boundary(term, term->curs.x, term->curs.y);
2683                             check_boundary(term, term->curs.x+n, term->curs.y);
2684                             check_selection(term, term->curs, cursplus);
2685                             while (n--)
2686                                 *p++ = term->erase_char;
2687                             term->seen_disp_event = TRUE;
2688                         }
2689                         break;
2690                       case 'x':       /* report terminal characteristics */
2691                         compatibility(VT100);
2692                         if (term->ldisc) {
2693                             char buf[32];
2694                             int i = def(term->esc_args[0], 0);
2695                             if (i == 0 || i == 1) {
2696                                 strcpy(buf, "\033[2;1;1;112;112;1;0x");
2697                                 buf[2] += i;
2698                                 ldisc_send(term->ldisc, buf, 20, 0);
2699                             }
2700                         }
2701                         break;
2702                       case 'Z':         /* BackTab for xterm */
2703                         compatibility(OTHER);
2704                         {
2705                             int i = def(term->esc_args[0], 1);
2706                             pos old_curs = term->curs;
2707
2708                             for(;i>0 && term->curs.x>0; i--) {
2709                                 do {
2710                                     term->curs.x--;
2711                                 } while (term->curs.x >0 &&
2712                                          !term->tabs[term->curs.x]);
2713                             }
2714                             fix_cpos;
2715                             check_selection(term, old_curs, term->curs);
2716                         }
2717                         break;
2718                       case ANSI('L', '='):
2719                         compatibility(OTHER);
2720                         term->use_bce = (term->esc_args[0] <= 0);
2721                         term->erase_char = ERASE_CHAR;
2722                         if (term->use_bce)
2723                             term->erase_char = (' ' | ATTR_ASCII |
2724                                                 (term->curr_attr & 
2725                                                  (ATTR_FGMASK | ATTR_BGMASK)));
2726                         break;
2727                       case ANSI('E', '='):
2728                         compatibility(OTHER);
2729                         term->blink_is_real = (term->esc_args[0] >= 1);
2730                         break;
2731                       case ANSI('p', '"'):
2732                         /*
2733                          * Allow the host to make this emulator a
2734                          * 'perfect' VT102. This first appeared in
2735                          * the VT220, but we do need to get back to
2736                          * PuTTY mode so I won't check it.
2737                          *
2738                          * The arg in 40..42,50 are a PuTTY extension.
2739                          * The 2nd arg, 8bit vs 7bit is not checked.
2740                          *
2741                          * Setting VT102 mode should also change
2742                          * the Fkeys to generate PF* codes as a
2743                          * real VT102 has no Fkeys. The VT220 does
2744                          * this, F11..F13 become ESC,BS,LF other
2745                          * Fkeys send nothing.
2746                          *
2747                          * Note ESC c will NOT change this!
2748                          */
2749
2750                         switch (term->esc_args[0]) {
2751                           case 61:
2752                             term->compatibility_level &= ~TM_VTXXX;
2753                             term->compatibility_level |= TM_VT102;
2754                             break;
2755                           case 62:
2756                             term->compatibility_level &= ~TM_VTXXX;
2757                             term->compatibility_level |= TM_VT220;
2758                             break;
2759
2760                           default:
2761                             if (term->esc_args[0] > 60 &&
2762                                 term->esc_args[0] < 70)
2763                                 term->compatibility_level |= TM_VTXXX;
2764                             break;
2765
2766                           case 40:
2767                             term->compatibility_level &= TM_VTXXX;
2768                             break;
2769                           case 41:
2770                             term->compatibility_level = TM_PUTTY;
2771                             break;
2772                           case 42:
2773                             term->compatibility_level = TM_SCOANSI;
2774                             break;
2775
2776                           case ARG_DEFAULT:
2777                             term->compatibility_level = TM_PUTTY;
2778                             break;
2779                           case 50:
2780                             break;
2781                         }
2782
2783                         /* Change the response to CSI c */
2784                         if (term->esc_args[0] == 50) {
2785                             int i;
2786                             char lbuf[64];
2787                             strcpy(term->id_string, "\033[?");
2788                             for (i = 1; i < term->esc_nargs; i++) {
2789                                 if (i != 1)
2790                                     strcat(term->id_string, ";");
2791                                 sprintf(lbuf, "%d", term->esc_args[i]);
2792                                 strcat(term->id_string, lbuf);
2793                             }
2794                             strcat(term->id_string, "c");
2795                         }
2796 #if 0
2797                         /* Is this a good idea ? 
2798                          * Well we should do a soft reset at this point ...
2799                          */
2800                         if (!has_compat(VT420) && has_compat(VT100)) {
2801                             if (!term->cfg.no_remote_resize) {
2802                                 if (term->reset_132)
2803                                     request_resize(132, 24);
2804                                 else
2805                                     request_resize(80, 24);
2806                             }
2807                         }
2808 #endif
2809                         break;
2810                     }
2811                 break;
2812               case SEEN_OSC:
2813                 term->osc_w = FALSE;
2814                 switch (c) {
2815                   case 'P':            /* Linux palette sequence */
2816                     term->termstate = SEEN_OSC_P;
2817                     term->osc_strlen = 0;
2818                     break;
2819                   case 'R':            /* Linux palette reset */
2820                     palette_reset(term->frontend);
2821                     term_invalidate(term);
2822                     term->termstate = TOPLEVEL;
2823                     break;
2824                   case 'W':            /* word-set */
2825                     term->termstate = SEEN_OSC_W;
2826                     term->osc_w = TRUE;
2827                     break;
2828                   case '0':
2829                   case '1':
2830                   case '2':
2831                   case '3':
2832                   case '4':
2833                   case '5':
2834                   case '6':
2835                   case '7':
2836                   case '8':
2837                   case '9':
2838                     term->esc_args[0] = 10 * term->esc_args[0] + c - '0';
2839                     break;
2840                   case 'L':
2841                     /*
2842                      * Grotty hack to support xterm and DECterm title
2843                      * sequences concurrently.
2844                      */
2845                     if (term->esc_args[0] == 2) {
2846                         term->esc_args[0] = 1;
2847                         break;
2848                     }
2849                     /* else fall through */
2850                   default:
2851                     term->termstate = OSC_STRING;
2852                     term->osc_strlen = 0;
2853                 }
2854                 break;
2855               case OSC_STRING:
2856                 /*
2857                  * This OSC stuff is EVIL. It takes just one character to get into
2858                  * sysline mode and it's not initially obvious how to get out.
2859                  * So I've added CR and LF as string aborts.
2860                  * This shouldn't effect compatibility as I believe embedded 
2861                  * control characters are supposed to be interpreted (maybe?) 
2862                  * and they don't display anything useful anyway.
2863                  *
2864                  * -- RDB
2865                  */
2866                 if (c == '\012' || c == '\015') {
2867                     term->termstate = TOPLEVEL;
2868                 } else if (c == 0234 || c == '\007') {
2869                     /*
2870                      * These characters terminate the string; ST and BEL
2871                      * terminate the sequence and trigger instant
2872                      * processing of it, whereas ESC goes back to SEEN_ESC
2873                      * mode unless it is followed by \, in which case it is
2874                      * synonymous with ST in the first place.
2875                      */
2876                     do_osc(term);
2877                     term->termstate = TOPLEVEL;
2878                 } else if (c == '\033')
2879                     term->termstate = OSC_MAYBE_ST;
2880                 else if (term->osc_strlen < OSC_STR_MAX)
2881                     term->osc_string[term->osc_strlen++] = c;
2882                 break;
2883               case SEEN_OSC_P:
2884                 {
2885                     int max = (term->osc_strlen == 0 ? 21 : 16);
2886                     int val;
2887                     if (c >= '0' && c <= '9')
2888                         val = c - '0';
2889                     else if (c >= 'A' && c <= 'A' + max - 10)
2890                         val = c - 'A' + 10;
2891                     else if (c >= 'a' && c <= 'a' + max - 10)
2892                         val = c - 'a' + 10;
2893                     else {
2894                         term->termstate = TOPLEVEL;
2895                         break;
2896                     }
2897                     term->osc_string[term->osc_strlen++] = val;
2898                     if (term->osc_strlen >= 7) {
2899                         palette_set(term->frontend, term->osc_string[0],
2900                                     term->osc_string[1] * 16 + term->osc_string[2],
2901                                     term->osc_string[3] * 16 + term->osc_string[4],
2902                                     term->osc_string[5] * 16 + term->osc_string[6]);
2903                         term_invalidate(term);
2904                         term->termstate = TOPLEVEL;
2905                     }
2906                 }
2907                 break;
2908               case SEEN_OSC_W:
2909                 switch (c) {
2910                   case '0':
2911                   case '1':
2912                   case '2':
2913                   case '3':
2914                   case '4':
2915                   case '5':
2916                   case '6':
2917                   case '7':
2918                   case '8':
2919                   case '9':
2920                     term->esc_args[0] = 10 * term->esc_args[0] + c - '0';
2921                     break;
2922                   default:
2923                     term->termstate = OSC_STRING;
2924                     term->osc_strlen = 0;
2925                 }
2926                 break;
2927               case VT52_ESC:
2928                 term->termstate = TOPLEVEL;
2929                 term->seen_disp_event = TRUE;
2930                 switch (c) {
2931                   case 'A':
2932                     move(term, term->curs.x, term->curs.y - 1, 1);
2933                     break;
2934                   case 'B':
2935                     move(term, term->curs.x, term->curs.y + 1, 1);
2936                     break;
2937                   case 'C':
2938                     move(term, term->curs.x + 1, term->curs.y, 1);
2939                     break;
2940                   case 'D':
2941                     move(term, term->curs.x - 1, term->curs.y, 1);
2942                     break;
2943                     /*
2944                      * From the VT100 Manual
2945                      * NOTE: The special graphics characters in the VT100
2946                      *       are different from those in the VT52
2947                      *
2948                      * From VT102 manual:
2949                      *       137 _  Blank             - Same
2950                      *       140 `  Reserved          - Humm.
2951                      *       141 a  Solid rectangle   - Similar
2952                      *       142 b  1/                - Top half of fraction for the
2953                      *       143 c  3/                - subscript numbers below.
2954                      *       144 d  5/
2955                      *       145 e  7/
2956                      *       146 f  Degrees           - Same
2957                      *       147 g  Plus or minus     - Same
2958                      *       150 h  Right arrow
2959                      *       151 i  Ellipsis (dots)
2960                      *       152 j  Divide by
2961                      *       153 k  Down arrow
2962                      *       154 l  Bar at scan 0
2963                      *       155 m  Bar at scan 1
2964                      *       156 n  Bar at scan 2
2965                      *       157 o  Bar at scan 3     - Similar
2966                      *       160 p  Bar at scan 4     - Similar
2967                      *       161 q  Bar at scan 5     - Similar
2968                      *       162 r  Bar at scan 6     - Same
2969                      *       163 s  Bar at scan 7     - Similar
2970                      *       164 t  Subscript 0
2971                      *       165 u  Subscript 1
2972                      *       166 v  Subscript 2
2973                      *       167 w  Subscript 3
2974                      *       170 x  Subscript 4
2975                      *       171 y  Subscript 5
2976                      *       172 z  Subscript 6
2977                      *       173 {  Subscript 7
2978                      *       174 |  Subscript 8
2979                      *       175 }  Subscript 9
2980                      *       176 ~  Paragraph
2981                      *
2982                      */
2983                   case 'F':
2984                     term->cset_attr[term->cset = 0] = ATTR_LINEDRW;
2985                     break;
2986                   case 'G':
2987                     term->cset_attr[term->cset = 0] = ATTR_ASCII;
2988                     break;
2989                   case 'H':
2990                     move(term, 0, 0, 0);
2991                     break;
2992                   case 'I':
2993                     if (term->curs.y == 0)
2994                         scroll(term, 0, term->rows - 1, -1, TRUE);
2995                     else if (term->curs.y > 0)
2996                         term->curs.y--;
2997                     fix_cpos;
2998                     term->wrapnext = FALSE;
2999                     break;
3000                   case 'J':
3001                     erase_lots(term, FALSE, FALSE, TRUE);
3002                     term->disptop = 0;
3003                     break;
3004                   case 'K':
3005                     erase_lots(term, TRUE, FALSE, TRUE);
3006                     break;
3007 #if 0
3008                   case 'V':
3009                     /* XXX Print cursor line */
3010                     break;
3011                   case 'W':
3012                     /* XXX Start controller mode */
3013                     break;
3014                   case 'X':
3015                     /* XXX Stop controller mode */
3016                     break;
3017 #endif
3018                   case 'Y':
3019                     term->termstate = VT52_Y1;
3020                     break;
3021                   case 'Z':
3022                     if (term->ldisc)
3023                         ldisc_send(term->ldisc, "\033/Z", 3, 0);
3024                     break;
3025                   case '=':
3026                     term->app_keypad_keys = TRUE;
3027                     break;
3028                   case '>':
3029                     term->app_keypad_keys = FALSE;
3030                     break;
3031                   case '<':
3032                     /* XXX This should switch to VT100 mode not current or default
3033                      *     VT mode. But this will only have effect in a VT220+
3034                      *     emulation.
3035                      */
3036                     term->vt52_mode = FALSE;
3037                     term->blink_is_real = term->cfg.blinktext;
3038                     break;
3039 #if 0
3040                   case '^':
3041                     /* XXX Enter auto print mode */
3042                     break;
3043                   case '_':
3044                     /* XXX Exit auto print mode */
3045                     break;
3046                   case ']':
3047                     /* XXX Print screen */
3048                     break;
3049 #endif
3050
3051 #ifdef VT52_PLUS
3052                   case 'E':
3053                     /* compatibility(ATARI) */
3054                     move(term, 0, 0, 0);
3055                     erase_lots(term, FALSE, FALSE, TRUE);
3056                     term->disptop = 0;
3057                     break;
3058                   case 'L':
3059                     /* compatibility(ATARI) */
3060                     if (term->curs.y <= term->marg_b)
3061                         scroll(term, term->curs.y, term->marg_b, -1, FALSE);
3062                     break;
3063                   case 'M':
3064                     /* compatibility(ATARI) */
3065                     if (term->curs.y <= term->marg_b)
3066                         scroll(term, term->curs.y, term->marg_b, 1, TRUE);
3067                     break;
3068                   case 'b':
3069                     /* compatibility(ATARI) */
3070                     term->termstate = VT52_FG;
3071                     break;
3072                   case 'c':
3073                     /* compatibility(ATARI) */
3074                     term->termstate = VT52_BG;
3075                     break;
3076                   case 'd':
3077                     /* compatibility(ATARI) */
3078                     erase_lots(term, FALSE, TRUE, FALSE);
3079                     term->disptop = 0;
3080                     break;
3081                   case 'e':
3082                     /* compatibility(ATARI) */
3083                     term->cursor_on = TRUE;
3084                     break;
3085                   case 'f':
3086                     /* compatibility(ATARI) */
3087                     term->cursor_on = FALSE;
3088                     break;
3089                     /* case 'j': Save cursor position - broken on ST */
3090                     /* case 'k': Restore cursor position */
3091                   case 'l':
3092                     /* compatibility(ATARI) */
3093                     erase_lots(term, TRUE, TRUE, TRUE);
3094                     term->curs.x = 0;
3095                     term->wrapnext = FALSE;
3096                     fix_cpos;
3097                     break;
3098                   case 'o':
3099                     /* compatibility(ATARI) */
3100                     erase_lots(term, TRUE, TRUE, FALSE);
3101                     break;
3102                   case 'p':
3103                     /* compatibility(ATARI) */
3104                     term->curr_attr |= ATTR_REVERSE;
3105                     break;
3106                   case 'q':
3107                     /* compatibility(ATARI) */
3108                     term->curr_attr &= ~ATTR_REVERSE;
3109                     break;
3110                   case 'v':            /* wrap Autowrap on - Wyse style */
3111                     /* compatibility(ATARI) */
3112                     term->wrap = 1;
3113                     break;
3114                   case 'w':            /* Autowrap off */
3115                     /* compatibility(ATARI) */
3116                     term->wrap = 0;
3117                     break;
3118
3119                   case 'R':
3120                     /* compatibility(OTHER) */
3121                     term->vt52_bold = FALSE;
3122                     term->curr_attr = ATTR_DEFAULT;
3123                     if (term->use_bce)
3124                         term->erase_char = (' ' | ATTR_ASCII |
3125                                             (term->curr_attr & 
3126                                              (ATTR_FGMASK | ATTR_BGMASK)));
3127                     break;
3128                   case 'S':
3129                     /* compatibility(VI50) */
3130                     term->curr_attr |= ATTR_UNDER;
3131                     break;
3132                   case 'W':
3133                     /* compatibility(VI50) */
3134                     term->curr_attr &= ~ATTR_UNDER;
3135                     break;
3136                   case 'U':
3137                     /* compatibility(VI50) */
3138                     term->vt52_bold = TRUE;
3139                     term->curr_attr |= ATTR_BOLD;
3140                     break;
3141                   case 'T':
3142                     /* compatibility(VI50) */
3143                     term->vt52_bold = FALSE;
3144                     term->curr_attr &= ~ATTR_BOLD;
3145                     break;
3146 #endif
3147                 }
3148                 break;
3149               case VT52_Y1:
3150                 term->termstate = VT52_Y2;
3151                 move(term, term->curs.x, c - ' ', 0);
3152                 break;
3153               case VT52_Y2:
3154                 term->termstate = TOPLEVEL;
3155                 move(term, c - ' ', term->curs.y, 0);
3156                 break;
3157
3158 #ifdef VT52_PLUS
3159               case VT52_FG:
3160                 term->termstate = TOPLEVEL;
3161                 term->curr_attr &= ~ATTR_FGMASK;
3162                 term->curr_attr &= ~ATTR_BOLD;
3163                 term->curr_attr |= (c & 0x7) << ATTR_FGSHIFT;
3164                 if ((c & 0x8) || term->vt52_bold)
3165                     term->curr_attr |= ATTR_BOLD;
3166
3167                 if (term->use_bce)
3168                     term->erase_char = (' ' | ATTR_ASCII |
3169                                         (term->curr_attr &
3170                                          (ATTR_FGMASK | ATTR_BGMASK)));
3171                 break;
3172               case VT52_BG:
3173                 term->termstate = TOPLEVEL;
3174                 term->curr_attr &= ~ATTR_BGMASK;
3175                 term->curr_attr &= ~ATTR_BLINK;
3176                 term->curr_attr |= (c & 0x7) << ATTR_BGSHIFT;
3177
3178                 /* Note: bold background */
3179                 if (c & 0x8)
3180                     term->curr_attr |= ATTR_BLINK;
3181
3182                 if (term->use_bce)
3183                     term->erase_char = (' ' | ATTR_ASCII |
3184                                         (term->curr_attr &
3185                                          (ATTR_FGMASK | ATTR_BGMASK)));
3186                 break;
3187 #endif
3188               default: break;          /* placate gcc warning about enum use */
3189             }
3190         if (term->selstate != NO_SELECTION) {
3191             pos cursplus = term->curs;
3192             incpos(cursplus);
3193             check_selection(term, term->curs, cursplus);
3194         }
3195     }
3196
3197     term_print_flush(term);
3198 }
3199
3200 #if 0
3201 /*
3202  * Compare two lines to determine whether they are sufficiently
3203  * alike to scroll-optimise one to the other. Return the degree of
3204  * similarity.
3205  */
3206 static int linecmp(Terminal *term, unsigned long *a, unsigned long *b)
3207 {
3208     int i, n;
3209
3210     for (i = n = 0; i < term->cols; i++)
3211         n += (*a++ == *b++);
3212     return n;
3213 }
3214 #endif
3215
3216 /*
3217  * Given a context, update the window. Out of paranoia, we don't
3218  * allow WM_PAINT responses to do scrolling optimisations.
3219  */
3220 static void do_paint(Terminal *term, Context ctx, int may_optimise)
3221 {
3222     int i, j, our_curs_y, our_curs_x;
3223     unsigned long rv, cursor;
3224     pos scrpos;
3225     char ch[1024];
3226     long cursor_background = ERASE_CHAR;
3227     unsigned long ticks;
3228 #ifdef OPTIMISE_SCROLL
3229     struct scrollregion *sr;
3230 #endif /* OPTIMISE_SCROLL */
3231
3232     /*
3233      * Check the visual bell state.
3234      */
3235     if (term->in_vbell) {
3236         ticks = GETTICKCOUNT();
3237         if (ticks - term->vbell_startpoint >= VBELL_TIMEOUT)
3238             term->in_vbell = FALSE; 
3239    }
3240
3241     rv = (!term->rvideo ^ !term->in_vbell ? ATTR_REVERSE : 0);
3242
3243     /* Depends on:
3244      * screen array, disptop, scrtop,
3245      * selection, rv, 
3246      * cfg.blinkpc, blink_is_real, tblinker, 
3247      * curs.y, curs.x, blinker, cfg.blink_cur, cursor_on, has_focus, wrapnext
3248      */
3249
3250     /* Has the cursor position or type changed ? */
3251     if (term->cursor_on) {
3252         if (term->has_focus) {
3253             if (term->blinker || !term->cfg.blink_cur)
3254                 cursor = TATTR_ACTCURS;
3255             else
3256                 cursor = 0;
3257         } else
3258             cursor = TATTR_PASCURS;
3259         if (term->wrapnext)
3260             cursor |= TATTR_RIGHTCURS;
3261     } else
3262         cursor = 0;
3263     our_curs_y = term->curs.y - term->disptop;
3264     {
3265         /*
3266          * Adjust the cursor position in the case where it's
3267          * resting on the right-hand half of a CJK wide character.
3268          * xterm's behaviour here, which seems adequate to me, is
3269          * to display the cursor covering the _whole_ character,
3270          * exactly as if it were one space to the left.
3271          */
3272         unsigned long *ldata = lineptr(term->curs.y);
3273         our_curs_x = term->curs.x;
3274         if (our_curs_x > 0 &&
3275             (ldata[our_curs_x] & (CHAR_MASK | CSET_MASK)) == UCSWIDE)
3276             our_curs_x--;
3277     }
3278
3279     if (term->dispcurs && (term->curstype != cursor ||
3280                            term->dispcurs !=
3281                            term->disptext + our_curs_y * (term->cols + 1) +
3282                            our_curs_x)) {
3283         if (term->dispcurs > term->disptext && 
3284             (*term->dispcurs & (CHAR_MASK | CSET_MASK)) == UCSWIDE)
3285             term->dispcurs[-1] |= ATTR_INVALID;
3286         if ( (term->dispcurs[1] & (CHAR_MASK | CSET_MASK)) == UCSWIDE)
3287             term->dispcurs[1] |= ATTR_INVALID;
3288         *term->dispcurs |= ATTR_INVALID;
3289         term->curstype = 0;
3290     }
3291     term->dispcurs = NULL;
3292
3293 #ifdef OPTIMISE_SCROLL
3294     /* Do scrolls */
3295     sr = term->scrollhead;
3296     while (sr) {
3297         struct scrollregion *next = sr->next;
3298         do_scroll(ctx, sr->topline, sr->botline, sr->lines);
3299         sfree(sr);
3300         sr = next;
3301     }
3302     term->scrollhead = term->scrolltail = NULL;
3303 #endif /* OPTIMISE_SCROLL */
3304
3305     /* The normal screen data */
3306     for (i = 0; i < term->rows; i++) {
3307         unsigned long *ldata;
3308         int lattr;
3309         int idx, dirty_line, dirty_run, selected;
3310         unsigned long attr = 0;
3311         int updated_line = 0;
3312         int start = 0;
3313         int ccount = 0;
3314         int last_run_dirty = 0;
3315
3316         scrpos.y = i + term->disptop;
3317         ldata = lineptr(scrpos.y);
3318         lattr = (ldata[term->cols] & LATTR_MODE);
3319
3320         idx = i * (term->cols + 1);
3321         dirty_run = dirty_line = (ldata[term->cols] !=
3322                                   term->disptext[idx + term->cols]);
3323         term->disptext[idx + term->cols] = ldata[term->cols];
3324
3325         for (j = 0; j < term->cols; j++, idx++) {
3326             unsigned long tattr, tchar;
3327             unsigned long *d = ldata + j;
3328             int break_run;
3329             scrpos.x = j;
3330
3331             tchar = (*d & (CHAR_MASK | CSET_MASK));
3332             tattr = (*d & (ATTR_MASK ^ CSET_MASK));
3333             switch (tchar & CSET_MASK) {
3334               case ATTR_ASCII:
3335                 tchar = term->ucsdata->unitab_line[tchar & 0xFF];
3336                 break;
3337               case ATTR_LINEDRW:
3338                 tchar = term->ucsdata->unitab_xterm[tchar & 0xFF];
3339                 break;
3340               case ATTR_SCOACS:  
3341                 tchar = term->ucsdata->unitab_scoacs[tchar&0xFF]; 
3342                 break;
3343             }
3344             tattr |= (tchar & CSET_MASK);
3345             tchar &= CHAR_MASK;
3346             if ((d[1] & (CHAR_MASK | CSET_MASK)) == UCSWIDE)
3347                     tattr |= ATTR_WIDE;
3348
3349             /* Video reversing things */
3350             if (term->selstate == DRAGGING || term->selstate == SELECTED) {
3351                 if (term->seltype == LEXICOGRAPHIC)
3352                     selected = (posle(term->selstart, scrpos) &&
3353                                 poslt(scrpos, term->selend));
3354                 else
3355                     selected = (posPle(term->selstart, scrpos) &&
3356                                 posPlt(scrpos, term->selend));
3357             } else
3358                 selected = FALSE;
3359             tattr = (tattr ^ rv
3360                      ^ (selected ? ATTR_REVERSE : 0));
3361
3362             /* 'Real' blinking ? */
3363             if (term->blink_is_real && (tattr & ATTR_BLINK)) {
3364                 if (term->has_focus && term->tblinker) {
3365                     tchar = term->ucsdata->unitab_line[(unsigned char)' '];
3366                 }
3367                 tattr &= ~ATTR_BLINK;
3368             }
3369
3370             /*
3371              * Check the font we'll _probably_ be using to see if 
3372              * the character is wide when we don't want it to be.
3373              */
3374             if ((tchar | tattr) != (term->disptext[idx]& ~ATTR_NARROW)) {
3375                 if ((tattr & ATTR_WIDE) == 0 && 
3376                     char_width(ctx, (tchar | tattr) & 0xFFFF) == 2)
3377                     tattr |= ATTR_NARROW;
3378             } else if (term->disptext[idx]&ATTR_NARROW)
3379                 tattr |= ATTR_NARROW;
3380
3381             /* Cursor here ? Save the 'background' */
3382             if (i == our_curs_y && j == our_curs_x) {
3383                 cursor_background = tattr | tchar;
3384                 term->dispcurs = term->disptext + idx;
3385             }
3386
3387             if ((term->disptext[idx] ^ tattr) & ATTR_WIDE)
3388                 dirty_line = TRUE;
3389
3390             break_run = (((tattr ^ attr) & term->attr_mask) ||
3391                 j - start >= sizeof(ch));
3392
3393             /* Special hack for VT100 Linedraw glyphs */
3394             if ((attr & CSET_MASK) == 0x2300 && tchar >= 0xBA
3395                 && tchar <= 0xBD) break_run = TRUE;
3396
3397             if (!term->ucsdata->dbcs_screenfont && !dirty_line) {
3398                 if ((tchar | tattr) == term->disptext[idx])
3399                     break_run = TRUE;
3400                 else if (!dirty_run && ccount == 1)
3401                     break_run = TRUE;
3402             }
3403
3404             if (break_run) {
3405                 if ((dirty_run || last_run_dirty) && ccount > 0) {
3406                     do_text(ctx, start, i, ch, ccount, attr, lattr);
3407                     updated_line = 1;
3408                 }
3409                 start = j;
3410                 ccount = 0;
3411                 attr = tattr;
3412                 if (term->ucsdata->dbcs_screenfont)
3413                     last_run_dirty = dirty_run;
3414                 dirty_run = dirty_line;
3415             }
3416
3417             if ((tchar | tattr) != term->disptext[idx])
3418                 dirty_run = TRUE;
3419             ch[ccount++] = (char) tchar;
3420             term->disptext[idx] = tchar | tattr;
3421
3422             /* If it's a wide char step along to the next one. */
3423             if (tattr & ATTR_WIDE) {
3424                 if (++j < term->cols) {
3425                     idx++;
3426                     d++;
3427                     /*
3428                      * By construction above, the cursor should not
3429                      * be on the right-hand half of this character.
3430                      * Ever.
3431                      */
3432                     assert(!(i == our_curs_y && j == our_curs_x));
3433                     if (term->disptext[idx] != *d)
3434                         dirty_run = TRUE;
3435                     term->disptext[idx] = *d;
3436                 }
3437             }
3438         }
3439         if (dirty_run && ccount > 0) {
3440             do_text(ctx, start, i, ch, ccount, attr, lattr);
3441             updated_line = 1;
3442         }
3443
3444         /* Cursor on this line ? (and changed) */
3445         if (i == our_curs_y && (term->curstype != cursor || updated_line)) {
3446             ch[0] = (char) (cursor_background & CHAR_MASK);
3447             attr = (cursor_background & ATTR_MASK) | cursor;
3448             do_cursor(ctx, our_curs_x, i, ch, 1, attr, lattr);
3449             term->curstype = cursor;
3450         }
3451     }
3452 }
3453
3454 /*
3455  * Flick the switch that says if blinking things should be shown or hidden.
3456  */
3457
3458 void term_blink(Terminal *term, int flg)
3459 {
3460     long now, blink_diff;
3461
3462     now = GETTICKCOUNT();
3463     blink_diff = now - term->last_tblink;
3464
3465     /* Make sure the text blinks no more than 2Hz; we'll use 0.45 s period. */
3466     if (blink_diff < 0 || blink_diff > (TICKSPERSEC * 9 / 20)) {
3467         term->last_tblink = now;
3468         term->tblinker = !term->tblinker;
3469     }
3470
3471     if (flg) {
3472         term->blinker = 1;
3473         term->last_blink = now;
3474         return;
3475     }
3476
3477     blink_diff = now - term->last_blink;
3478
3479     /* Make sure the cursor blinks no faster than system blink rate */
3480     if (blink_diff >= 0 && blink_diff < (long) CURSORBLINK)
3481         return;
3482
3483     term->last_blink = now;
3484     term->blinker = !term->blinker;
3485 }
3486
3487 /*
3488  * Invalidate the whole screen so it will be repainted in full.
3489  */
3490 void term_invalidate(Terminal *term)
3491 {
3492     int i;
3493
3494     for (i = 0; i < term->rows * (term->cols + 1); i++)
3495         term->disptext[i] = ATTR_INVALID;
3496 }
3497
3498 /*
3499  * Paint the window in response to a WM_PAINT message.
3500  */
3501 void term_paint(Terminal *term, Context ctx,
3502                 int left, int top, int right, int bottom, int immediately)
3503 {
3504     int i, j;
3505     if (left < 0) left = 0;
3506     if (top < 0) top = 0;
3507     if (right >= term->cols) right = term->cols-1;
3508     if (bottom >= term->rows) bottom = term->rows-1;
3509
3510     for (i = top; i <= bottom && i < term->rows; i++) {
3511         if ((term->disptext[i * (term->cols + 1) + term->cols] &
3512              LATTR_MODE) == LATTR_NORM)
3513             for (j = left; j <= right && j < term->cols; j++)
3514                 term->disptext[i * (term->cols + 1) + j] = ATTR_INVALID;
3515         else
3516             for (j = left / 2; j <= right / 2 + 1 && j < term->cols; j++)
3517                 term->disptext[i * (term->cols + 1) + j] = ATTR_INVALID;
3518     }
3519
3520     /* This should happen soon enough, also for some reason it sometimes 
3521      * fails to actually do anything when re-sizing ... painting the wrong
3522      * window perhaps ?
3523      */
3524     if (immediately)
3525         do_paint (term, ctx, FALSE);
3526 }
3527
3528 /*
3529  * Attempt to scroll the scrollback. The second parameter gives the
3530  * position we want to scroll to; the first is +1 to denote that
3531  * this position is relative to the beginning of the scrollback, -1
3532  * to denote it is relative to the end, and 0 to denote that it is
3533  * relative to the current position.
3534  */
3535 void term_scroll(Terminal *term, int rel, int where)
3536 {
3537     int sbtop = -sblines(term);
3538 #ifdef OPTIMISE_SCROLL
3539     int olddisptop = term->disptop;
3540     int shift;
3541 #endif /* OPTIMISE_SCROLL */
3542
3543     term->disptop = (rel < 0 ? 0 : rel > 0 ? sbtop : term->disptop) + where;
3544     if (term->disptop < sbtop)
3545         term->disptop = sbtop;
3546     if (term->disptop > 0)
3547         term->disptop = 0;
3548     update_sbar(term);
3549 #ifdef OPTIMISE_SCROLL
3550     shift = (term->disptop - olddisptop);
3551     if (shift < term->rows && shift > -term->rows)
3552         scroll_display(term, 0, term->rows - 1, shift);
3553 #endif /* OPTIMISE_SCROLL */
3554     term_update(term);
3555 }
3556
3557 static void clipme(Terminal *term, pos top, pos bottom, int rect)
3558 {
3559     wchar_t *workbuf;
3560     wchar_t *wbptr;                    /* where next char goes within workbuf */
3561     int old_top_x;
3562     int wblen = 0;                     /* workbuf len */
3563     int buflen;                        /* amount of memory allocated to workbuf */
3564
3565     buflen = 5120;                     /* Default size */
3566     workbuf = snewn(buflen, wchar_t);
3567     wbptr = workbuf;                   /* start filling here */
3568     old_top_x = top.x;                 /* needed for rect==1 */
3569
3570     while (poslt(top, bottom)) {
3571         int nl = FALSE;
3572         unsigned long *ldata = lineptr(top.y);
3573         pos nlpos;
3574
3575         /*
3576          * nlpos will point at the maximum position on this line we
3577          * should copy up to. So we start it at the end of the
3578          * line...
3579          */
3580         nlpos.y = top.y;
3581         nlpos.x = term->cols;
3582
3583         /*
3584          * ... move it backwards if there's unused space at the end
3585          * of the line (and also set `nl' if this is the case,
3586          * because in normal selection mode this means we need a
3587          * newline at the end)...
3588          */
3589         if (!(ldata[term->cols] & LATTR_WRAPPED)) {
3590             while (((ldata[nlpos.x - 1] & 0xFF) == 0x20 ||
3591                     (DIRECT_CHAR(ldata[nlpos.x - 1]) &&
3592                      (ldata[nlpos.x - 1] & CHAR_MASK) == 0x20))
3593                    && poslt(top, nlpos))
3594                 decpos(nlpos);
3595             if (poslt(nlpos, bottom))
3596                 nl = TRUE;
3597         } else if (ldata[term->cols] & LATTR_WRAPPED2) {
3598             /* Ignore the last char on the line in a WRAPPED2 line. */
3599             decpos(nlpos);
3600         }
3601
3602         /*
3603          * ... and then clip it to the terminal x coordinate if
3604          * we're doing rectangular selection. (In this case we
3605          * still did the above, so that copying e.g. the right-hand
3606          * column from a table doesn't fill with spaces on the
3607          * right.)
3608          */
3609         if (rect) {
3610             if (nlpos.x > bottom.x)
3611                 nlpos.x = bottom.x;
3612             nl = (top.y < bottom.y);
3613         }
3614
3615         while (poslt(top, bottom) && poslt(top, nlpos)) {
3616 #if 0
3617             char cbuf[16], *p;
3618             sprintf(cbuf, "<U+%04x>", (ldata[top.x] & 0xFFFF));
3619 #else
3620             wchar_t cbuf[16], *p;
3621             int uc = (ldata[top.x] & 0xFFFF);
3622             int set, c;
3623
3624             if (uc == UCSWIDE) {
3625                 top.x++;
3626                 continue;
3627             }
3628
3629             switch (uc & CSET_MASK) {
3630               case ATTR_LINEDRW:
3631                 if (!term->cfg.rawcnp) {
3632                     uc = term->ucsdata->unitab_xterm[uc & 0xFF];
3633                     break;
3634                 }
3635               case ATTR_ASCII:
3636                 uc = term->ucsdata->unitab_line[uc & 0xFF];
3637                 break;
3638               case ATTR_SCOACS:  
3639                 uc = term->ucsdata->unitab_scoacs[uc&0xFF]; 
3640                 break;
3641             }
3642             switch (uc & CSET_MASK) {
3643               case ATTR_ACP:
3644                 uc = term->ucsdata->unitab_font[uc & 0xFF];
3645                 break;
3646               case ATTR_OEMCP:
3647                 uc = term->ucsdata->unitab_oemcp[uc & 0xFF];
3648                 break;
3649             }
3650
3651             set = (uc & CSET_MASK);
3652             c = (uc & CHAR_MASK);
3653             cbuf[0] = uc;
3654             cbuf[1] = 0;
3655
3656             if (DIRECT_FONT(uc)) {
3657                 if (c >= ' ' && c != 0x7F) {
3658                     char buf[4];
3659                     WCHAR wbuf[4];
3660                     int rv;
3661                     if (is_dbcs_leadbyte(term->ucsdata->font_codepage, (BYTE) c)) {
3662                         buf[0] = c;
3663                         buf[1] = (char) (0xFF & ldata[top.x + 1]);
3664                         rv = mb_to_wc(term->ucsdata->font_codepage, 0, buf, 2, wbuf, 4);
3665                         top.x++;
3666                     } else {
3667                         buf[0] = c;
3668                         rv = mb_to_wc(term->ucsdata->font_codepage, 0, buf, 1, wbuf, 4);
3669                     }
3670
3671                     if (rv > 0) {
3672                         memcpy(cbuf, wbuf, rv * sizeof(wchar_t));
3673                         cbuf[rv] = 0;
3674                     }
3675                 }
3676             }
3677 #endif
3678
3679             for (p = cbuf; *p; p++) {
3680                 /* Enough overhead for trailing NL and nul */
3681                 if (wblen >= buflen - 16) {
3682                     buflen += 100;
3683                     workbuf = sresize(workbuf, buflen, wchar_t);
3684                     wbptr = workbuf + wblen;
3685                 }
3686                 wblen++;
3687                 *wbptr++ = *p;
3688             }
3689             top.x++;
3690         }
3691         if (nl) {
3692             int i;
3693             for (i = 0; i < sel_nl_sz; i++) {
3694                 wblen++;
3695                 *wbptr++ = sel_nl[i];
3696             }
3697         }
3698         top.y++;
3699         top.x = rect ? old_top_x : 0;
3700     }
3701 #if SELECTION_NUL_TERMINATED
3702     wblen++;
3703     *wbptr++ = 0;
3704 #endif
3705     write_clip(term->frontend, workbuf, wblen, FALSE); /* transfer to clipbd */
3706     if (buflen > 0)                    /* indicates we allocated this buffer */
3707         sfree(workbuf);
3708 }
3709
3710 void term_copyall(Terminal *term)
3711 {
3712     pos top;
3713     top.y = -sblines(term);
3714     top.x = 0;
3715     clipme(term, top, term->curs, 0);
3716 }
3717
3718 /*
3719  * The wordness array is mainly for deciding the disposition of the
3720  * US-ASCII characters.
3721  */
3722 static int wordtype(Terminal *term, int uc)
3723 {
3724     struct ucsword {
3725         int start, end, ctype;
3726     };
3727     static const struct ucsword ucs_words[] = {
3728         {
3729         128, 160, 0}, {
3730         161, 191, 1}, {
3731         215, 215, 1}, {
3732         247, 247, 1}, {
3733         0x037e, 0x037e, 1},            /* Greek question mark */
3734         {
3735         0x0387, 0x0387, 1},            /* Greek ano teleia */
3736         {
3737         0x055a, 0x055f, 1},            /* Armenian punctuation */
3738         {
3739         0x0589, 0x0589, 1},            /* Armenian full stop */
3740         {
3741         0x0700, 0x070d, 1},            /* Syriac punctuation */
3742         {
3743         0x104a, 0x104f, 1},            /* Myanmar punctuation */
3744         {
3745         0x10fb, 0x10fb, 1},            /* Georgian punctuation */
3746         {
3747         0x1361, 0x1368, 1},            /* Ethiopic punctuation */
3748         {
3749         0x166d, 0x166e, 1},            /* Canadian Syl. punctuation */
3750         {
3751         0x17d4, 0x17dc, 1},            /* Khmer punctuation */
3752         {
3753         0x1800, 0x180a, 1},            /* Mongolian punctuation */
3754         {
3755         0x2000, 0x200a, 0},            /* Various spaces */
3756         {
3757         0x2070, 0x207f, 2},            /* superscript */
3758         {
3759         0x2080, 0x208f, 2},            /* subscript */
3760         {
3761         0x200b, 0x27ff, 1},            /* punctuation and symbols */
3762         {
3763         0x3000, 0x3000, 0},            /* ideographic space */
3764         {
3765         0x3001, 0x3020, 1},            /* ideographic punctuation */
3766         {
3767         0x303f, 0x309f, 3},            /* Hiragana */
3768         {
3769         0x30a0, 0x30ff, 3},            /* Katakana */
3770         {
3771         0x3300, 0x9fff, 3},            /* CJK Ideographs */
3772         {
3773         0xac00, 0xd7a3, 3},            /* Hangul Syllables */
3774         {
3775         0xf900, 0xfaff, 3},            /* CJK Ideographs */
3776         {
3777         0xfe30, 0xfe6b, 1},            /* punctuation forms */
3778         {
3779         0xff00, 0xff0f, 1},            /* half/fullwidth ASCII */
3780         {
3781         0xff1a, 0xff20, 1},            /* half/fullwidth ASCII */
3782         {
3783         0xff3b, 0xff40, 1},            /* half/fullwidth ASCII */
3784         {
3785         0xff5b, 0xff64, 1},            /* half/fullwidth ASCII */
3786         {
3787         0xfff0, 0xffff, 0},            /* half/fullwidth ASCII */
3788         {
3789         0, 0, 0}
3790     };
3791     const struct ucsword *wptr;
3792
3793     uc &= (CSET_MASK | CHAR_MASK);
3794
3795     switch (uc & CSET_MASK) {
3796       case ATTR_LINEDRW:
3797         uc = term->ucsdata->unitab_xterm[uc & 0xFF];
3798         break;
3799       case ATTR_ASCII:
3800         uc = term->ucsdata->unitab_line[uc & 0xFF];
3801         break;
3802       case ATTR_SCOACS:  
3803         uc = term->ucsdata->unitab_scoacs[uc&0xFF]; 
3804         break;
3805     }
3806     switch (uc & CSET_MASK) {
3807       case ATTR_ACP:
3808         uc = term->ucsdata->unitab_font[uc & 0xFF];
3809         break;
3810       case ATTR_OEMCP:
3811         uc = term->ucsdata->unitab_oemcp[uc & 0xFF];
3812         break;
3813     }
3814
3815     /* For DBCS font's I can't do anything usefull. Even this will sometimes
3816      * fail as there's such a thing as a double width space. :-(
3817      */
3818     if (term->ucsdata->dbcs_screenfont &&
3819         term->ucsdata->font_codepage == term->ucsdata->line_codepage)
3820         return (uc != ' ');
3821
3822     if (uc < 0x80)
3823         return term->wordness[uc];
3824
3825     for (wptr = ucs_words; wptr->start; wptr++) {
3826         if (uc >= wptr->start && uc <= wptr->end)
3827             return wptr->ctype;
3828     }
3829
3830     return 2;
3831 }
3832
3833 /*
3834  * Spread the selection outwards according to the selection mode.
3835  */
3836 static pos sel_spread_half(Terminal *term, pos p, int dir)
3837 {
3838     unsigned long *ldata;
3839     short wvalue;
3840     int topy = -sblines(term);
3841
3842     ldata = lineptr(p.y);
3843
3844     switch (term->selmode) {
3845       case SM_CHAR:
3846         /*
3847          * In this mode, every character is a separate unit, except
3848          * for runs of spaces at the end of a non-wrapping line.
3849          */
3850         if (!(ldata[term->cols] & LATTR_WRAPPED)) {
3851             unsigned long *q = ldata + term->cols;
3852             while (q > ldata && (q[-1] & CHAR_MASK) == 0x20)
3853                 q--;
3854             if (q == ldata + term->cols)
3855                 q--;
3856             if (p.x >= q - ldata)
3857                 p.x = (dir == -1 ? q - ldata : term->cols - 1);
3858         }
3859         break;
3860       case SM_WORD:
3861         /*
3862          * In this mode, the units are maximal runs of characters
3863          * whose `wordness' has the same value.
3864          */
3865         wvalue = wordtype(term, UCSGET(ldata, p.x));
3866         if (dir == +1) {
3867             while (1) {
3868                 int maxcols = (ldata[term->cols] & LATTR_WRAPPED2 ?
3869                                term->cols-1 : term->cols);
3870                 if (p.x < maxcols-1) {
3871                     if (wordtype(term, UCSGET(ldata, p.x + 1)) == wvalue)
3872                         p.x++;
3873                     else
3874                         break;
3875                 } else {
3876                     if (ldata[term->cols] & LATTR_WRAPPED) {
3877                         unsigned long *ldata2;
3878                         ldata2 = lineptr(p.y+1);
3879                         if (wordtype(term, UCSGET(ldata2, 0)) == wvalue) {
3880                             p.x = 0;
3881                             p.y++;
3882                             ldata = ldata2;
3883                         } else
3884                             break;
3885                     } else
3886                         break;
3887                 }
3888             }
3889         } else {
3890             while (1) {
3891                 if (p.x > 0) {
3892                     if (wordtype(term, UCSGET(ldata, p.x - 1)) == wvalue)
3893                         p.x--;
3894                     else
3895                         break;
3896                 } else {
3897                     unsigned long *ldata2;
3898                     int maxcols;
3899                     if (p.y <= topy)
3900                         break;
3901                     ldata2 = lineptr(p.y-1);
3902                     maxcols = (ldata2[term->cols] & LATTR_WRAPPED2 ?
3903                               term->cols-1 : term->cols);
3904                     if (ldata2[term->cols] & LATTR_WRAPPED) {
3905                         if (wordtype(term, UCSGET(ldata2, maxcols-1))
3906                             == wvalue) {
3907                             p.x = maxcols-1;
3908                             p.y--;
3909                             ldata = ldata2;
3910                         } else
3911                             break;
3912                     } else
3913                         break;
3914                 }
3915             }
3916         }
3917         break;
3918       case SM_LINE:
3919         /*
3920          * In this mode, every line is a unit.
3921          */
3922         p.x = (dir == -1 ? 0 : term->cols - 1);
3923         break;
3924     }
3925     return p;
3926 }
3927
3928 static void sel_spread(Terminal *term)
3929 {
3930     if (term->seltype == LEXICOGRAPHIC) {
3931         term->selstart = sel_spread_half(term, term->selstart, -1);
3932         decpos(term->selend);
3933         term->selend = sel_spread_half(term, term->selend, +1);
3934         incpos(term->selend);
3935     }
3936 }
3937
3938 void term_do_paste(Terminal *term)
3939 {
3940     wchar_t *data;
3941     int len;
3942
3943     get_clip(term->frontend, &data, &len);
3944     if (data && len > 0) {
3945         wchar_t *p, *q;
3946
3947         term_seen_key_event(term);     /* pasted data counts */
3948
3949         if (term->paste_buffer)
3950             sfree(term->paste_buffer);
3951         term->paste_pos = term->paste_hold = term->paste_len = 0;
3952         term->paste_buffer = snewn(len, wchar_t);
3953
3954         p = q = data;
3955         while (p < data + len) {
3956             while (p < data + len &&
3957                    !(p <= data + len - sel_nl_sz &&
3958                      !memcmp(p, sel_nl, sizeof(sel_nl))))
3959                 p++;
3960
3961             {
3962                 int i;
3963                 for (i = 0; i < p - q; i++) {
3964                     term->paste_buffer[term->paste_len++] = q[i];
3965                 }
3966             }
3967
3968             if (p <= data + len - sel_nl_sz &&
3969                 !memcmp(p, sel_nl, sizeof(sel_nl))) {
3970                 term->paste_buffer[term->paste_len++] = '\015';
3971                 p += sel_nl_sz;
3972             }
3973             q = p;
3974         }
3975
3976         /* Assume a small paste will be OK in one go. */
3977         if (term->paste_len < 256) {
3978             if (term->ldisc)
3979                 luni_send(term->ldisc, term->paste_buffer, term->paste_len, 0);
3980             if (term->paste_buffer)
3981                 sfree(term->paste_buffer);
3982             term->paste_buffer = 0;
3983             term->paste_pos = term->paste_hold = term->paste_len = 0;
3984         }
3985     }
3986     get_clip(term->frontend, NULL, NULL);
3987 }
3988
3989 void term_mouse(Terminal *term, Mouse_Button braw, Mouse_Button bcooked,
3990                 Mouse_Action a, int x, int y, int shift, int ctrl, int alt)
3991 {
3992     pos selpoint;
3993     unsigned long *ldata;
3994     int raw_mouse = (term->xterm_mouse &&
3995                      !term->cfg.no_mouse_rep &&
3996                      !(term->cfg.mouse_override && shift));
3997     int default_seltype;
3998
3999     if (y < 0) {
4000         y = 0;
4001         if (a == MA_DRAG && !raw_mouse)
4002             term_scroll(term, 0, -1);
4003     }
4004     if (y >= term->rows) {
4005         y = term->rows - 1;
4006         if (a == MA_DRAG && !raw_mouse)
4007             term_scroll(term, 0, +1);
4008     }
4009     if (x < 0) {
4010         if (y > 0) {
4011             x = term->cols - 1;
4012             y--;
4013         } else
4014             x = 0;
4015     }
4016     if (x >= term->cols)
4017         x = term->cols - 1;
4018
4019     selpoint.y = y + term->disptop;
4020     selpoint.x = x;
4021     ldata = lineptr(selpoint.y);
4022     if ((ldata[term->cols] & LATTR_MODE) != LATTR_NORM)
4023         selpoint.x /= 2;
4024
4025     if (raw_mouse) {
4026         int encstate = 0, r, c;
4027         char abuf[16];
4028
4029         if (term->ldisc) {
4030
4031             switch (braw) {
4032               case MBT_LEFT:
4033                 encstate = 0x20;               /* left button down */
4034                 break;
4035               case MBT_MIDDLE:
4036                 encstate = 0x21;
4037                 break;
4038               case MBT_RIGHT:
4039                 encstate = 0x22;
4040                 break;
4041               case MBT_WHEEL_UP:
4042                 encstate = 0x60;
4043                 break;
4044               case MBT_WHEEL_DOWN:
4045                 encstate = 0x61;
4046                 break;
4047               default: break;          /* placate gcc warning about enum use */
4048             }
4049             switch (a) {
4050               case MA_DRAG:
4051                 if (term->xterm_mouse == 1)
4052                     return;
4053                 encstate += 0x20;
4054                 break;
4055               case MA_RELEASE:
4056                 encstate = 0x23;
4057                 term->mouse_is_down = 0;
4058                 break;
4059               case MA_CLICK:
4060                 if (term->mouse_is_down == braw)
4061                     return;
4062                 term->mouse_is_down = braw;
4063                 break;
4064               default: break;          /* placate gcc warning about enum use */
4065             }
4066             if (shift)
4067                 encstate += 0x04;
4068             if (ctrl)
4069                 encstate += 0x10;
4070             r = y + 33;
4071             c = x + 33;
4072
4073             sprintf(abuf, "\033[M%c%c%c", encstate, c, r);
4074             ldisc_send(term->ldisc, abuf, 6, 0);
4075         }
4076         return;
4077     }
4078
4079     /*
4080      * Set the selection type (rectangular or normal) at the start
4081      * of a selection attempt, from the state of Alt.
4082      */
4083     if (!alt ^ !term->cfg.rect_select)
4084         default_seltype = RECTANGULAR;
4085     else
4086         default_seltype = LEXICOGRAPHIC;
4087         
4088     if (term->selstate == NO_SELECTION) {
4089         term->seltype = default_seltype;
4090     }
4091
4092     if (bcooked == MBT_SELECT && a == MA_CLICK) {
4093         deselect(term);
4094         term->selstate = ABOUT_TO;
4095         term->seltype = default_seltype;
4096         term->selanchor = selpoint;
4097         term->selmode = SM_CHAR;
4098     } else if (bcooked == MBT_SELECT && (a == MA_2CLK || a == MA_3CLK)) {
4099         deselect(term);
4100         term->selmode = (a == MA_2CLK ? SM_WORD : SM_LINE);
4101         term->selstate = DRAGGING;
4102         term->selstart = term->selanchor = selpoint;
4103         term->selend = term->selstart;
4104         incpos(term->selend);
4105         sel_spread(term);
4106     } else if ((bcooked == MBT_SELECT && a == MA_DRAG) ||
4107                (bcooked == MBT_EXTEND && a != MA_RELEASE)) {
4108         if (term->selstate == ABOUT_TO && poseq(term->selanchor, selpoint))
4109             return;
4110         if (bcooked == MBT_EXTEND && a != MA_DRAG &&
4111             term->selstate == SELECTED) {
4112             if (term->seltype == LEXICOGRAPHIC) {
4113                 /*
4114                  * For normal selection, we extend by moving
4115                  * whichever end of the current selection is closer
4116                  * to the mouse.
4117                  */
4118                 if (posdiff(selpoint, term->selstart) <
4119                     posdiff(term->selend, term->selstart) / 2) {
4120                     term->selanchor = term->selend;
4121                     decpos(term->selanchor);
4122                 } else {
4123                     term->selanchor = term->selstart;
4124                 }
4125             } else {
4126                 /*
4127                  * For rectangular selection, we have a choice of
4128                  * _four_ places to put selanchor and selpoint: the
4129                  * four corners of the selection.
4130                  */
4131                 if (2*selpoint.x < term->selstart.x + term->selend.x)
4132                     term->selanchor.x = term->selend.x-1;
4133                 else
4134                     term->selanchor.x = term->selstart.x;
4135
4136                 if (2*selpoint.y < term->selstart.y + term->selend.y)
4137                     term->selanchor.y = term->selend.y;
4138                 else
4139                     term->selanchor.y = term->selstart.y;
4140             }
4141             term->selstate = DRAGGING;
4142         }
4143         if (term->selstate != ABOUT_TO && term->selstate != DRAGGING)
4144             term->selanchor = selpoint;
4145         term->selstate = DRAGGING;
4146         if (term->seltype == LEXICOGRAPHIC) {
4147             /*
4148              * For normal selection, we set (selstart,selend) to
4149              * (selpoint,selanchor) in some order.
4150              */
4151             if (poslt(selpoint, term->selanchor)) {
4152                 term->selstart = selpoint;
4153                 term->selend = term->selanchor;
4154                 incpos(term->selend);
4155             } else {
4156                 term->selstart = term->selanchor;
4157                 term->selend = selpoint;
4158                 incpos(term->selend);
4159             }
4160         } else {
4161             /*
4162              * For rectangular selection, we may need to
4163              * interchange x and y coordinates (if the user has
4164              * dragged in the -x and +y directions, or vice versa).
4165              */
4166             term->selstart.x = min(term->selanchor.x, selpoint.x);
4167             term->selend.x = 1+max(term->selanchor.x, selpoint.x);
4168             term->selstart.y = min(term->selanchor.y, selpoint.y);
4169             term->selend.y =   max(term->selanchor.y, selpoint.y);
4170         }
4171         sel_spread(term);
4172     } else if ((bcooked == MBT_SELECT || bcooked == MBT_EXTEND) &&
4173                a == MA_RELEASE) {
4174         if (term->selstate == DRAGGING) {
4175             /*
4176              * We've completed a selection. We now transfer the
4177              * data to the clipboard.
4178              */
4179             clipme(term, term->selstart, term->selend,
4180                    (term->seltype == RECTANGULAR));
4181             term->selstate = SELECTED;
4182         } else
4183             term->selstate = NO_SELECTION;
4184     } else if (bcooked == MBT_PASTE
4185                && (a == MA_CLICK
4186 #if MULTICLICK_ONLY_EVENT
4187                    || a == MA_2CLK || a == MA_3CLK
4188 #endif
4189                    )) {
4190         request_paste(term->frontend);
4191     }
4192
4193     term_update(term);
4194 }
4195
4196 void term_key(Terminal *term, Key_Sym keysym, wchar_t *text, size_t tlen,
4197               unsigned int modifiers, unsigned int flags)
4198 {
4199     char output[10];
4200     char *p = output;
4201     int prependesc = FALSE;
4202 #if 0
4203     int i;
4204
4205     fprintf(stderr, "keysym = %d, %d chars:", keysym, tlen);
4206     for (i = 0; i < tlen; i++)
4207         fprintf(stderr, " %04x", (unsigned)text[i]);
4208     fprintf(stderr, "\n");
4209 #endif
4210
4211     /* XXX Num Lock */
4212     if ((flags & PKF_REPEAT) && term->repeat_off)
4213         return;
4214
4215     /* Currently, Meta always just prefixes everything with ESC. */
4216     if (modifiers & PKM_META)
4217         prependesc = TRUE;
4218     modifiers &= ~PKM_META;
4219
4220     /*
4221      * Alt is only used for Alt+keypad, which isn't supported yet, so
4222      * ignore it.
4223      */
4224     modifiers &= ~PKM_ALT;
4225
4226     /* Standard local function keys */
4227     switch (modifiers & (PKM_SHIFT | PKM_CONTROL)) {
4228       case PKM_SHIFT:
4229         if (keysym == PK_PAGEUP)
4230             /* scroll up one page */;
4231         if (keysym == PK_PAGEDOWN)
4232             /* scroll down on page */;
4233         if (keysym == PK_INSERT)
4234             term_do_paste(term);
4235         break;
4236       case PKM_CONTROL:
4237         if (keysym == PK_PAGEUP)
4238             /* scroll up one line */;
4239         if (keysym == PK_PAGEDOWN)
4240             /* scroll down one line */;
4241         /* Control-Numlock for app-keypad mode switch */
4242         if (keysym == PK_PF1)
4243             term->app_keypad_keys ^= 1;
4244         break;
4245     }
4246
4247     if (modifiers & PKM_ALT) {
4248         /* Alt+F4 (close) */
4249         /* Alt+Return (full screen) */
4250         /* Alt+Space (system menu) */
4251     }
4252
4253     if (keysym == PK_NULL && (modifiers & PKM_CONTROL) && tlen == 1 &&
4254         text[0] >= 0x20 && text[0] <= 0x7e) {
4255         /* ASCII chars + Control */
4256         if ((text[0] >= 0x40 && text[0] <= 0x5f) ||
4257             (text[0] >= 0x61 && text[0] <= 0x7a))
4258             text[0] &= 0x1f;
4259         else {
4260             /*
4261              * Control-2 should return ^@ (0x00), Control-6 should return
4262              * ^^ (0x1E), and Control-Minus should return ^_ (0x1F). Since
4263              * the DOS keyboard handling did it, and we have nothing better
4264              * to do with the key combo in question, we'll also map
4265              * Control-Backquote to ^\ (0x1C).
4266              */
4267             switch (text[0]) {
4268               case ' ': text[0] = 0x00; break;
4269               case '-': text[0] = 0x1f; break;
4270               case '/': text[0] = 0x1f; break;
4271               case '2': text[0] = 0x00; break;
4272               case '3': text[0] = 0x1b; break;
4273               case '4': text[0] = 0x1c; break;
4274               case '5': text[0] = 0x1d; break;
4275               case '6': text[0] = 0x1e; break;
4276               case '7': text[0] = 0x1f; break;
4277               case '8': text[0] = 0x7f; break;
4278               case '`': text[0] = 0x1c; break;
4279             }
4280         }
4281     }
4282
4283     /* Nethack keypad */
4284     if (term->cfg.nethack_keypad) {
4285         char c = 0;
4286         switch (keysym) {
4287           case PK_KP1: c = 'b'; break;
4288           case PK_KP2: c = 'j'; break;
4289           case PK_KP3: c = 'n'; break;
4290           case PK_KP4: c = 'h'; break;
4291           case PK_KP5: c = '.'; break;
4292           case PK_KP6: c = 'l'; break;
4293           case PK_KP7: c = 'y'; break;
4294           case PK_KP8: c = 'k'; break;
4295           case PK_KP9: c = 'u'; break;
4296           default: break; /* else gcc warns `enum value not used' */
4297         }
4298         if (c != 0) {
4299             if (c != '.') {
4300                 if (modifiers & PKM_CONTROL)
4301                     c &= 0x1f;
4302                 else if (modifiers & PKM_SHIFT)
4303                     c = toupper(c);
4304             }
4305             *p++ = c;
4306             goto done;
4307         }
4308     }
4309
4310     /* Numeric Keypad */
4311     if (PK_ISKEYPAD(keysym)) {
4312         int xkey = 0;
4313
4314         /*
4315          * In VT400 mode, PFn always emits an escape sequence.  In
4316          * Linux and tilde modes, this only happens in app keypad mode.
4317          */
4318         if (term->cfg.funky_type == FUNKY_VT400 ||
4319             ((term->cfg.funky_type == FUNKY_LINUX ||
4320               term->cfg.funky_type == FUNKY_TILDE) &&
4321              term->app_keypad_keys && !term->cfg.no_applic_k)) {
4322             switch (keysym) {
4323               case PK_PF1: xkey = 'P'; break;
4324               case PK_PF2: xkey = 'Q'; break;
4325               case PK_PF3: xkey = 'R'; break;
4326               case PK_PF4: xkey = 'S'; break;
4327               default: break; /* else gcc warns `enum value not used' */
4328             }
4329         }
4330         if (term->app_keypad_keys && !term->cfg.no_applic_k) {
4331             switch (keysym) {
4332               case PK_KP0: xkey = 'p'; break;
4333               case PK_KP1: xkey = 'q'; break;
4334               case PK_KP2: xkey = 'r'; break;
4335               case PK_KP3: xkey = 's'; break;
4336               case PK_KP4: xkey = 't'; break;
4337               case PK_KP5: xkey = 'u'; break;
4338               case PK_KP6: xkey = 'v'; break;
4339               case PK_KP7: xkey = 'w'; break;
4340               case PK_KP8: xkey = 'x'; break;
4341               case PK_KP9: xkey = 'y'; break;
4342               case PK_KPDECIMAL: xkey = 'n'; break;
4343               case PK_KPENTER: xkey = 'M'; break;
4344               default: break; /* else gcc warns `enum value not used' */
4345             }
4346             if (term->cfg.funky_type == FUNKY_XTERM && tlen > 0) {
4347                 /*
4348                  * xterm can't see the layout of the keypad, so it has
4349                  * to rely on the X keysyms returned by the keys.
4350                  * Hence, we look at the strings here, not the PuTTY
4351                  * keysyms (which describe the layout).
4352                  */
4353                 switch (text[0]) {
4354                   case '+':
4355                     if (modifiers & PKM_SHIFT)
4356                         xkey = 'l';
4357                     else
4358                         xkey = 'k';
4359                     break;
4360                   case '/': xkey = 'o'; break;
4361                   case '*': xkey = 'j'; break;
4362                   case '-': xkey = 'm'; break;
4363                 }
4364             } else {
4365                 /*
4366                  * In all other modes, we try to retain the layout of
4367                  * the DEC keypad in application mode.
4368                  */
4369                 switch (keysym) {
4370                   case PK_KPBIGPLUS:
4371                     /* This key covers the '-' and ',' keys on a VT220 */
4372                     if (modifiers & PKM_SHIFT)
4373                         xkey = 'm'; /* VT220 '-' */
4374                     else
4375                         xkey = 'l'; /* VT220 ',' */
4376                     break;
4377                   case PK_KPMINUS: xkey = 'm'; break;
4378                   case PK_KPCOMMA: xkey = 'l'; break;
4379                   default: break; /* else gcc warns `enum value not used' */
4380                 }
4381             }
4382         }
4383         if (xkey) {
4384             if (term->vt52_mode) {
4385                 if (xkey >= 'P' && xkey <= 'S')
4386                     p += sprintf((char *) p, "\x1B%c", xkey);
4387                 else
4388                     p += sprintf((char *) p, "\x1B?%c", xkey);
4389             } else
4390                 p += sprintf((char *) p, "\x1BO%c", xkey);
4391             goto done;
4392         }
4393         /* Not in application mode -- treat the number pad as arrow keys? */
4394         if ((flags & PKF_NUMLOCK) == 0) {
4395             switch (keysym) {
4396               case PK_KP0: keysym = PK_INSERT; break;
4397               case PK_KP1: keysym = PK_END; break;
4398               case PK_KP2: keysym = PK_DOWN; break;
4399               case PK_KP3: keysym = PK_PAGEDOWN; break;
4400               case PK_KP4: keysym = PK_LEFT; break;
4401               case PK_KP5: keysym = PK_REST; break;
4402               case PK_KP6: keysym = PK_RIGHT; break;
4403               case PK_KP7: keysym = PK_HOME; break;
4404               case PK_KP8: keysym = PK_UP; break;
4405               case PK_KP9: keysym = PK_PAGEUP; break;
4406               default: break; /* else gcc warns `enum value not used' */
4407             }
4408         }
4409     }
4410
4411     /* Miscellaneous keys */
4412     switch (keysym) {
4413       case PK_ESCAPE:
4414         *p++ = 0x1b;
4415         goto done;
4416       case PK_BACKSPACE:
4417             if (modifiers == 0)
4418                 *p++ = (term->cfg.bksp_is_delete ? 0x7F : 0x08);
4419             else if (modifiers == PKM_SHIFT)
4420                 /* We do the opposite of what is configured */
4421                 *p++ = (term->cfg.bksp_is_delete ? 0x08 : 0x7F);
4422             else break;
4423             goto done;
4424       case PK_TAB:
4425         if (modifiers == 0)
4426             *p++ = 0x09;
4427         else if (modifiers == PKM_SHIFT)
4428             *p++ = 0x1B, *p++ = '[', *p++ = 'Z';
4429         else break;
4430         goto done;
4431         /* XXX window.c has ctrl+shift+space sending 0xa0 */
4432       case PK_PAUSE:
4433         if (modifiers == PKM_CONTROL)
4434             *p++ = 26;
4435         else break;
4436         goto done;
4437       case PK_RETURN:
4438       case PK_KPENTER: /* Odd keypad modes handled above */
4439         if (modifiers == 0) {
4440             *p++ = 0x0d;
4441             if (term->cr_lf_return)
4442                 *p++ = 0x0a;
4443             goto done;
4444         }
4445       default: break; /* else gcc warns `enum value not used' */
4446     }
4447
4448     /* SCO function keys and editing keys */
4449     if (term->cfg.funky_type == FUNKY_SCO) {
4450         if (PK_ISFKEY(keysym) && keysym <= PK_F12) {
4451             static char const codes[] =
4452                 "MNOPQRSTUVWX" "YZabcdefghij" "klmnopqrstuv" "wxyz@[\\]^_`{";
4453             int index = keysym - PK_F1;
4454
4455             if (modifiers & PKM_SHIFT) index += 12;
4456             if (modifiers & PKM_CONTROL) index += 24;
4457             p += sprintf((char *) p, "\x1B[%c", codes[index]);
4458             goto done;
4459         }
4460         if (PK_ISEDITING(keysym)) {
4461             int xkey = 0;
4462
4463             switch (keysym) {
4464               case PK_DELETE:   *p++ = 0x7f; goto done;
4465               case PK_HOME:     xkey = 'H'; break;
4466               case PK_INSERT:   xkey = 'L'; break;
4467               case PK_END:      xkey = 'F'; break;
4468               case PK_PAGEUP:   xkey = 'I'; break;
4469               case PK_PAGEDOWN: xkey = 'G'; break;
4470               default: break; /* else gcc warns `enum value not used' */
4471             }
4472             p += sprintf((char *) p, "\x1B[%c", xkey);
4473         }
4474     }
4475
4476     if (PK_ISEDITING(keysym) && (modifiers & PKM_SHIFT) == 0) {
4477         int code;
4478
4479         if (term->cfg.funky_type == FUNKY_XTERM) {
4480             /* Xterm shuffles these keys, apparently. */
4481             switch (keysym) {
4482               case PK_HOME:     keysym = PK_INSERT;   break;
4483               case PK_INSERT:   keysym = PK_HOME;     break;
4484               case PK_DELETE:   keysym = PK_END;      break;
4485               case PK_END:      keysym = PK_PAGEUP;   break;
4486               case PK_PAGEUP:   keysym = PK_DELETE;   break;
4487               case PK_PAGEDOWN: keysym = PK_PAGEDOWN; break;
4488               default: break; /* else gcc warns `enum value not used' */
4489             }
4490         }
4491
4492         /* RXVT Home/End */
4493         if (term->cfg.rxvt_homeend &&
4494             (keysym == PK_HOME || keysym == PK_END)) {
4495             p += sprintf((char *) p, keysym == PK_HOME ? "\x1B[H" : "\x1BOw");
4496             goto done;
4497         }
4498
4499         if (term->vt52_mode) {
4500             int xkey;
4501
4502             /*
4503              * A real VT52 doesn't have these, and a VT220 doesn't
4504              * send anything for them in VT52 mode.
4505              */
4506             switch (keysym) {
4507               case PK_HOME:     xkey = 'H'; break;
4508               case PK_INSERT:   xkey = 'L'; break;
4509               case PK_DELETE:   xkey = 'M'; break;
4510               case PK_END:      xkey = 'E'; break;
4511               case PK_PAGEUP:   xkey = 'I'; break;
4512               case PK_PAGEDOWN: xkey = 'G'; break;
4513               default: break; /* else gcc warns `enum value not used' */
4514             }
4515             p += sprintf((char *) p, "\x1B%c", xkey);
4516             goto done;
4517         }
4518
4519         switch (keysym) {
4520           case PK_HOME:     code = 1; break;
4521           case PK_INSERT:   code = 2; break;
4522           case PK_DELETE:   code = 3; break;
4523           case PK_END:      code = 4; break;
4524           case PK_PAGEUP:   code = 5; break;
4525           case PK_PAGEDOWN: code = 6; break;
4526           default: break; /* else gcc warns `enum value not used' */
4527         }
4528         p += sprintf((char *) p, "\x1B[%d~", code);
4529         goto done;
4530     }
4531
4532     if (PK_ISFKEY(keysym)) {
4533         /* Map Shift+F1-F10 to F11-F20 */
4534         if (keysym >= PK_F1 && keysym <= PK_F10 && (modifiers & PKM_SHIFT))
4535             keysym += 10;
4536         if ((term->vt52_mode || term->cfg.funky_type == FUNKY_VT100P) &&
4537             keysym <= PK_F14) {
4538             /* XXX This overrides the XTERM/VT52 mode below */
4539             int offt = 0;
4540             if (keysym >= PK_F6)  offt++;
4541             if (keysym >= PK_F12) offt++;
4542             p += sprintf((char *) p, term->vt52_mode ? "\x1B%c" : "\x1BO%c",
4543                          'P' + keysym - PK_F1 - offt);
4544             goto done;
4545         }
4546         if (term->cfg.funky_type == FUNKY_LINUX && keysym <= PK_F5) {
4547             p += sprintf((char *) p, "\x1B[[%c", 'A' + keysym - PK_F1);
4548             goto done;
4549         }
4550         if (term->cfg.funky_type == FUNKY_XTERM && keysym <= PK_F4) {
4551             if (term->vt52_mode)
4552                 p += sprintf((char *) p, "\x1B%c", 'P' + keysym - PK_F1);
4553             else
4554                 p += sprintf((char *) p, "\x1BO%c", 'P' + keysym - PK_F1);
4555             goto done;
4556         }
4557         p += sprintf((char *) p, "\x1B[%d~", 11 + keysym - PK_F1);
4558         goto done;
4559     }
4560
4561     if (PK_ISCURSOR(keysym)) {
4562         int xkey;
4563
4564         switch (keysym) {
4565           case PK_UP:    xkey = 'A'; break;
4566           case PK_DOWN:  xkey = 'B'; break;
4567           case PK_RIGHT: xkey = 'C'; break;
4568           case PK_LEFT:  xkey = 'D'; break;
4569           case PK_REST:  xkey = 'G'; break; /* centre key on number pad */
4570           default: break; /* else gcc warns `enum value not used' */
4571         }
4572         if (term->vt52_mode)
4573             p += sprintf((char *) p, "\x1B%c", xkey);
4574         else {
4575             int app_flg = (term->app_cursor_keys && !term->cfg.no_applic_c);
4576
4577             /* Useful mapping of Ctrl-arrows */
4578             if (modifiers == PKM_CONTROL)
4579                 app_flg = !app_flg;
4580
4581             if (app_flg)
4582                 p += sprintf((char *) p, "\x1BO%c", xkey);
4583             else
4584                 p += sprintf((char *) p, "\x1B[%c", xkey);
4585         }
4586         goto done;
4587     }
4588
4589   done:
4590     if (p > output || tlen > 0) {
4591         /*
4592          * Interrupt an ongoing paste. I'm not sure
4593          * this is sensible, but for the moment it's
4594          * preferable to having to faff about buffering
4595          * things.
4596          */
4597         term_nopaste(term);
4598
4599         /*
4600          * We need not bother about stdin backlogs
4601          * here, because in GUI PuTTY we can't do
4602          * anything about it anyway; there's no means
4603          * of asking Windows to hold off on KEYDOWN
4604          * messages. We _have_ to buffer everything
4605          * we're sent.
4606          */
4607         term_seen_key_event(term);
4608
4609         if (prependesc) {
4610 #if 0
4611             fprintf(stderr, "sending ESC\n");
4612 #endif
4613             ldisc_send(term->ldisc, "\x1b", 1, 1);
4614         }
4615
4616         if (p > output) {
4617 #if 0
4618             fprintf(stderr, "sending %d bytes:", p - output);
4619             for (i = 0; i < p - output; i++)
4620                 fprintf(stderr, " %02x", output[i]);
4621             fprintf(stderr, "\n");
4622 #endif
4623             ldisc_send(term->ldisc, output, p - output, 1);
4624         } else if (tlen > 0) {
4625 #if 0
4626             fprintf(stderr, "sending %d unichars:", tlen);
4627             for (i = 0; i < tlen; i++)
4628                 fprintf(stderr, " %04x", (unsigned) text[i]);
4629             fprintf(stderr, "\n");
4630 #endif
4631             luni_send(term->ldisc, text, tlen, 1);
4632         }
4633     }
4634 }
4635
4636 void term_nopaste(Terminal *term)
4637 {
4638     if (term->paste_len == 0)
4639         return;
4640     sfree(term->paste_buffer);
4641     term->paste_buffer = NULL;
4642     term->paste_len = 0;
4643 }
4644
4645 int term_paste_pending(Terminal *term)
4646 {
4647     return term->paste_len != 0;
4648 }
4649
4650 void term_paste(Terminal *term)
4651 {
4652     long now, paste_diff;
4653
4654     if (term->paste_len == 0)
4655         return;
4656
4657     /* Don't wait forever to paste */
4658     if (term->paste_hold) {
4659         now = GETTICKCOUNT();
4660         paste_diff = now - term->last_paste;
4661         if (paste_diff >= 0 && paste_diff < 450)
4662             return;
4663     }
4664     term->paste_hold = 0;
4665
4666     while (term->paste_pos < term->paste_len) {
4667         int n = 0;
4668         while (n + term->paste_pos < term->paste_len) {
4669             if (term->paste_buffer[term->paste_pos + n++] == '\015')
4670                 break;
4671         }
4672         if (term->ldisc)
4673             luni_send(term->ldisc, term->paste_buffer + term->paste_pos, n, 0);
4674         term->paste_pos += n;
4675
4676         if (term->paste_pos < term->paste_len) {
4677             term->paste_hold = 1;
4678             return;
4679         }
4680     }
4681     sfree(term->paste_buffer);
4682     term->paste_buffer = NULL;
4683     term->paste_len = 0;
4684 }
4685
4686 static void deselect(Terminal *term)
4687 {
4688     term->selstate = NO_SELECTION;
4689     term->selstart.x = term->selstart.y = term->selend.x = term->selend.y = 0;
4690 }
4691
4692 void term_deselect(Terminal *term)
4693 {
4694     deselect(term);
4695     term_update(term);
4696 }
4697
4698 int term_ldisc(Terminal *term, int option)
4699 {
4700     if (option == LD_ECHO)
4701         return term->term_echoing;
4702     if (option == LD_EDIT)
4703         return term->term_editing;
4704     return FALSE;
4705 }
4706
4707 /*
4708  * from_backend(), to get data from the backend for the terminal.
4709  */
4710 int from_backend(void *vterm, int is_stderr, const char *data, int len)
4711 {
4712     Terminal *term = (Terminal *)vterm;
4713
4714     assert(len > 0);
4715
4716     bufchain_add(&term->inbuf, data, len);
4717
4718     /*
4719      * term_out() always completely empties inbuf. Therefore,
4720      * there's no reason at all to return anything other than zero
4721      * from this function, because there _can't_ be a question of
4722      * the remote side needing to wait until term_out() has cleared
4723      * a backlog.
4724      *
4725      * This is a slightly suboptimal way to deal with SSH2 - in
4726      * principle, the window mechanism would allow us to continue
4727      * to accept data on forwarded ports and X connections even
4728      * while the terminal processing was going slowly - but we
4729      * can't do the 100% right thing without moving the terminal
4730      * processing into a separate thread, and that might hurt
4731      * portability. So we manage stdout buffering the old SSH1 way:
4732      * if the terminal processing goes slowly, the whole SSH
4733      * connection stops accepting data until it's ready.
4734      *
4735      * In practice, I can't imagine this causing serious trouble.
4736      */
4737     return 0;
4738 }
4739
4740 void term_provide_logctx(Terminal *term, void *logctx)
4741 {
4742     term->logctx = logctx;
4743 }