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