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