]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - terminal.c
Revamp the terminal paste mechanism using toplevel callbacks.
[PuTTY.git] / terminal.c
1 /*
2  * Terminal emulator.
3  */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <ctype.h>
8
9 #include <time.h>
10 #include <assert.h>
11 #include "putty.h"
12 #include "terminal.h"
13
14 #define poslt(p1,p2) ( (p1).y < (p2).y || ( (p1).y == (p2).y && (p1).x < (p2).x ) )
15 #define posle(p1,p2) ( (p1).y < (p2).y || ( (p1).y == (p2).y && (p1).x <= (p2).x ) )
16 #define poseq(p1,p2) ( (p1).y == (p2).y && (p1).x == (p2).x )
17 #define posdiff(p1,p2) ( ((p1).y - (p2).y) * (term->cols+1) + (p1).x - (p2).x )
18
19 /* Product-order comparisons for rectangular block selection. */
20 #define posPlt(p1,p2) ( (p1).y <= (p2).y && (p1).x < (p2).x )
21 #define posPle(p1,p2) ( (p1).y <= (p2).y && (p1).x <= (p2).x )
22
23 #define incpos(p) ( (p).x == term->cols ? ((p).x = 0, (p).y++, 1) : ((p).x++, 0) )
24 #define decpos(p) ( (p).x == 0 ? ((p).x = term->cols, (p).y--, 1) : ((p).x--, 0) )
25
26 #define VT52_PLUS
27
28 #define CL_ANSIMIN      0x0001         /* Codes in all ANSI like terminals. */
29 #define CL_VT100        0x0002         /* VT100 */
30 #define CL_VT100AVO     0x0004         /* VT100 +AVO; 132x24 (not 132x14) & attrs */
31 #define CL_VT102        0x0008         /* VT102 */
32 #define CL_VT220        0x0010         /* VT220 */
33 #define CL_VT320        0x0020         /* VT320 */
34 #define CL_VT420        0x0040         /* VT420 */
35 #define CL_VT510        0x0080         /* VT510, NB VT510 includes ANSI */
36 #define CL_VT340TEXT    0x0100         /* VT340 extensions that appear in the VT420 */
37 #define CL_SCOANSI      0x1000         /* SCOANSI not in ANSIMIN. */
38 #define CL_ANSI         0x2000         /* ANSI ECMA-48 not in the VT100..VT420 */
39 #define CL_OTHER        0x4000         /* Others, Xterm, linux, putty, dunno, etc */
40
41 #define TM_VT100        (CL_ANSIMIN|CL_VT100)
42 #define TM_VT100AVO     (TM_VT100|CL_VT100AVO)
43 #define TM_VT102        (TM_VT100AVO|CL_VT102)
44 #define TM_VT220        (TM_VT102|CL_VT220)
45 #define TM_VTXXX        (TM_VT220|CL_VT340TEXT|CL_VT510|CL_VT420|CL_VT320)
46 #define TM_SCOANSI      (CL_ANSIMIN|CL_SCOANSI)
47
48 #define TM_PUTTY        (0xFFFF)
49
50 #define UPDATE_DELAY    ((TICKSPERSEC+49)/50)/* ticks to defer window update */
51 #define TBLINK_DELAY    ((TICKSPERSEC*9+19)/20)/* ticks between text blinks*/
52 #define CBLINK_DELAY    (CURSORBLINK) /* ticks between cursor blinks */
53 #define VBELL_DELAY     (VBELL_TIMEOUT) /* visual bell timeout in ticks */
54
55 #define compatibility(x) \
56     if ( ((CL_##x)&term->compatibility_level) == 0 ) {  \
57        term->termstate=TOPLEVEL;                        \
58        break;                                           \
59     }
60 #define compatibility2(x,y) \
61     if ( ((CL_##x|CL_##y)&term->compatibility_level) == 0 ) { \
62        term->termstate=TOPLEVEL;                        \
63        break;                                           \
64     }
65
66 #define has_compat(x) ( ((CL_##x)&term->compatibility_level) != 0 )
67
68 char *EMPTY_WINDOW_TITLE = "";
69
70 const char sco2ansicolour[] = { 0, 4, 2, 6, 1, 5, 3, 7 };
71
72 #define sel_nl_sz  (sizeof(sel_nl)/sizeof(wchar_t))
73 const wchar_t sel_nl[] = SEL_NL;
74
75 /*
76  * Fetch the character at a particular position in a line array,
77  * for purposes of `wordtype'. The reason this isn't just a simple
78  * array reference is that if the character we find is UCSWIDE,
79  * then we must look one space further to the left.
80  */
81 #define UCSGET(a, x) \
82     ( (x)>0 && (a)[(x)].chr == UCSWIDE ? (a)[(x)-1].chr : (a)[(x)].chr )
83
84 /*
85  * Detect the various aliases of U+0020 SPACE.
86  */
87 #define IS_SPACE_CHR(chr) \
88         ((chr) == 0x20 || (DIRECT_CHAR(chr) && ((chr) & 0xFF) == 0x20))
89
90 /*
91  * Spot magic CSETs.
92  */
93 #define CSET_OF(chr) (DIRECT_CHAR(chr)||DIRECT_FONT(chr) ? (chr)&CSET_MASK : 0)
94
95 /*
96  * Internal prototypes.
97  */
98 static void resizeline(Terminal *, termline *, int);
99 static termline *lineptr(Terminal *, int, int, int);
100 static void unlineptr(termline *);
101 static void do_paint(Terminal *, Context, int);
102 static void erase_lots(Terminal *, int, int, int);
103 static int find_last_nonempty_line(Terminal *, tree234 *);
104 static void swap_screen(Terminal *, int, int, int);
105 static void update_sbar(Terminal *);
106 static void deselect(Terminal *);
107 static void term_print_finish(Terminal *);
108 static void scroll(Terminal *, int, int, int, int);
109 #ifdef OPTIMISE_SCROLL
110 static void scroll_display(Terminal *, int, int, int);
111 #endif /* OPTIMISE_SCROLL */
112 static void term_resume_pasting(Terminal *term);
113 static void term_paste_callback(void *vterm);
114 static void term_paste_queue(Terminal *term, int timed);
115
116 static termline *newline(Terminal *term, int cols, int bce)
117 {
118     termline *line;
119     int j;
120
121     line = snew(termline);
122     line->chars = snewn(cols, termchar);
123     for (j = 0; j < cols; j++)
124         line->chars[j] = (bce ? term->erase_char : term->basic_erase_char);
125     line->cols = line->size = cols;
126     line->lattr = LATTR_NORM;
127     line->temporary = FALSE;
128     line->cc_free = 0;
129
130     return line;
131 }
132
133 static void freeline(termline *line)
134 {
135     if (line) {
136         sfree(line->chars);
137         sfree(line);
138     }
139 }
140
141 static void unlineptr(termline *line)
142 {
143     if (line->temporary)
144         freeline(line);
145 }
146
147 #ifdef TERM_CC_DIAGS
148 /*
149  * Diagnostic function: verify that a termline has a correct
150  * combining character structure.
151  * 
152  * This is a performance-intensive check, so it's no longer enabled
153  * by default.
154  */
155 static void cc_check(termline *line)
156 {
157     unsigned char *flags;
158     int i, j;
159
160     assert(line->size >= line->cols);
161
162     flags = snewn(line->size, unsigned char);
163
164     for (i = 0; i < line->size; i++)
165         flags[i] = (i < line->cols);
166
167     for (i = 0; i < line->cols; i++) {
168         j = i;
169         while (line->chars[j].cc_next) {
170             j += line->chars[j].cc_next;
171             assert(j >= line->cols && j < line->size);
172             assert(!flags[j]);
173             flags[j] = TRUE;
174         }
175     }
176
177     j = line->cc_free;
178     if (j) {
179         while (1) {
180             assert(j >= line->cols && j < line->size);
181             assert(!flags[j]);
182             flags[j] = TRUE;
183             if (line->chars[j].cc_next)
184                 j += line->chars[j].cc_next;
185             else
186                 break;
187         }
188     }
189
190     j = 0;
191     for (i = 0; i < line->size; i++)
192         j += (flags[i] != 0);
193
194     assert(j == line->size);
195
196     sfree(flags);
197 }
198 #endif
199
200 /*
201  * Add a combining character to a character cell.
202  */
203 static void add_cc(termline *line, int col, unsigned long chr)
204 {
205     int newcc;
206
207     assert(col >= 0 && col < line->cols);
208
209     /*
210      * Start by extending the cols array if the free list is empty.
211      */
212     if (!line->cc_free) {
213         int n = line->size;
214         line->size += 16 + (line->size - line->cols) / 2;
215         line->chars = sresize(line->chars, line->size, termchar);
216         line->cc_free = n;
217         while (n < line->size) {
218             if (n+1 < line->size)
219                 line->chars[n].cc_next = 1;
220             else
221                 line->chars[n].cc_next = 0;
222             n++;
223         }
224     }
225
226     /*
227      * Now walk the cc list of the cell in question.
228      */
229     while (line->chars[col].cc_next)
230         col += line->chars[col].cc_next;
231
232     /*
233      * `col' now points at the last cc currently in this cell; so
234      * we simply add another one.
235      */
236     newcc = line->cc_free;
237     if (line->chars[newcc].cc_next)
238         line->cc_free = newcc + line->chars[newcc].cc_next;
239     else
240         line->cc_free = 0;
241     line->chars[newcc].cc_next = 0;
242     line->chars[newcc].chr = chr;
243     line->chars[col].cc_next = newcc - col;
244
245 #ifdef TERM_CC_DIAGS
246     cc_check(line);
247 #endif
248 }
249
250 /*
251  * Clear the combining character list in a character cell.
252  */
253 static void clear_cc(termline *line, int col)
254 {
255     int oldfree, origcol = col;
256
257     assert(col >= 0 && col < line->cols);
258
259     if (!line->chars[col].cc_next)
260         return;                        /* nothing needs doing */
261
262     oldfree = line->cc_free;
263     line->cc_free = col + line->chars[col].cc_next;
264     while (line->chars[col].cc_next)
265         col += line->chars[col].cc_next;
266     if (oldfree)
267         line->chars[col].cc_next = oldfree - col;
268     else
269         line->chars[col].cc_next = 0;
270
271     line->chars[origcol].cc_next = 0;
272
273 #ifdef TERM_CC_DIAGS
274     cc_check(line);
275 #endif
276 }
277
278 /*
279  * Compare two character cells for equality. Special case required
280  * in do_paint() where we override what we expect the chr and attr
281  * fields to be.
282  */
283 static int termchars_equal_override(termchar *a, termchar *b,
284                                     unsigned long bchr, unsigned long battr)
285 {
286     /* FULL-TERMCHAR */
287     if (a->chr != bchr)
288         return FALSE;
289     if ((a->attr &~ DATTR_MASK) != (battr &~ DATTR_MASK))
290         return FALSE;
291     while (a->cc_next || b->cc_next) {
292         if (!a->cc_next || !b->cc_next)
293             return FALSE;              /* one cc-list ends, other does not */
294         a += a->cc_next;
295         b += b->cc_next;
296         if (a->chr != b->chr)
297             return FALSE;
298     }
299     return TRUE;
300 }
301
302 static int termchars_equal(termchar *a, termchar *b)
303 {
304     return termchars_equal_override(a, b, b->chr, b->attr);
305 }
306
307 /*
308  * Copy a character cell. (Requires a pointer to the destination
309  * termline, so as to access its free list.)
310  */
311 static void copy_termchar(termline *destline, int x, termchar *src)
312 {
313     clear_cc(destline, x);
314
315     destline->chars[x] = *src;         /* copy everything except cc-list */
316     destline->chars[x].cc_next = 0;    /* and make sure this is zero */
317
318     while (src->cc_next) {
319         src += src->cc_next;
320         add_cc(destline, x, src->chr);
321     }
322
323 #ifdef TERM_CC_DIAGS
324     cc_check(destline);
325 #endif
326 }
327
328 /*
329  * Move a character cell within its termline.
330  */
331 static void move_termchar(termline *line, termchar *dest, termchar *src)
332 {
333     /* First clear the cc list from the original char, just in case. */
334     clear_cc(line, dest - line->chars);
335
336     /* Move the character cell and adjust its cc_next. */
337     *dest = *src;                      /* copy everything except cc-list */
338     if (src->cc_next)
339         dest->cc_next = src->cc_next - (dest-src);
340
341     /* Ensure the original cell doesn't have a cc list. */
342     src->cc_next = 0;
343
344 #ifdef TERM_CC_DIAGS
345     cc_check(line);
346 #endif
347 }
348
349 /*
350  * Compress and decompress a termline into an RLE-based format for
351  * storing in scrollback. (Since scrollback almost never needs to
352  * be modified and exists in huge quantities, this is a sensible
353  * tradeoff, particularly since it allows us to continue adding
354  * features to the main termchar structure without proportionally
355  * bloating the terminal emulator's memory footprint unless those
356  * features are in constant use.)
357  */
358 struct buf {
359     unsigned char *data;
360     int len, size;
361 };
362 static void add(struct buf *b, unsigned char c)
363 {
364     if (b->len >= b->size) {
365         b->size = (b->len * 3 / 2) + 512;
366         b->data = sresize(b->data, b->size, unsigned char);
367     }
368     b->data[b->len++] = c;
369 }
370 static int get(struct buf *b)
371 {
372     return b->data[b->len++];
373 }
374 static void makerle(struct buf *b, termline *ldata,
375                     void (*makeliteral)(struct buf *b, termchar *c,
376                                         unsigned long *state))
377 {
378     int hdrpos, hdrsize, n, prevlen, prevpos, thislen, thispos, prev2;
379     termchar *c = ldata->chars;
380     unsigned long state = 0, oldstate;
381
382     n = ldata->cols;
383
384     hdrpos = b->len;
385     hdrsize = 0;
386     add(b, 0);
387     prevlen = prevpos = 0;
388     prev2 = FALSE;
389
390     while (n-- > 0) {
391         thispos = b->len;
392         makeliteral(b, c++, &state);
393         thislen = b->len - thispos;
394         if (thislen == prevlen &&
395             !memcmp(b->data + prevpos, b->data + thispos, thislen)) {
396             /*
397              * This literal precisely matches the previous one.
398              * Turn it into a run if it's worthwhile.
399              * 
400              * With one-byte literals, it costs us two bytes to
401              * encode a run, plus another byte to write the header
402              * to resume normal output; so a three-element run is
403              * neutral, and anything beyond that is unconditionally
404              * worthwhile. With two-byte literals or more, even a
405              * 2-run is a win.
406              */
407             if (thislen > 1 || prev2) {
408                 int runpos, runlen;
409
410                 /*
411                  * It's worth encoding a run. Start at prevpos,
412                  * unless hdrsize==0 in which case we can back up
413                  * another one and start by overwriting hdrpos.
414                  */
415
416                 hdrsize--;             /* remove the literal at prevpos */
417                 if (prev2) {
418                     assert(hdrsize > 0);
419                     hdrsize--;
420                     prevpos -= prevlen;/* and possibly another one */
421                 }
422
423                 if (hdrsize == 0) {
424                     assert(prevpos == hdrpos + 1);
425                     runpos = hdrpos;
426                     b->len = prevpos+prevlen;
427                 } else {
428                     memmove(b->data + prevpos+1, b->data + prevpos, prevlen);
429                     runpos = prevpos;
430                     b->len = prevpos+prevlen+1;
431                     /*
432                      * Terminate the previous run of ordinary
433                      * literals.
434                      */
435                     assert(hdrsize >= 1 && hdrsize <= 128);
436                     b->data[hdrpos] = hdrsize - 1;
437                 }
438
439                 runlen = prev2 ? 3 : 2;
440
441                 while (n > 0 && runlen < 129) {
442                     int tmppos, tmplen;
443                     tmppos = b->len;
444                     oldstate = state;
445                     makeliteral(b, c, &state);
446                     tmplen = b->len - tmppos;
447                     b->len = tmppos;
448                     if (tmplen != thislen ||
449                         memcmp(b->data + runpos+1, b->data + tmppos, tmplen)) {
450                         state = oldstate;
451                         break;         /* run over */
452                     }
453                     n--, c++, runlen++;
454                 }
455
456                 assert(runlen >= 2 && runlen <= 129);
457                 b->data[runpos] = runlen + 0x80 - 2;
458
459                 hdrpos = b->len;
460                 hdrsize = 0;
461                 add(b, 0);
462                 /* And ensure this run doesn't interfere with the next. */
463                 prevlen = prevpos = 0;
464                 prev2 = FALSE;
465
466                 continue;
467             } else {
468                 /*
469                  * Just flag that the previous two literals were
470                  * identical, in case we find a third identical one
471                  * we want to turn into a run.
472                  */
473                 prev2 = TRUE;
474                 prevlen = thislen;
475                 prevpos = thispos;
476             }
477         } else {
478             prev2 = FALSE;
479             prevlen = thislen;
480             prevpos = thispos;
481         }
482
483         /*
484          * This character isn't (yet) part of a run. Add it to
485          * hdrsize.
486          */
487         hdrsize++;
488         if (hdrsize == 128) {
489             b->data[hdrpos] = hdrsize - 1;
490             hdrpos = b->len;
491             hdrsize = 0;
492             add(b, 0);
493             prevlen = prevpos = 0;
494             prev2 = FALSE;
495         }
496     }
497
498     /*
499      * Clean up.
500      */
501     if (hdrsize > 0) {
502         assert(hdrsize <= 128);
503         b->data[hdrpos] = hdrsize - 1;
504     } else {
505         b->len = hdrpos;
506     }
507 }
508 static void makeliteral_chr(struct buf *b, termchar *c, unsigned long *state)
509 {
510     /*
511      * My encoding for characters is UTF-8-like, in that it stores
512      * 7-bit ASCII in one byte and uses high-bit-set bytes as
513      * introducers to indicate a longer sequence. However, it's
514      * unlike UTF-8 in that it doesn't need to be able to
515      * resynchronise, and therefore I don't want to waste two bits
516      * per byte on having recognisable continuation characters.
517      * Also I don't want to rule out the possibility that I may one
518      * day use values 0x80000000-0xFFFFFFFF for interesting
519      * purposes, so unlike UTF-8 I need a full 32-bit range.
520      * Accordingly, here is my encoding:
521      * 
522      * 00000000-0000007F: 0xxxxxxx (but see below)
523      * 00000080-00003FFF: 10xxxxxx xxxxxxxx
524      * 00004000-001FFFFF: 110xxxxx xxxxxxxx xxxxxxxx
525      * 00200000-0FFFFFFF: 1110xxxx xxxxxxxx xxxxxxxx xxxxxxxx
526      * 10000000-FFFFFFFF: 11110ZZZ xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx
527      * 
528      * (`Z' is like `x' but is always going to be zero since the
529      * values I'm encoding don't go above 2^32. In principle the
530      * five-byte form of the encoding could extend to 2^35, and
531      * there could be six-, seven-, eight- and nine-byte forms as
532      * well to allow up to 64-bit values to be encoded. But that's
533      * completely unnecessary for these purposes!)
534      * 
535      * The encoding as written above would be very simple, except
536      * that 7-bit ASCII can occur in several different ways in the
537      * terminal data; sometimes it crops up in the D800 page
538      * (CSET_ASCII) but at other times it's in the 0000 page (real
539      * Unicode). Therefore, this encoding is actually _stateful_:
540      * the one-byte encoding of 00-7F actually indicates `reuse the
541      * upper three bytes of the last character', and to encode an
542      * absolute value of 00-7F you need to use the two-byte form
543      * instead.
544      */
545     if ((c->chr & ~0x7F) == *state) {
546         add(b, (unsigned char)(c->chr & 0x7F));
547     } else if (c->chr < 0x4000) {
548         add(b, (unsigned char)(((c->chr >> 8) & 0x3F) | 0x80));
549         add(b, (unsigned char)(c->chr & 0xFF));
550     } else if (c->chr < 0x200000) {
551         add(b, (unsigned char)(((c->chr >> 16) & 0x1F) | 0xC0));
552         add(b, (unsigned char)((c->chr >> 8) & 0xFF));
553         add(b, (unsigned char)(c->chr & 0xFF));
554     } else if (c->chr < 0x10000000) {
555         add(b, (unsigned char)(((c->chr >> 24) & 0x0F) | 0xE0));
556         add(b, (unsigned char)((c->chr >> 16) & 0xFF));
557         add(b, (unsigned char)((c->chr >> 8) & 0xFF));
558         add(b, (unsigned char)(c->chr & 0xFF));
559     } else {
560         add(b, 0xF0);
561         add(b, (unsigned char)((c->chr >> 24) & 0xFF));
562         add(b, (unsigned char)((c->chr >> 16) & 0xFF));
563         add(b, (unsigned char)((c->chr >> 8) & 0xFF));
564         add(b, (unsigned char)(c->chr & 0xFF));
565     }
566     *state = c->chr & ~0xFF;
567 }
568 static void makeliteral_attr(struct buf *b, termchar *c, unsigned long *state)
569 {
570     /*
571      * My encoding for attributes is 16-bit-granular and assumes
572      * that the top bit of the word is never required. I either
573      * store a two-byte value with the top bit clear (indicating
574      * just that value), or a four-byte value with the top bit set
575      * (indicating the same value with its top bit clear).
576      * 
577      * However, first I permute the bits of the attribute value, so
578      * that the eight bits of colour (four in each of fg and bg)
579      * which are never non-zero unless xterm 256-colour mode is in
580      * use are placed higher up the word than everything else. This
581      * ensures that attribute values remain 16-bit _unless_ the
582      * user uses extended colour.
583      */
584     unsigned attr, colourbits;
585
586     attr = c->attr;
587
588     assert(ATTR_BGSHIFT > ATTR_FGSHIFT);
589
590     colourbits = (attr >> (ATTR_BGSHIFT + 4)) & 0xF;
591     colourbits <<= 4;
592     colourbits |= (attr >> (ATTR_FGSHIFT + 4)) & 0xF;
593
594     attr = (((attr >> (ATTR_BGSHIFT + 8)) << (ATTR_BGSHIFT + 4)) |
595             (attr & ((1 << (ATTR_BGSHIFT + 4))-1)));
596     attr = (((attr >> (ATTR_FGSHIFT + 8)) << (ATTR_FGSHIFT + 4)) |
597             (attr & ((1 << (ATTR_FGSHIFT + 4))-1)));
598
599     attr |= (colourbits << (32-9));
600
601     if (attr < 0x8000) {
602         add(b, (unsigned char)((attr >> 8) & 0xFF));
603         add(b, (unsigned char)(attr & 0xFF));
604     } else {
605         add(b, (unsigned char)(((attr >> 24) & 0x7F) | 0x80));
606         add(b, (unsigned char)((attr >> 16) & 0xFF));
607         add(b, (unsigned char)((attr >> 8) & 0xFF));
608         add(b, (unsigned char)(attr & 0xFF));
609     }
610 }
611 static void makeliteral_cc(struct buf *b, termchar *c, unsigned long *state)
612 {
613     /*
614      * For combining characters, I just encode a bunch of ordinary
615      * chars using makeliteral_chr, and terminate with a \0
616      * character (which I know won't come up as a combining char
617      * itself).
618      * 
619      * I don't use the stateful encoding in makeliteral_chr.
620      */
621     unsigned long zstate;
622     termchar z;
623
624     while (c->cc_next) {
625         c += c->cc_next;
626
627         assert(c->chr != 0);
628
629         zstate = 0;
630         makeliteral_chr(b, c, &zstate);
631     }
632
633     z.chr = 0;
634     zstate = 0;
635     makeliteral_chr(b, &z, &zstate);
636 }
637
638 static termline *decompressline(unsigned char *data, int *bytes_used);
639
640 static unsigned char *compressline(termline *ldata)
641 {
642     struct buf buffer = { NULL, 0, 0 }, *b = &buffer;
643
644     /*
645      * First, store the column count, 7 bits at a time, least
646      * significant `digit' first, with the high bit set on all but
647      * the last.
648      */
649     {
650         int n = ldata->cols;
651         while (n >= 128) {
652             add(b, (unsigned char)((n & 0x7F) | 0x80));
653             n >>= 7;
654         }
655         add(b, (unsigned char)(n));
656     }
657
658     /*
659      * Next store the lattrs; same principle.
660      */
661     {
662         int n = ldata->lattr;
663         while (n >= 128) {
664             add(b, (unsigned char)((n & 0x7F) | 0x80));
665             n >>= 7;
666         }
667         add(b, (unsigned char)(n));
668     }
669
670     /*
671      * Now we store a sequence of separate run-length encoded
672      * fragments, each containing exactly as many symbols as there
673      * are columns in the ldata.
674      * 
675      * All of these have a common basic format:
676      * 
677      *  - a byte 00-7F indicates that X+1 literals follow it
678      *  - a byte 80-FF indicates that a single literal follows it
679      *    and expects to be repeated (X-0x80)+2 times.
680      * 
681      * The format of the `literals' varies between the fragments.
682      */
683     makerle(b, ldata, makeliteral_chr);
684     makerle(b, ldata, makeliteral_attr);
685     makerle(b, ldata, makeliteral_cc);
686
687     /*
688      * Diagnostics: ensure that the compressed data really does
689      * decompress to the right thing.
690      * 
691      * This is a bit performance-heavy for production code.
692      */
693 #ifdef TERM_CC_DIAGS
694 #ifndef CHECK_SB_COMPRESSION
695     {
696         int dused;
697         termline *dcl;
698         int i;
699
700 #ifdef DIAGNOSTIC_SB_COMPRESSION
701         for (i = 0; i < b->len; i++) {
702             printf(" %02x ", b->data[i]);
703         }
704         printf("\n");
705 #endif
706
707         dcl = decompressline(b->data, &dused);
708         assert(b->len == dused);
709         assert(ldata->cols == dcl->cols);
710         assert(ldata->lattr == dcl->lattr);
711         for (i = 0; i < ldata->cols; i++)
712             assert(termchars_equal(&ldata->chars[i], &dcl->chars[i]));
713
714 #ifdef DIAGNOSTIC_SB_COMPRESSION
715         printf("%d cols (%d bytes) -> %d bytes (factor of %g)\n",
716                ldata->cols, 4 * ldata->cols, dused,
717                (double)dused / (4 * ldata->cols));
718 #endif
719
720         freeline(dcl);
721     }
722 #endif
723 #endif /* TERM_CC_DIAGS */
724
725     /*
726      * Trim the allocated memory so we don't waste any, and return.
727      */
728     return sresize(b->data, b->len, unsigned char);
729 }
730
731 static void readrle(struct buf *b, termline *ldata,
732                     void (*readliteral)(struct buf *b, termchar *c,
733                                         termline *ldata, unsigned long *state))
734 {
735     int n = 0;
736     unsigned long state = 0;
737
738     while (n < ldata->cols) {
739         int hdr = get(b);
740
741         if (hdr >= 0x80) {
742             /* A run. */
743
744             int pos = b->len, count = hdr + 2 - 0x80;
745             while (count--) {
746                 assert(n < ldata->cols);
747                 b->len = pos;
748                 readliteral(b, ldata->chars + n, ldata, &state);
749                 n++;
750             }
751         } else {
752             /* Just a sequence of consecutive literals. */
753
754             int count = hdr + 1;
755             while (count--) {
756                 assert(n < ldata->cols);
757                 readliteral(b, ldata->chars + n, ldata, &state);
758                 n++;
759             }
760         }
761     }
762
763     assert(n == ldata->cols);
764 }
765 static void readliteral_chr(struct buf *b, termchar *c, termline *ldata,
766                             unsigned long *state)
767 {
768     int byte;
769
770     /*
771      * 00000000-0000007F: 0xxxxxxx
772      * 00000080-00003FFF: 10xxxxxx xxxxxxxx
773      * 00004000-001FFFFF: 110xxxxx xxxxxxxx xxxxxxxx
774      * 00200000-0FFFFFFF: 1110xxxx xxxxxxxx xxxxxxxx xxxxxxxx
775      * 10000000-FFFFFFFF: 11110ZZZ xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx
776      */
777
778     byte = get(b);
779     if (byte < 0x80) {
780         c->chr = byte | *state;
781     } else if (byte < 0xC0) {
782         c->chr = (byte &~ 0xC0) << 8;
783         c->chr |= get(b);
784     } else if (byte < 0xE0) {
785         c->chr = (byte &~ 0xE0) << 16;
786         c->chr |= get(b) << 8;
787         c->chr |= get(b);
788     } else if (byte < 0xF0) {
789         c->chr = (byte &~ 0xF0) << 24;
790         c->chr |= get(b) << 16;
791         c->chr |= get(b) << 8;
792         c->chr |= get(b);
793     } else {
794         assert(byte == 0xF0);
795         c->chr = get(b) << 24;
796         c->chr |= get(b) << 16;
797         c->chr |= get(b) << 8;
798         c->chr |= get(b);
799     }
800     *state = c->chr & ~0xFF;
801 }
802 static void readliteral_attr(struct buf *b, termchar *c, termline *ldata,
803                              unsigned long *state)
804 {
805     unsigned val, attr, colourbits;
806
807     val = get(b) << 8;
808     val |= get(b);
809
810     if (val >= 0x8000) {
811         val &= ~0x8000;
812         val <<= 16;
813         val |= get(b) << 8;
814         val |= get(b);
815     }
816
817     colourbits = (val >> (32-9)) & 0xFF;
818     attr = (val & ((1<<(32-9))-1));
819
820     attr = (((attr >> (ATTR_FGSHIFT + 4)) << (ATTR_FGSHIFT + 8)) |
821             (attr & ((1 << (ATTR_FGSHIFT + 4))-1)));
822     attr = (((attr >> (ATTR_BGSHIFT + 4)) << (ATTR_BGSHIFT + 8)) |
823             (attr & ((1 << (ATTR_BGSHIFT + 4))-1)));
824
825     attr |= (colourbits >> 4) << (ATTR_BGSHIFT + 4);
826     attr |= (colourbits & 0xF) << (ATTR_FGSHIFT + 4);
827
828     c->attr = attr;
829 }
830 static void readliteral_cc(struct buf *b, termchar *c, termline *ldata,
831                            unsigned long *state)
832 {
833     termchar n;
834     unsigned long zstate;
835     int x = c - ldata->chars;
836
837     c->cc_next = 0;
838
839     while (1) {
840         zstate = 0;
841         readliteral_chr(b, &n, ldata, &zstate);
842         if (!n.chr)
843             break;
844         add_cc(ldata, x, n.chr);
845     }
846 }
847
848 static termline *decompressline(unsigned char *data, int *bytes_used)
849 {
850     int ncols, byte, shift;
851     struct buf buffer, *b = &buffer;
852     termline *ldata;
853
854     b->data = data;
855     b->len = 0;
856
857     /*
858      * First read in the column count.
859      */
860     ncols = shift = 0;
861     do {
862         byte = get(b);
863         ncols |= (byte & 0x7F) << shift;
864         shift += 7;
865     } while (byte & 0x80);
866
867     /*
868      * Now create the output termline.
869      */
870     ldata = snew(termline);
871     ldata->chars = snewn(ncols, termchar);
872     ldata->cols = ldata->size = ncols;
873     ldata->temporary = TRUE;
874     ldata->cc_free = 0;
875
876     /*
877      * We must set all the cc pointers in ldata->chars to 0 right
878      * now, so that cc diagnostics that verify the integrity of the
879      * whole line will make sense while we're in the middle of
880      * building it up.
881      */
882     {
883         int i;
884         for (i = 0; i < ldata->cols; i++)
885             ldata->chars[i].cc_next = 0;
886     }
887
888     /*
889      * Now read in the lattr.
890      */
891     ldata->lattr = shift = 0;
892     do {
893         byte = get(b);
894         ldata->lattr |= (byte & 0x7F) << shift;
895         shift += 7;
896     } while (byte & 0x80);
897
898     /*
899      * Now we read in each of the RLE streams in turn.
900      */
901     readrle(b, ldata, readliteral_chr);
902     readrle(b, ldata, readliteral_attr);
903     readrle(b, ldata, readliteral_cc);
904
905     /* Return the number of bytes read, for diagnostic purposes. */
906     if (bytes_used)
907         *bytes_used = b->len;
908
909     return ldata;
910 }
911
912 /*
913  * Resize a line to make it `cols' columns wide.
914  */
915 static void resizeline(Terminal *term, termline *line, int cols)
916 {
917     int i, oldcols;
918
919     if (line->cols != cols) {
920
921         oldcols = line->cols;
922
923         /*
924          * This line is the wrong length, which probably means it
925          * hasn't been accessed since a resize. Resize it now.
926          * 
927          * First, go through all the characters that will be thrown
928          * out in the resize (if we're shrinking the line) and
929          * return their cc lists to the cc free list.
930          */
931         for (i = cols; i < oldcols; i++)
932             clear_cc(line, i);
933
934         /*
935          * If we're shrinking the line, we now bodily move the
936          * entire cc section from where it started to where it now
937          * needs to be. (We have to do this before the resize, so
938          * that the data we're copying is still there. However, if
939          * we're expanding, we have to wait until _after_ the
940          * resize so that the space we're copying into is there.)
941          */
942         if (cols < oldcols)
943             memmove(line->chars + cols, line->chars + oldcols,
944                     (line->size - line->cols) * TSIZE);
945
946         /*
947          * Now do the actual resize, leaving the _same_ amount of
948          * cc space as there was to begin with.
949          */
950         line->size += cols - oldcols;
951         line->chars = sresize(line->chars, line->size, TTYPE);
952         line->cols = cols;
953
954         /*
955          * If we're expanding the line, _now_ we move the cc
956          * section.
957          */
958         if (cols > oldcols)
959             memmove(line->chars + cols, line->chars + oldcols,
960                     (line->size - line->cols) * TSIZE);
961
962         /*
963          * Go through what's left of the original line, and adjust
964          * the first cc_next pointer in each list. (All the
965          * subsequent ones are still valid because they are
966          * relative offsets within the cc block.) Also do the same
967          * to the head of the cc_free list.
968          */
969         for (i = 0; i < oldcols && i < cols; i++)
970             if (line->chars[i].cc_next)
971                 line->chars[i].cc_next += cols - oldcols;
972         if (line->cc_free)
973             line->cc_free += cols - oldcols;
974
975         /*
976          * And finally fill in the new space with erase chars. (We
977          * don't have to worry about cc lists here, because we
978          * _know_ the erase char doesn't have one.)
979          */
980         for (i = oldcols; i < cols; i++)
981             line->chars[i] = term->basic_erase_char;
982
983 #ifdef TERM_CC_DIAGS
984         cc_check(line);
985 #endif
986     }
987 }
988
989 /*
990  * Get the number of lines in the scrollback.
991  */
992 static int sblines(Terminal *term)
993 {
994     int sblines = count234(term->scrollback);
995     if (term->erase_to_scrollback &&
996         term->alt_which && term->alt_screen) {
997             sblines += term->alt_sblines;
998     }
999     return sblines;
1000 }
1001
1002 /*
1003  * Retrieve a line of the screen or of the scrollback, according to
1004  * whether the y coordinate is non-negative or negative
1005  * (respectively).
1006  */
1007 static termline *lineptr(Terminal *term, int y, int lineno, int screen)
1008 {
1009     termline *line;
1010     tree234 *whichtree;
1011     int treeindex;
1012
1013     if (y >= 0) {
1014         whichtree = term->screen;
1015         treeindex = y;
1016     } else {
1017         int altlines = 0;
1018
1019         assert(!screen);
1020
1021         if (term->erase_to_scrollback &&
1022             term->alt_which && term->alt_screen) {
1023             altlines = term->alt_sblines;
1024         }
1025         if (y < -altlines) {
1026             whichtree = term->scrollback;
1027             treeindex = y + altlines + count234(term->scrollback);
1028         } else {
1029             whichtree = term->alt_screen;
1030             treeindex = y + term->alt_sblines;
1031             /* treeindex = y + count234(term->alt_screen); */
1032         }
1033     }
1034     if (whichtree == term->scrollback) {
1035         unsigned char *cline = index234(whichtree, treeindex);
1036         line = decompressline(cline, NULL);
1037     } else {
1038         line = index234(whichtree, treeindex);
1039     }
1040
1041     /* We assume that we don't screw up and retrieve something out of range. */
1042     if (line == NULL) {
1043         fatalbox("line==NULL in terminal.c\n"
1044                  "lineno=%d y=%d w=%d h=%d\n"
1045                  "count(scrollback=%p)=%d\n"
1046                  "count(screen=%p)=%d\n"
1047                  "count(alt=%p)=%d alt_sblines=%d\n"
1048                  "whichtree=%p treeindex=%d\n\n"
1049                  "Please contact <putty@projects.tartarus.org> "
1050                  "and pass on the above information.",
1051                  lineno, y, term->cols, term->rows,
1052                  term->scrollback, count234(term->scrollback),
1053                  term->screen, count234(term->screen),
1054                  term->alt_screen, count234(term->alt_screen), term->alt_sblines,
1055                  whichtree, treeindex);
1056     }
1057     assert(line != NULL);
1058
1059     resizeline(term, line, term->cols);
1060     /* FIXME: should we sort the compressed scrollback out here? */
1061
1062     return line;
1063 }
1064
1065 #define lineptr(x) (lineptr)(term,x,__LINE__,FALSE)
1066 #define scrlineptr(x) (lineptr)(term,x,__LINE__,TRUE)
1067
1068 static void term_schedule_tblink(Terminal *term);
1069 static void term_schedule_cblink(Terminal *term);
1070
1071 static void term_timer(void *ctx, unsigned long now)
1072 {
1073     Terminal *term = (Terminal *)ctx;
1074     int update = FALSE;
1075
1076     if (term->tblink_pending && now == term->next_tblink) {
1077         term->tblinker = !term->tblinker;
1078         term->tblink_pending = FALSE;
1079         term_schedule_tblink(term);
1080         update = TRUE;
1081     }
1082
1083     if (term->cblink_pending && now == term->next_cblink) {
1084         term->cblinker = !term->cblinker;
1085         term->cblink_pending = FALSE;
1086         term_schedule_cblink(term);
1087         update = TRUE;
1088     }
1089
1090     if (term->in_vbell && now == term->vbell_end) {
1091         term->in_vbell = FALSE;
1092         update = TRUE;
1093     }
1094
1095     if (update ||
1096         (term->window_update_pending && now == term->next_update))
1097         term_update(term);
1098 }
1099
1100 static void term_schedule_update(Terminal *term)
1101 {
1102     if (!term->window_update_pending) {
1103         term->window_update_pending = TRUE;
1104         term->next_update = schedule_timer(UPDATE_DELAY, term_timer, term);
1105     }
1106 }
1107
1108 /*
1109  * Call this whenever the terminal window state changes, to queue
1110  * an update.
1111  */
1112 static void seen_disp_event(Terminal *term)
1113 {
1114     term->seen_disp_event = TRUE;      /* for scrollback-reset-on-activity */
1115     term_schedule_update(term);
1116 }
1117
1118 /*
1119  * Call when the terminal's blinking-text settings change, or when
1120  * a text blink has just occurred.
1121  */
1122 static void term_schedule_tblink(Terminal *term)
1123 {
1124     if (term->blink_is_real) {
1125         if (!term->tblink_pending)
1126             term->next_tblink = schedule_timer(TBLINK_DELAY, term_timer, term);
1127         term->tblink_pending = TRUE;
1128     } else {
1129         term->tblinker = 1;            /* reset when not in use */
1130         term->tblink_pending = FALSE;
1131     }
1132 }
1133
1134 /*
1135  * Likewise with cursor blinks.
1136  */
1137 static void term_schedule_cblink(Terminal *term)
1138 {
1139     if (term->blink_cur && term->has_focus) {
1140         if (!term->cblink_pending)
1141             term->next_cblink = schedule_timer(CBLINK_DELAY, term_timer, term);
1142         term->cblink_pending = TRUE;
1143     } else {
1144         term->cblinker = 1;            /* reset when not in use */
1145         term->cblink_pending = FALSE;
1146     }
1147 }
1148
1149 /*
1150  * Call to reset cursor blinking on new output.
1151  */
1152 static void term_reset_cblink(Terminal *term)
1153 {
1154     seen_disp_event(term);
1155     term->cblinker = 1;
1156     term->cblink_pending = FALSE;
1157     term_schedule_cblink(term);
1158 }
1159
1160 /*
1161  * Call to begin a visual bell.
1162  */
1163 static void term_schedule_vbell(Terminal *term, int already_started,
1164                                 long startpoint)
1165 {
1166     long ticks_already_gone;
1167
1168     if (already_started)
1169         ticks_already_gone = GETTICKCOUNT() - startpoint;
1170     else
1171         ticks_already_gone = 0;
1172
1173     if (ticks_already_gone < VBELL_DELAY) {
1174         term->in_vbell = TRUE;
1175         term->vbell_end = schedule_timer(VBELL_DELAY - ticks_already_gone,
1176                                          term_timer, term);
1177     } else {
1178         term->in_vbell = FALSE;
1179     }
1180 }
1181
1182 /*
1183  * Set up power-on settings for the terminal.
1184  * If 'clear' is false, don't actually clear the primary screen, and
1185  * position the cursor below the last non-blank line (scrolling if
1186  * necessary).
1187  */
1188 static void power_on(Terminal *term, int clear)
1189 {
1190     term->alt_x = term->alt_y = 0;
1191     term->savecurs.x = term->savecurs.y = 0;
1192     term->alt_savecurs.x = term->alt_savecurs.y = 0;
1193     term->alt_t = term->marg_t = 0;
1194     if (term->rows != -1)
1195         term->alt_b = term->marg_b = term->rows - 1;
1196     else
1197         term->alt_b = term->marg_b = 0;
1198     if (term->cols != -1) {
1199         int i;
1200         for (i = 0; i < term->cols; i++)
1201             term->tabs[i] = (i % 8 == 0 ? TRUE : FALSE);
1202     }
1203     term->alt_om = term->dec_om = conf_get_int(term->conf, CONF_dec_om);
1204     term->alt_ins = term->insert = FALSE;
1205     term->alt_wnext = term->wrapnext =
1206         term->save_wnext = term->alt_save_wnext = FALSE;
1207     term->alt_wrap = term->wrap = conf_get_int(term->conf, CONF_wrap_mode);
1208     term->alt_cset = term->cset = term->save_cset = term->alt_save_cset = 0;
1209     term->alt_utf = term->utf = term->save_utf = term->alt_save_utf = 0;
1210     term->utf_state = 0;
1211     term->alt_sco_acs = term->sco_acs =
1212         term->save_sco_acs = term->alt_save_sco_acs = 0;
1213     term->cset_attr[0] = term->cset_attr[1] =
1214         term->save_csattr = term->alt_save_csattr = CSET_ASCII;
1215     term->rvideo = 0;
1216     term->in_vbell = FALSE;
1217     term->cursor_on = 1;
1218     term->big_cursor = 0;
1219     term->default_attr = term->save_attr =
1220         term->alt_save_attr = term->curr_attr = ATTR_DEFAULT;
1221     term->term_editing = term->term_echoing = FALSE;
1222     term->app_cursor_keys = conf_get_int(term->conf, CONF_app_cursor);
1223     term->app_keypad_keys = conf_get_int(term->conf, CONF_app_keypad);
1224     term->use_bce = conf_get_int(term->conf, CONF_bce);
1225     term->blink_is_real = conf_get_int(term->conf, CONF_blinktext);
1226     term->erase_char = term->basic_erase_char;
1227     term->alt_which = 0;
1228     term_print_finish(term);
1229     term->xterm_mouse = 0;
1230     term->xterm_extended_mouse = 0;
1231     term->urxvt_extended_mouse = 0;
1232     set_raw_mouse_mode(term->frontend, FALSE);
1233     term->bracketed_paste = FALSE;
1234     {
1235         int i;
1236         for (i = 0; i < 256; i++)
1237             term->wordness[i] = conf_get_int_int(term->conf, CONF_wordness, i);
1238     }
1239     if (term->screen) {
1240         swap_screen(term, 1, FALSE, FALSE);
1241         erase_lots(term, FALSE, TRUE, TRUE);
1242         swap_screen(term, 0, FALSE, FALSE);
1243         if (clear)
1244             erase_lots(term, FALSE, TRUE, TRUE);
1245         term->curs.y = find_last_nonempty_line(term, term->screen) + 1;
1246         if (term->curs.y == term->rows) {
1247             term->curs.y--;
1248             scroll(term, 0, term->rows - 1, 1, TRUE);
1249         }
1250     } else {
1251         term->curs.y = 0;
1252     }
1253     term->curs.x = 0;
1254     term_schedule_tblink(term);
1255     term_schedule_cblink(term);
1256 }
1257
1258 /*
1259  * Force a screen update.
1260  */
1261 void term_update(Terminal *term)
1262 {
1263     Context ctx;
1264
1265     term->window_update_pending = FALSE;
1266
1267     ctx = get_ctx(term->frontend);
1268     if (ctx) {
1269         int need_sbar_update = term->seen_disp_event;
1270         if (term->seen_disp_event && term->scroll_on_disp) {
1271             term->disptop = 0;         /* return to main screen */
1272             term->seen_disp_event = 0;
1273             need_sbar_update = TRUE;
1274         }
1275
1276         if (need_sbar_update)
1277             update_sbar(term);
1278         do_paint(term, ctx, TRUE);
1279         sys_cursor(term->frontend, term->curs.x, term->curs.y - term->disptop);
1280         free_ctx(ctx);
1281     }
1282 }
1283
1284 /*
1285  * Called from front end when a keypress occurs, to trigger
1286  * anything magical that needs to happen in that situation.
1287  */
1288 void term_seen_key_event(Terminal *term)
1289 {
1290     /*
1291      * On any keypress, clear the bell overload mechanism
1292      * completely, on the grounds that large numbers of
1293      * beeps coming from deliberate key action are likely
1294      * to be intended (e.g. beeps from filename completion
1295      * blocking repeatedly).
1296      */
1297     term->beep_overloaded = FALSE;
1298     while (term->beephead) {
1299         struct beeptime *tmp = term->beephead;
1300         term->beephead = tmp->next;
1301         sfree(tmp);
1302     }
1303     term->beeptail = NULL;
1304     term->nbeeps = 0;
1305
1306     /*
1307      * Reset the scrollback on keypress, if we're doing that.
1308      */
1309     if (term->scroll_on_key) {
1310         term->disptop = 0;             /* return to main screen */
1311         seen_disp_event(term);
1312     }
1313 }
1314
1315 /*
1316  * Same as power_on(), but an external function.
1317  */
1318 void term_pwron(Terminal *term, int clear)
1319 {
1320     power_on(term, clear);
1321     if (term->ldisc)                   /* cause ldisc to notice changes */
1322         ldisc_send(term->ldisc, NULL, 0, 0);
1323     term->disptop = 0;
1324     deselect(term);
1325     term_update(term);
1326 }
1327
1328 static void set_erase_char(Terminal *term)
1329 {
1330     term->erase_char = term->basic_erase_char;
1331     if (term->use_bce)
1332         term->erase_char.attr = (term->curr_attr &
1333                                  (ATTR_FGMASK | ATTR_BGMASK));
1334 }
1335
1336 /*
1337  * We copy a bunch of stuff out of the Conf structure into local
1338  * fields in the Terminal structure, to avoid the repeated tree234
1339  * lookups which would be involved in fetching them from the former
1340  * every time.
1341  */
1342 void term_copy_stuff_from_conf(Terminal *term)
1343 {
1344     term->ansi_colour = conf_get_int(term->conf, CONF_ansi_colour);
1345     term->arabicshaping = conf_get_int(term->conf, CONF_arabicshaping);
1346     term->beep = conf_get_int(term->conf, CONF_beep);
1347     term->bellovl = conf_get_int(term->conf, CONF_bellovl);
1348     term->bellovl_n = conf_get_int(term->conf, CONF_bellovl_n);
1349     term->bellovl_s = conf_get_int(term->conf, CONF_bellovl_s);
1350     term->bellovl_t = conf_get_int(term->conf, CONF_bellovl_t);
1351     term->bidi = conf_get_int(term->conf, CONF_bidi);
1352     term->bksp_is_delete = conf_get_int(term->conf, CONF_bksp_is_delete);
1353     term->blink_cur = conf_get_int(term->conf, CONF_blink_cur);
1354     term->blinktext = conf_get_int(term->conf, CONF_blinktext);
1355     term->cjk_ambig_wide = conf_get_int(term->conf, CONF_cjk_ambig_wide);
1356     term->conf_height = conf_get_int(term->conf, CONF_height);
1357     term->conf_width = conf_get_int(term->conf, CONF_width);
1358     term->crhaslf = conf_get_int(term->conf, CONF_crhaslf);
1359     term->erase_to_scrollback = conf_get_int(term->conf, CONF_erase_to_scrollback);
1360     term->funky_type = conf_get_int(term->conf, CONF_funky_type);
1361     term->lfhascr = conf_get_int(term->conf, CONF_lfhascr);
1362     term->logflush = conf_get_int(term->conf, CONF_logflush);
1363     term->logtype = conf_get_int(term->conf, CONF_logtype);
1364     term->mouse_override = conf_get_int(term->conf, CONF_mouse_override);
1365     term->nethack_keypad = conf_get_int(term->conf, CONF_nethack_keypad);
1366     term->no_alt_screen = conf_get_int(term->conf, CONF_no_alt_screen);
1367     term->no_applic_c = conf_get_int(term->conf, CONF_no_applic_c);
1368     term->no_applic_k = conf_get_int(term->conf, CONF_no_applic_k);
1369     term->no_dbackspace = conf_get_int(term->conf, CONF_no_dbackspace);
1370     term->no_mouse_rep = conf_get_int(term->conf, CONF_no_mouse_rep);
1371     term->no_remote_charset = conf_get_int(term->conf, CONF_no_remote_charset);
1372     term->no_remote_resize = conf_get_int(term->conf, CONF_no_remote_resize);
1373     term->no_remote_wintitle = conf_get_int(term->conf, CONF_no_remote_wintitle);
1374     term->rawcnp = conf_get_int(term->conf, CONF_rawcnp);
1375     term->rect_select = conf_get_int(term->conf, CONF_rect_select);
1376     term->remote_qtitle_action = conf_get_int(term->conf, CONF_remote_qtitle_action);
1377     term->rxvt_homeend = conf_get_int(term->conf, CONF_rxvt_homeend);
1378     term->scroll_on_disp = conf_get_int(term->conf, CONF_scroll_on_disp);
1379     term->scroll_on_key = conf_get_int(term->conf, CONF_scroll_on_key);
1380     term->xterm_256_colour = conf_get_int(term->conf, CONF_xterm_256_colour);
1381
1382     /*
1383      * Parse the control-character escapes in the configured
1384      * answerback string.
1385      */
1386     {
1387         char *answerback = conf_get_str(term->conf, CONF_answerback);
1388         int maxlen = strlen(answerback);
1389
1390         term->answerback = snewn(maxlen, char);
1391         term->answerbacklen = 0;
1392
1393         while (*answerback) {
1394             char *n;
1395             char c = ctrlparse(answerback, &n);
1396             if (n) {
1397                 term->answerback[term->answerbacklen++] = c;
1398                 answerback = n;
1399             } else {
1400                 term->answerback[term->answerbacklen++] = *answerback++;
1401             }
1402         }
1403     }
1404 }
1405
1406 /*
1407  * When the user reconfigures us, we need to check the forbidden-
1408  * alternate-screen config option, disable raw mouse mode if the
1409  * user has disabled mouse reporting, and abandon a print job if
1410  * the user has disabled printing.
1411  */
1412 void term_reconfig(Terminal *term, Conf *conf)
1413 {
1414     /*
1415      * Before adopting the new config, check all those terminal
1416      * settings which control power-on defaults; and if they've
1417      * changed, we will modify the current state as well as the
1418      * default one. The full list is: Auto wrap mode, DEC Origin
1419      * Mode, BCE, blinking text, character classes.
1420      */
1421     int reset_wrap, reset_decom, reset_bce, reset_tblink, reset_charclass;
1422     int i;
1423
1424     reset_wrap = (conf_get_int(term->conf, CONF_wrap_mode) !=
1425                   conf_get_int(conf, CONF_wrap_mode));
1426     reset_decom = (conf_get_int(term->conf, CONF_dec_om) !=
1427                    conf_get_int(conf, CONF_dec_om));
1428     reset_bce = (conf_get_int(term->conf, CONF_bce) !=
1429                  conf_get_int(conf, CONF_bce));
1430     reset_tblink = (conf_get_int(term->conf, CONF_blinktext) !=
1431                     conf_get_int(conf, CONF_blinktext));
1432     reset_charclass = 0;
1433     for (i = 0; i < 256; i++)
1434         if (conf_get_int_int(term->conf, CONF_wordness, i) !=
1435             conf_get_int_int(conf, CONF_wordness, i))
1436             reset_charclass = 1;
1437
1438     /*
1439      * If the bidi or shaping settings have changed, flush the bidi
1440      * cache completely.
1441      */
1442     if (conf_get_int(term->conf, CONF_arabicshaping) !=
1443         conf_get_int(conf, CONF_arabicshaping) ||
1444         conf_get_int(term->conf, CONF_bidi) !=
1445         conf_get_int(conf, CONF_bidi)) {
1446         for (i = 0; i < term->bidi_cache_size; i++) {
1447             sfree(term->pre_bidi_cache[i].chars);
1448             sfree(term->post_bidi_cache[i].chars);
1449             term->pre_bidi_cache[i].width = -1;
1450             term->pre_bidi_cache[i].chars = NULL;
1451             term->post_bidi_cache[i].width = -1;
1452             term->post_bidi_cache[i].chars = NULL;
1453         }
1454     }
1455
1456     conf_free(term->conf);
1457     term->conf = conf_copy(conf);
1458
1459     if (reset_wrap)
1460         term->alt_wrap = term->wrap = conf_get_int(term->conf, CONF_wrap_mode);
1461     if (reset_decom)
1462         term->alt_om = term->dec_om = conf_get_int(term->conf, CONF_dec_om);
1463     if (reset_bce) {
1464         term->use_bce = conf_get_int(term->conf, CONF_bce);
1465         set_erase_char(term);
1466     }
1467     if (reset_tblink) {
1468         term->blink_is_real = conf_get_int(term->conf, CONF_blinktext);
1469     }
1470     if (reset_charclass)
1471         for (i = 0; i < 256; i++)
1472             term->wordness[i] = conf_get_int_int(term->conf, CONF_wordness, i);
1473
1474     if (conf_get_int(term->conf, CONF_no_alt_screen))
1475         swap_screen(term, 0, FALSE, FALSE);
1476     if (conf_get_int(term->conf, CONF_no_mouse_rep)) {
1477         term->xterm_mouse = 0;
1478         set_raw_mouse_mode(term->frontend, 0);
1479     }
1480     if (conf_get_int(term->conf, CONF_no_remote_charset)) {
1481         term->cset_attr[0] = term->cset_attr[1] = CSET_ASCII;
1482         term->sco_acs = term->alt_sco_acs = 0;
1483         term->utf = 0;
1484     }
1485     if (!conf_get_str(term->conf, CONF_printer)) {
1486         term_print_finish(term);
1487     }
1488     term_schedule_tblink(term);
1489     term_schedule_cblink(term);
1490     term_copy_stuff_from_conf(term);
1491 }
1492
1493 /*
1494  * Clear the scrollback.
1495  */
1496 void term_clrsb(Terminal *term)
1497 {
1498     unsigned char *line;
1499     term->disptop = 0;
1500     while ((line = delpos234(term->scrollback, 0)) != NULL) {
1501         sfree(line);            /* this is compressed data, not a termline */
1502     }
1503     term->tempsblines = 0;
1504     term->alt_sblines = 0;
1505     update_sbar(term);
1506 }
1507
1508 /*
1509  * Initialise the terminal.
1510  */
1511 Terminal *term_init(Conf *myconf, struct unicode_data *ucsdata,
1512                     void *frontend)
1513 {
1514     Terminal *term;
1515
1516     /*
1517      * Allocate a new Terminal structure and initialise the fields
1518      * that need it.
1519      */
1520     term = snew(Terminal);
1521     term->frontend = frontend;
1522     term->ucsdata = ucsdata;
1523     term->conf = conf_copy(myconf);
1524     term->logctx = NULL;
1525     term->compatibility_level = TM_PUTTY;
1526     strcpy(term->id_string, "\033[?6c");
1527     term->cblink_pending = term->tblink_pending = FALSE;
1528     term->paste_buffer = NULL;
1529     term->paste_len = 0;
1530     bufchain_init(&term->inbuf);
1531     bufchain_init(&term->printer_buf);
1532     term->printing = term->only_printing = FALSE;
1533     term->print_job = NULL;
1534     term->vt52_mode = FALSE;
1535     term->cr_lf_return = FALSE;
1536     term->seen_disp_event = FALSE;
1537     term->mouse_is_down = FALSE;
1538     term->reset_132 = FALSE;
1539     term->cblinker = term->tblinker = 0;
1540     term->has_focus = 1;
1541     term->repeat_off = FALSE;
1542     term->termstate = TOPLEVEL;
1543     term->selstate = NO_SELECTION;
1544     term->curstype = 0;
1545
1546     term_copy_stuff_from_conf(term);
1547
1548     term->screen = term->alt_screen = term->scrollback = NULL;
1549     term->tempsblines = 0;
1550     term->alt_sblines = 0;
1551     term->disptop = 0;
1552     term->disptext = NULL;
1553     term->dispcursx = term->dispcursy = -1;
1554     term->tabs = NULL;
1555     deselect(term);
1556     term->rows = term->cols = -1;
1557     power_on(term, TRUE);
1558     term->beephead = term->beeptail = NULL;
1559 #ifdef OPTIMISE_SCROLL
1560     term->scrollhead = term->scrolltail = NULL;
1561 #endif /* OPTIMISE_SCROLL */
1562     term->nbeeps = 0;
1563     term->lastbeep = FALSE;
1564     term->beep_overloaded = FALSE;
1565     term->attr_mask = 0xffffffff;
1566     term->resize_fn = NULL;
1567     term->resize_ctx = NULL;
1568     term->in_term_out = FALSE;
1569     term->ltemp = NULL;
1570     term->ltemp_size = 0;
1571     term->wcFrom = NULL;
1572     term->wcTo = NULL;
1573     term->wcFromTo_size = 0;
1574
1575     term->window_update_pending = FALSE;
1576
1577     term->bidi_cache_size = 0;
1578     term->pre_bidi_cache = term->post_bidi_cache = NULL;
1579
1580     /* FULL-TERMCHAR */
1581     term->basic_erase_char.chr = CSET_ASCII | ' ';
1582     term->basic_erase_char.attr = ATTR_DEFAULT;
1583     term->basic_erase_char.cc_next = 0;
1584     term->erase_char = term->basic_erase_char;
1585
1586     return term;
1587 }
1588
1589 void term_free(Terminal *term)
1590 {
1591     termline *line;
1592     struct beeptime *beep;
1593     int i;
1594
1595     while ((line = delpos234(term->scrollback, 0)) != NULL)
1596         sfree(line);                   /* compressed data, not a termline */
1597     freetree234(term->scrollback);
1598     while ((line = delpos234(term->screen, 0)) != NULL)
1599         freeline(line);
1600     freetree234(term->screen);
1601     while ((line = delpos234(term->alt_screen, 0)) != NULL)
1602         freeline(line);
1603     freetree234(term->alt_screen);
1604     if (term->disptext) {
1605         for (i = 0; i < term->rows; i++)
1606             freeline(term->disptext[i]);
1607     }
1608     sfree(term->disptext);
1609     while (term->beephead) {
1610         beep = term->beephead;
1611         term->beephead = beep->next;
1612         sfree(beep);
1613     }
1614     bufchain_clear(&term->inbuf);
1615     if(term->print_job)
1616         printer_finish_job(term->print_job);
1617     bufchain_clear(&term->printer_buf);
1618     sfree(term->paste_buffer);
1619     sfree(term->ltemp);
1620     sfree(term->wcFrom);
1621     sfree(term->wcTo);
1622
1623     for (i = 0; i < term->bidi_cache_size; i++) {
1624         sfree(term->pre_bidi_cache[i].chars);
1625         sfree(term->post_bidi_cache[i].chars);
1626         sfree(term->post_bidi_cache[i].forward);
1627         sfree(term->post_bidi_cache[i].backward);
1628     }
1629     sfree(term->pre_bidi_cache);
1630     sfree(term->post_bidi_cache);
1631
1632     sfree(term->tabs);
1633
1634     expire_timer_context(term);
1635
1636     conf_free(term->conf);
1637
1638     sfree(term);
1639 }
1640
1641 /*
1642  * Set up the terminal for a given size.
1643  */
1644 void term_size(Terminal *term, int newrows, int newcols, int newsavelines)
1645 {
1646     tree234 *newalt;
1647     termline **newdisp, *line;
1648     int i, j, oldrows = term->rows;
1649     int sblen;
1650     int save_alt_which = term->alt_which;
1651
1652     if (newrows == term->rows && newcols == term->cols &&
1653         newsavelines == term->savelines)
1654         return;                        /* nothing to do */
1655
1656     /* Behave sensibly if we're given zero (or negative) rows/cols */
1657
1658     if (newrows < 1) newrows = 1;
1659     if (newcols < 1) newcols = 1;
1660
1661     deselect(term);
1662     swap_screen(term, 0, FALSE, FALSE);
1663
1664     term->alt_t = term->marg_t = 0;
1665     term->alt_b = term->marg_b = newrows - 1;
1666
1667     if (term->rows == -1) {
1668         term->scrollback = newtree234(NULL);
1669         term->screen = newtree234(NULL);
1670         term->tempsblines = 0;
1671         term->rows = 0;
1672     }
1673
1674     /*
1675      * Resize the screen and scrollback. We only need to shift
1676      * lines around within our data structures, because lineptr()
1677      * will take care of resizing each individual line if
1678      * necessary. So:
1679      * 
1680      *  - If the new screen is longer, we shunt lines in from temporary
1681      *    scrollback if possible, otherwise we add new blank lines at
1682      *    the bottom.
1683      *
1684      *  - If the new screen is shorter, we remove any blank lines at
1685      *    the bottom if possible, otherwise shunt lines above the cursor
1686      *    to scrollback if possible, otherwise delete lines below the
1687      *    cursor.
1688      * 
1689      *  - Then, if the new scrollback length is less than the
1690      *    amount of scrollback we actually have, we must throw some
1691      *    away.
1692      */
1693     sblen = count234(term->scrollback);
1694     /* Do this loop to expand the screen if newrows > rows */
1695     assert(term->rows == count234(term->screen));
1696     while (term->rows < newrows) {
1697         if (term->tempsblines > 0) {
1698             unsigned char *cline;
1699             /* Insert a line from the scrollback at the top of the screen. */
1700             assert(sblen >= term->tempsblines);
1701             cline = delpos234(term->scrollback, --sblen);
1702             line = decompressline(cline, NULL);
1703             sfree(cline);
1704             line->temporary = FALSE;   /* reconstituted line is now real */
1705             term->tempsblines -= 1;
1706             addpos234(term->screen, line, 0);
1707             term->curs.y += 1;
1708             term->savecurs.y += 1;
1709             term->alt_y += 1;
1710             term->alt_savecurs.y += 1;
1711         } else {
1712             /* Add a new blank line at the bottom of the screen. */
1713             line = newline(term, newcols, FALSE);
1714             addpos234(term->screen, line, count234(term->screen));
1715         }
1716         term->rows += 1;
1717     }
1718     /* Do this loop to shrink the screen if newrows < rows */
1719     while (term->rows > newrows) {
1720         if (term->curs.y < term->rows - 1) {
1721             /* delete bottom row, unless it contains the cursor */
1722             line = delpos234(term->screen, term->rows - 1);
1723             freeline(line);
1724         } else {
1725             /* push top row to scrollback */
1726             line = delpos234(term->screen, 0);
1727             addpos234(term->scrollback, compressline(line), sblen++);
1728             freeline(line);
1729             term->tempsblines += 1;
1730             term->curs.y -= 1;
1731             term->savecurs.y -= 1;
1732             term->alt_y -= 1;
1733             term->alt_savecurs.y -= 1;
1734         }
1735         term->rows -= 1;
1736     }
1737     assert(term->rows == newrows);
1738     assert(count234(term->screen) == newrows);
1739
1740     /* Delete any excess lines from the scrollback. */
1741     while (sblen > newsavelines) {
1742         line = delpos234(term->scrollback, 0);
1743         sfree(line);
1744         sblen--;
1745     }
1746     if (sblen < term->tempsblines)
1747         term->tempsblines = sblen;
1748     assert(count234(term->scrollback) <= newsavelines);
1749     assert(count234(term->scrollback) >= term->tempsblines);
1750     term->disptop = 0;
1751
1752     /* Make a new displayed text buffer. */
1753     newdisp = snewn(newrows, termline *);
1754     for (i = 0; i < newrows; i++) {
1755         newdisp[i] = newline(term, newcols, FALSE);
1756         for (j = 0; j < newcols; j++)
1757             newdisp[i]->chars[j].attr = ATTR_INVALID;
1758     }
1759     if (term->disptext) {
1760         for (i = 0; i < oldrows; i++)
1761             freeline(term->disptext[i]);
1762     }
1763     sfree(term->disptext);
1764     term->disptext = newdisp;
1765     term->dispcursx = term->dispcursy = -1;
1766
1767     /* Make a new alternate screen. */
1768     newalt = newtree234(NULL);
1769     for (i = 0; i < newrows; i++) {
1770         line = newline(term, newcols, TRUE);
1771         addpos234(newalt, line, i);
1772     }
1773     if (term->alt_screen) {
1774         while (NULL != (line = delpos234(term->alt_screen, 0)))
1775             freeline(line);
1776         freetree234(term->alt_screen);
1777     }
1778     term->alt_screen = newalt;
1779     term->alt_sblines = 0;
1780
1781     term->tabs = sresize(term->tabs, newcols, unsigned char);
1782     {
1783         int i;
1784         for (i = (term->cols > 0 ? term->cols : 0); i < newcols; i++)
1785             term->tabs[i] = (i % 8 == 0 ? TRUE : FALSE);
1786     }
1787
1788     /* Check that the cursor positions are still valid. */
1789     if (term->savecurs.y < 0)
1790         term->savecurs.y = 0;
1791     if (term->savecurs.y >= newrows)
1792         term->savecurs.y = newrows - 1;
1793     if (term->savecurs.x >= newcols)
1794         term->savecurs.x = newcols - 1;
1795     if (term->alt_savecurs.y < 0)
1796         term->alt_savecurs.y = 0;
1797     if (term->alt_savecurs.y >= newrows)
1798         term->alt_savecurs.y = newrows - 1;
1799     if (term->alt_savecurs.x >= newcols)
1800         term->alt_savecurs.x = newcols - 1;
1801     if (term->curs.y < 0)
1802         term->curs.y = 0;
1803     if (term->curs.y >= newrows)
1804         term->curs.y = newrows - 1;
1805     if (term->curs.x >= newcols)
1806         term->curs.x = newcols - 1;
1807     if (term->alt_y < 0)
1808         term->alt_y = 0;
1809     if (term->alt_y >= newrows)
1810         term->alt_y = newrows - 1;
1811     if (term->alt_x >= newcols)
1812         term->alt_x = newcols - 1;
1813     term->alt_x = term->alt_y = 0;
1814     term->wrapnext = term->alt_wnext = FALSE;
1815
1816     term->rows = newrows;
1817     term->cols = newcols;
1818     term->savelines = newsavelines;
1819
1820     swap_screen(term, save_alt_which, FALSE, FALSE);
1821
1822     update_sbar(term);
1823     term_update(term);
1824     if (term->resize_fn)
1825         term->resize_fn(term->resize_ctx, term->cols, term->rows);
1826 }
1827
1828 /*
1829  * Hand a function and context pointer to the terminal which it can
1830  * use to notify a back end of resizes.
1831  */
1832 void term_provide_resize_fn(Terminal *term,
1833                             void (*resize_fn)(void *, int, int),
1834                             void *resize_ctx)
1835 {
1836     term->resize_fn = resize_fn;
1837     term->resize_ctx = resize_ctx;
1838     if (resize_fn && term->cols > 0 && term->rows > 0)
1839         resize_fn(resize_ctx, term->cols, term->rows);
1840 }
1841
1842 /* Find the bottom line on the screen that has any content.
1843  * If only the top line has content, returns 0.
1844  * If no lines have content, return -1.
1845  */ 
1846 static int find_last_nonempty_line(Terminal * term, tree234 * screen)
1847 {
1848     int i;
1849     for (i = count234(screen) - 1; i >= 0; i--) {
1850         termline *line = index234(screen, i);
1851         int j;
1852         for (j = 0; j < line->cols; j++)
1853             if (!termchars_equal(&line->chars[j], &term->erase_char))
1854                 break;
1855         if (j != line->cols) break;
1856     }
1857     return i;
1858 }
1859
1860 /*
1861  * Swap screens. If `reset' is TRUE and we have been asked to
1862  * switch to the alternate screen, we must bring most of its
1863  * configuration from the main screen and erase the contents of the
1864  * alternate screen completely. (This is even true if we're already
1865  * on it! Blame xterm.)
1866  */
1867 static void swap_screen(Terminal *term, int which, int reset, int keep_cur_pos)
1868 {
1869     int t;
1870     pos tp;
1871     tree234 *ttr;
1872
1873     if (!which)
1874         reset = FALSE;                 /* do no weird resetting if which==0 */
1875
1876     if (which != term->alt_which) {
1877         term->alt_which = which;
1878
1879         ttr = term->alt_screen;
1880         term->alt_screen = term->screen;
1881         term->screen = ttr;
1882         term->alt_sblines = find_last_nonempty_line(term, term->alt_screen) + 1;
1883         t = term->curs.x;
1884         if (!reset && !keep_cur_pos)
1885             term->curs.x = term->alt_x;
1886         term->alt_x = t;
1887         t = term->curs.y;
1888         if (!reset && !keep_cur_pos)
1889             term->curs.y = term->alt_y;
1890         term->alt_y = t;
1891         t = term->marg_t;
1892         if (!reset) term->marg_t = term->alt_t;
1893         term->alt_t = t;
1894         t = term->marg_b;
1895         if (!reset) term->marg_b = term->alt_b;
1896         term->alt_b = t;
1897         t = term->dec_om;
1898         if (!reset) term->dec_om = term->alt_om;
1899         term->alt_om = t;
1900         t = term->wrap;
1901         if (!reset) term->wrap = term->alt_wrap;
1902         term->alt_wrap = t;
1903         t = term->wrapnext;
1904         if (!reset) term->wrapnext = term->alt_wnext;
1905         term->alt_wnext = t;
1906         t = term->insert;
1907         if (!reset) term->insert = term->alt_ins;
1908         term->alt_ins = t;
1909         t = term->cset;
1910         if (!reset) term->cset = term->alt_cset;
1911         term->alt_cset = t;
1912         t = term->utf;
1913         if (!reset) term->utf = term->alt_utf;
1914         term->alt_utf = t;
1915         t = term->sco_acs;
1916         if (!reset) term->sco_acs = term->alt_sco_acs;
1917         term->alt_sco_acs = t;
1918
1919         tp = term->savecurs;
1920         if (!reset && !keep_cur_pos)
1921             term->savecurs = term->alt_savecurs;
1922         term->alt_savecurs = tp;
1923         t = term->save_cset;
1924         if (!reset && !keep_cur_pos)
1925             term->save_cset = term->alt_save_cset;
1926         term->alt_save_cset = t;
1927         t = term->save_csattr;
1928         if (!reset && !keep_cur_pos)
1929             term->save_csattr = term->alt_save_csattr;
1930         term->alt_save_csattr = t;
1931         t = term->save_attr;
1932         if (!reset && !keep_cur_pos)
1933             term->save_attr = term->alt_save_attr;
1934         term->alt_save_attr = t;
1935         t = term->save_utf;
1936         if (!reset && !keep_cur_pos)
1937             term->save_utf = term->alt_save_utf;
1938         term->alt_save_utf = t;
1939         t = term->save_wnext;
1940         if (!reset && !keep_cur_pos)
1941             term->save_wnext = term->alt_save_wnext;
1942         term->alt_save_wnext = t;
1943         t = term->save_sco_acs;
1944         if (!reset && !keep_cur_pos)
1945             term->save_sco_acs = term->alt_save_sco_acs;
1946         term->alt_save_sco_acs = t;
1947     }
1948
1949     if (reset && term->screen) {
1950         /*
1951          * Yes, this _is_ supposed to honour background-colour-erase.
1952          */
1953         erase_lots(term, FALSE, TRUE, TRUE);
1954     }
1955 }
1956
1957 /*
1958  * Update the scroll bar.
1959  */
1960 static void update_sbar(Terminal *term)
1961 {
1962     int nscroll = sblines(term);
1963     set_sbar(term->frontend, nscroll + term->rows,
1964              nscroll + term->disptop, term->rows);
1965 }
1966
1967 /*
1968  * Check whether the region bounded by the two pointers intersects
1969  * the scroll region, and de-select the on-screen selection if so.
1970  */
1971 static void check_selection(Terminal *term, pos from, pos to)
1972 {
1973     if (poslt(from, term->selend) && poslt(term->selstart, to))
1974         deselect(term);
1975 }
1976
1977 /*
1978  * Scroll the screen. (`lines' is +ve for scrolling forward, -ve
1979  * for backward.) `sb' is TRUE if the scrolling is permitted to
1980  * affect the scrollback buffer.
1981  */
1982 static void scroll(Terminal *term, int topline, int botline, int lines, int sb)
1983 {
1984     termline *line;
1985     int i, seltop, scrollwinsize;
1986 #ifdef OPTIMISE_SCROLL
1987     int olddisptop, shift;
1988 #endif /* OPTIMISE_SCROLL */
1989
1990     if (topline != 0 || term->alt_which != 0)
1991         sb = FALSE;
1992
1993 #ifdef OPTIMISE_SCROLL
1994     olddisptop = term->disptop;
1995     shift = lines;
1996 #endif /* OPTIMISE_SCROLL */
1997
1998     scrollwinsize = botline - topline + 1;
1999
2000     if (lines < 0) {
2001         lines = -lines;
2002         if (lines > scrollwinsize)
2003             lines = scrollwinsize;
2004         while (lines-- > 0) {
2005             line = delpos234(term->screen, botline);
2006             resizeline(term, line, term->cols);
2007             for (i = 0; i < term->cols; i++)
2008                 copy_termchar(line, i, &term->erase_char);
2009             line->lattr = LATTR_NORM;
2010             addpos234(term->screen, line, topline);
2011
2012             if (term->selstart.y >= topline && term->selstart.y <= botline) {
2013                 term->selstart.y++;
2014                 if (term->selstart.y > botline) {
2015                     term->selstart.y = botline + 1;
2016                     term->selstart.x = 0;
2017                 }
2018             }
2019             if (term->selend.y >= topline && term->selend.y <= botline) {
2020                 term->selend.y++;
2021                 if (term->selend.y > botline) {
2022                     term->selend.y = botline + 1;
2023                     term->selend.x = 0;
2024                 }
2025             }
2026         }
2027     } else {
2028         if (lines > scrollwinsize)
2029             lines = scrollwinsize;
2030         while (lines-- > 0) {
2031             line = delpos234(term->screen, topline);
2032 #ifdef TERM_CC_DIAGS
2033             cc_check(line);
2034 #endif
2035             if (sb && term->savelines > 0) {
2036                 int sblen = count234(term->scrollback);
2037                 /*
2038                  * We must add this line to the scrollback. We'll
2039                  * remove a line from the top of the scrollback if
2040                  * the scrollback is full.
2041                  */
2042                 if (sblen == term->savelines) {
2043                     unsigned char *cline;
2044
2045                     sblen--;
2046                     cline = delpos234(term->scrollback, 0);
2047                     sfree(cline);
2048                 } else
2049                     term->tempsblines += 1;
2050
2051                 addpos234(term->scrollback, compressline(line), sblen);
2052
2053                 /* now `line' itself can be reused as the bottom line */
2054
2055                 /*
2056                  * If the user is currently looking at part of the
2057                  * scrollback, and they haven't enabled any options
2058                  * that are going to reset the scrollback as a
2059                  * result of this movement, then the chances are
2060                  * they'd like to keep looking at the same line. So
2061                  * we move their viewpoint at the same rate as the
2062                  * scroll, at least until their viewpoint hits the
2063                  * top end of the scrollback buffer, at which point
2064                  * we don't have the choice any more.
2065                  * 
2066                  * Thanks to Jan Holmen Holsten for the idea and
2067                  * initial implementation.
2068                  */
2069                 if (term->disptop > -term->savelines && term->disptop < 0)
2070                     term->disptop--;
2071             }
2072             resizeline(term, line, term->cols);
2073             for (i = 0; i < term->cols; i++)
2074                 copy_termchar(line, i, &term->erase_char);
2075             line->lattr = LATTR_NORM;
2076             addpos234(term->screen, line, botline);
2077
2078             /*
2079              * If the selection endpoints move into the scrollback,
2080              * we keep them moving until they hit the top. However,
2081              * of course, if the line _hasn't_ moved into the
2082              * scrollback then we don't do this, and cut them off
2083              * at the top of the scroll region.
2084              * 
2085              * This applies to selstart and selend (for an existing
2086              * selection), and also selanchor (for one being
2087              * selected as we speak).
2088              */
2089             seltop = sb ? -term->savelines : topline;
2090
2091             if (term->selstate != NO_SELECTION) {
2092                 if (term->selstart.y >= seltop &&
2093                     term->selstart.y <= botline) {
2094                     term->selstart.y--;
2095                     if (term->selstart.y < seltop) {
2096                         term->selstart.y = seltop;
2097                         term->selstart.x = 0;
2098                     }
2099                 }
2100                 if (term->selend.y >= seltop && term->selend.y <= botline) {
2101                     term->selend.y--;
2102                     if (term->selend.y < seltop) {
2103                         term->selend.y = seltop;
2104                         term->selend.x = 0;
2105                     }
2106                 }
2107                 if (term->selanchor.y >= seltop &&
2108                     term->selanchor.y <= botline) {
2109                     term->selanchor.y--;
2110                     if (term->selanchor.y < seltop) {
2111                         term->selanchor.y = seltop;
2112                         term->selanchor.x = 0;
2113                     }
2114                 }
2115             }
2116         }
2117     }
2118 #ifdef OPTIMISE_SCROLL
2119     shift += term->disptop - olddisptop;
2120     if (shift < term->rows && shift > -term->rows && shift != 0)
2121         scroll_display(term, topline, botline, shift);
2122 #endif /* OPTIMISE_SCROLL */
2123 }
2124
2125 #ifdef OPTIMISE_SCROLL
2126 /*
2127  * Add a scroll of a region on the screen into the pending scroll list.
2128  * `lines' is +ve for scrolling forward, -ve for backward.
2129  *
2130  * If the scroll is on the same area as the last scroll in the list,
2131  * merge them.
2132  */
2133 static void save_scroll(Terminal *term, int topline, int botline, int lines)
2134 {
2135     struct scrollregion *newscroll;
2136     if (term->scrolltail &&
2137         term->scrolltail->topline == topline && 
2138         term->scrolltail->botline == botline) {
2139         term->scrolltail->lines += lines;
2140     } else {
2141         newscroll = snew(struct scrollregion);
2142         newscroll->topline = topline;
2143         newscroll->botline = botline;
2144         newscroll->lines = lines;
2145         newscroll->next = NULL;
2146
2147         if (!term->scrollhead)
2148             term->scrollhead = newscroll;
2149         else
2150             term->scrolltail->next = newscroll;
2151         term->scrolltail = newscroll;
2152     }
2153 }
2154
2155 /*
2156  * Scroll the physical display, and our conception of it in disptext.
2157  */
2158 static void scroll_display(Terminal *term, int topline, int botline, int lines)
2159 {
2160     int distance, nlines, i, j;
2161
2162     distance = lines > 0 ? lines : -lines;
2163     nlines = botline - topline + 1 - distance;
2164     if (lines > 0) {
2165         for (i = 0; i < nlines; i++)
2166             for (j = 0; j < term->cols; j++)
2167                 copy_termchar(term->disptext[i], j,
2168                               term->disptext[i+distance]->chars+j);
2169         if (term->dispcursy >= 0 &&
2170             term->dispcursy >= topline + distance &&
2171             term->dispcursy < topline + distance + nlines)
2172             term->dispcursy -= distance;
2173         for (i = 0; i < distance; i++)
2174             for (j = 0; j < term->cols; j++)
2175                 term->disptext[nlines+i]->chars[j].attr |= ATTR_INVALID;
2176     } else {
2177         for (i = nlines; i-- ;)
2178             for (j = 0; j < term->cols; j++)
2179                 copy_termchar(term->disptext[i+distance], j,
2180                               term->disptext[i]->chars+j);
2181         if (term->dispcursy >= 0 &&
2182             term->dispcursy >= topline &&
2183             term->dispcursy < topline + nlines)
2184             term->dispcursy += distance;
2185         for (i = 0; i < distance; i++)
2186             for (j = 0; j < term->cols; j++)
2187                 term->disptext[i]->chars[j].attr |= ATTR_INVALID;
2188     }
2189     save_scroll(term, topline, botline, lines);
2190 }
2191 #endif /* OPTIMISE_SCROLL */
2192
2193 /*
2194  * Move the cursor to a given position, clipping at boundaries. We
2195  * may or may not want to clip at the scroll margin: marg_clip is 0
2196  * not to, 1 to disallow _passing_ the margins, and 2 to disallow
2197  * even _being_ outside the margins.
2198  */
2199 static void move(Terminal *term, int x, int y, int marg_clip)
2200 {
2201     if (x < 0)
2202         x = 0;
2203     if (x >= term->cols)
2204         x = term->cols - 1;
2205     if (marg_clip) {
2206         if ((term->curs.y >= term->marg_t || marg_clip == 2) &&
2207             y < term->marg_t)
2208             y = term->marg_t;
2209         if ((term->curs.y <= term->marg_b || marg_clip == 2) &&
2210             y > term->marg_b)
2211             y = term->marg_b;
2212     }
2213     if (y < 0)
2214         y = 0;
2215     if (y >= term->rows)
2216         y = term->rows - 1;
2217     term->curs.x = x;
2218     term->curs.y = y;
2219     term->wrapnext = FALSE;
2220 }
2221
2222 /*
2223  * Save or restore the cursor and SGR mode.
2224  */
2225 static void save_cursor(Terminal *term, int save)
2226 {
2227     if (save) {
2228         term->savecurs = term->curs;
2229         term->save_attr = term->curr_attr;
2230         term->save_cset = term->cset;
2231         term->save_utf = term->utf;
2232         term->save_wnext = term->wrapnext;
2233         term->save_csattr = term->cset_attr[term->cset];
2234         term->save_sco_acs = term->sco_acs;
2235     } else {
2236         term->curs = term->savecurs;
2237         /* Make sure the window hasn't shrunk since the save */
2238         if (term->curs.x >= term->cols)
2239             term->curs.x = term->cols - 1;
2240         if (term->curs.y >= term->rows)
2241             term->curs.y = term->rows - 1;
2242
2243         term->curr_attr = term->save_attr;
2244         term->cset = term->save_cset;
2245         term->utf = term->save_utf;
2246         term->wrapnext = term->save_wnext;
2247         /*
2248          * wrapnext might reset to False if the x position is no
2249          * longer at the rightmost edge.
2250          */
2251         if (term->wrapnext && term->curs.x < term->cols-1)
2252             term->wrapnext = FALSE;
2253         term->cset_attr[term->cset] = term->save_csattr;
2254         term->sco_acs = term->save_sco_acs;
2255         set_erase_char(term);
2256     }
2257 }
2258
2259 /*
2260  * This function is called before doing _anything_ which affects
2261  * only part of a line of text. It is used to mark the boundary
2262  * between two character positions, and it indicates that some sort
2263  * of effect is going to happen on only one side of that boundary.
2264  * 
2265  * The effect of this function is to check whether a CJK
2266  * double-width character is straddling the boundary, and to remove
2267  * it and replace it with two spaces if so. (Of course, one or
2268  * other of those spaces is then likely to be replaced with
2269  * something else again, as a result of whatever happens next.)
2270  * 
2271  * Also, if the boundary is at the right-hand _edge_ of the screen,
2272  * it implies something deliberate is being done to the rightmost
2273  * column position; hence we must clear LATTR_WRAPPED2.
2274  * 
2275  * The input to the function is the coordinates of the _second_
2276  * character of the pair.
2277  */
2278 static void check_boundary(Terminal *term, int x, int y)
2279 {
2280     termline *ldata;
2281
2282     /* Validate input coordinates, just in case. */
2283     if (x == 0 || x > term->cols)
2284         return;
2285
2286     ldata = scrlineptr(y);
2287     if (x == term->cols) {
2288         ldata->lattr &= ~LATTR_WRAPPED2;
2289     } else {
2290         if (ldata->chars[x].chr == UCSWIDE) {
2291             clear_cc(ldata, x-1);
2292             clear_cc(ldata, x);
2293             ldata->chars[x-1].chr = ' ' | CSET_ASCII;
2294             ldata->chars[x] = ldata->chars[x-1];
2295         }
2296     }
2297 }
2298
2299 /*
2300  * Erase a large portion of the screen: the whole screen, or the
2301  * whole line, or parts thereof.
2302  */
2303 static void erase_lots(Terminal *term,
2304                        int line_only, int from_begin, int to_end)
2305 {
2306     pos start, end;
2307     int erase_lattr;
2308     int erasing_lines_from_top = 0;
2309
2310     if (line_only) {
2311         start.y = term->curs.y;
2312         start.x = 0;
2313         end.y = term->curs.y + 1;
2314         end.x = 0;
2315         erase_lattr = FALSE;
2316     } else {
2317         start.y = 0;
2318         start.x = 0;
2319         end.y = term->rows;
2320         end.x = 0;
2321         erase_lattr = TRUE;
2322     }
2323     if (!from_begin) {
2324         start = term->curs;
2325     }
2326     if (!to_end) {
2327         end = term->curs;
2328         incpos(end);
2329     }
2330     if (!from_begin || !to_end)
2331         check_boundary(term, term->curs.x, term->curs.y);
2332     check_selection(term, start, end);
2333
2334     /* Clear screen also forces a full window redraw, just in case. */
2335     if (start.y == 0 && start.x == 0 && end.y == term->rows)
2336         term_invalidate(term);
2337
2338     /* Lines scrolled away shouldn't be brought back on if the terminal
2339      * resizes. */
2340     if (start.y == 0 && start.x == 0 && end.x == 0 && erase_lattr)
2341         erasing_lines_from_top = 1;
2342
2343     if (term->erase_to_scrollback && erasing_lines_from_top) {
2344         /* If it's a whole number of lines, starting at the top, and
2345          * we're fully erasing them, erase by scrolling and keep the
2346          * lines in the scrollback. */
2347         int scrolllines = end.y;
2348         if (end.y == term->rows) {
2349             /* Shrink until we find a non-empty row.*/
2350             scrolllines = find_last_nonempty_line(term, term->screen) + 1;
2351         }
2352         if (scrolllines > 0)
2353             scroll(term, 0, scrolllines - 1, scrolllines, TRUE);
2354     } else {
2355         termline *ldata = scrlineptr(start.y);
2356         while (poslt(start, end)) {
2357             if (start.x == term->cols) {
2358                 if (!erase_lattr)
2359                     ldata->lattr &= ~(LATTR_WRAPPED | LATTR_WRAPPED2);
2360                 else
2361                     ldata->lattr = LATTR_NORM;
2362             } else {
2363                 copy_termchar(ldata, start.x, &term->erase_char);
2364             }
2365             if (incpos(start) && start.y < term->rows) {
2366                 ldata = scrlineptr(start.y);
2367             }
2368         }
2369     }
2370
2371     /* After an erase of lines from the top of the screen, we shouldn't
2372      * bring the lines back again if the terminal enlarges (since the user or
2373      * application has explictly thrown them away). */
2374     if (erasing_lines_from_top && !(term->alt_which))
2375         term->tempsblines = 0;
2376 }
2377
2378 /*
2379  * Insert or delete characters within the current line. n is +ve if
2380  * insertion is desired, and -ve for deletion.
2381  */
2382 static void insch(Terminal *term, int n)
2383 {
2384     int dir = (n < 0 ? -1 : +1);
2385     int m, j;
2386     pos cursplus;
2387     termline *ldata;
2388
2389     n = (n < 0 ? -n : n);
2390     if (n > term->cols - term->curs.x)
2391         n = term->cols - term->curs.x;
2392     m = term->cols - term->curs.x - n;
2393     cursplus.y = term->curs.y;
2394     cursplus.x = term->curs.x + n;
2395     check_selection(term, term->curs, cursplus);
2396     check_boundary(term, term->curs.x, term->curs.y);
2397     if (dir < 0)
2398         check_boundary(term, term->curs.x + n, term->curs.y);
2399     ldata = scrlineptr(term->curs.y);
2400     if (dir < 0) {
2401         for (j = 0; j < m; j++)
2402             move_termchar(ldata,
2403                           ldata->chars + term->curs.x + j,
2404                           ldata->chars + term->curs.x + j + n);
2405         while (n--)
2406             copy_termchar(ldata, term->curs.x + m++, &term->erase_char);
2407     } else {
2408         for (j = m; j-- ;)
2409             move_termchar(ldata,
2410                           ldata->chars + term->curs.x + j + n,
2411                           ldata->chars + term->curs.x + j);
2412         while (n--)
2413             copy_termchar(ldata, term->curs.x + n, &term->erase_char);
2414     }
2415 }
2416
2417 /*
2418  * Toggle terminal mode `mode' to state `state'. (`query' indicates
2419  * whether the mode is a DEC private one or a normal one.)
2420  */
2421 static void toggle_mode(Terminal *term, int mode, int query, int state)
2422 {
2423     if (query)
2424         switch (mode) {
2425           case 1:                      /* DECCKM: application cursor keys */
2426             term->app_cursor_keys = state;
2427             break;
2428           case 2:                      /* DECANM: VT52 mode */
2429             term->vt52_mode = !state;
2430             if (term->vt52_mode) {
2431                 term->blink_is_real = FALSE;
2432                 term->vt52_bold = FALSE;
2433             } else {
2434                 term->blink_is_real = term->blinktext;
2435             }
2436             term_schedule_tblink(term);
2437             break;
2438           case 3:                      /* DECCOLM: 80/132 columns */
2439             deselect(term);
2440             if (!term->no_remote_resize)
2441                 request_resize(term->frontend, state ? 132 : 80, term->rows);
2442             term->reset_132 = state;
2443             term->alt_t = term->marg_t = 0;
2444             term->alt_b = term->marg_b = term->rows - 1;
2445             move(term, 0, 0, 0);
2446             erase_lots(term, FALSE, TRUE, TRUE);
2447             break;
2448           case 5:                      /* DECSCNM: reverse video */
2449             /*
2450              * Toggle reverse video. If we receive an OFF within the
2451              * visual bell timeout period after an ON, we trigger an
2452              * effective visual bell, so that ESC[?5hESC[?5l will
2453              * always be an actually _visible_ visual bell.
2454              */
2455             if (term->rvideo && !state) {
2456                 /* This is an OFF, so set up a vbell */
2457                 term_schedule_vbell(term, TRUE, term->rvbell_startpoint);
2458             } else if (!term->rvideo && state) {
2459                 /* This is an ON, so we notice the time and save it. */
2460                 term->rvbell_startpoint = GETTICKCOUNT();
2461             }
2462             term->rvideo = state;
2463             seen_disp_event(term);
2464             break;
2465           case 6:                      /* DECOM: DEC origin mode */
2466             term->dec_om = state;
2467             break;
2468           case 7:                      /* DECAWM: auto wrap */
2469             term->wrap = state;
2470             break;
2471           case 8:                      /* DECARM: auto key repeat */
2472             term->repeat_off = !state;
2473             break;
2474           case 10:                     /* DECEDM: set local edit mode */
2475             term->term_editing = state;
2476             if (term->ldisc)           /* cause ldisc to notice changes */
2477                 ldisc_send(term->ldisc, NULL, 0, 0);
2478             break;
2479           case 25:                     /* DECTCEM: enable/disable cursor */
2480             compatibility2(OTHER, VT220);
2481             term->cursor_on = state;
2482             seen_disp_event(term);
2483             break;
2484           case 47:                     /* alternate screen */
2485             compatibility(OTHER);
2486             deselect(term);
2487             swap_screen(term, term->no_alt_screen ? 0 : state, FALSE, FALSE);
2488             term->disptop = 0;
2489             break;
2490           case 1000:                   /* xterm mouse 1 (normal) */
2491             term->xterm_mouse = state ? 1 : 0;
2492             set_raw_mouse_mode(term->frontend, state);
2493             break;
2494           case 1002:                   /* xterm mouse 2 (inc. button drags) */
2495             term->xterm_mouse = state ? 2 : 0;
2496             set_raw_mouse_mode(term->frontend, state);
2497             break;
2498           case 1006:                   /* xterm extended mouse */
2499             term->xterm_extended_mouse = state ? 1 : 0;
2500             break;
2501           case 1015:                   /* urxvt extended mouse */
2502             term->urxvt_extended_mouse = state ? 1 : 0;
2503             break;
2504           case 1047:                   /* alternate screen */
2505             compatibility(OTHER);
2506             deselect(term);
2507             swap_screen(term, term->no_alt_screen ? 0 : state, TRUE, TRUE);
2508             term->disptop = 0;
2509             break;
2510           case 1048:                   /* save/restore cursor */
2511             if (!term->no_alt_screen)
2512                 save_cursor(term, state);
2513             if (!state) seen_disp_event(term);
2514             break;
2515           case 1049:                   /* cursor & alternate screen */
2516             if (state && !term->no_alt_screen)
2517                 save_cursor(term, state);
2518             if (!state) seen_disp_event(term);
2519             compatibility(OTHER);
2520             deselect(term);
2521             swap_screen(term, term->no_alt_screen ? 0 : state, TRUE, FALSE);
2522             if (!state && !term->no_alt_screen)
2523                 save_cursor(term, state);
2524             term->disptop = 0;
2525             break;
2526           case 2004:                   /* xterm bracketed paste */
2527             term->bracketed_paste = state ? TRUE : FALSE;
2528             break;
2529     } else
2530         switch (mode) {
2531           case 4:                      /* IRM: set insert mode */
2532             compatibility(VT102);
2533             term->insert = state;
2534             break;
2535           case 12:                     /* SRM: set echo mode */
2536             term->term_echoing = !state;
2537             if (term->ldisc)           /* cause ldisc to notice changes */
2538                 ldisc_send(term->ldisc, NULL, 0, 0);
2539             break;
2540           case 20:                     /* LNM: Return sends ... */
2541             term->cr_lf_return = state;
2542             break;
2543           case 34:                     /* WYULCURM: Make cursor BIG */
2544             compatibility2(OTHER, VT220);
2545             term->big_cursor = !state;
2546         }
2547 }
2548
2549 /*
2550  * Process an OSC sequence: set window title or icon name.
2551  */
2552 static void do_osc(Terminal *term)
2553 {
2554     if (term->osc_w) {
2555         while (term->osc_strlen--)
2556             term->wordness[(unsigned char)
2557                 term->osc_string[term->osc_strlen]] = term->esc_args[0];
2558     } else {
2559         term->osc_string[term->osc_strlen] = '\0';
2560         switch (term->esc_args[0]) {
2561           case 0:
2562           case 1:
2563             if (!term->no_remote_wintitle)
2564                 set_icon(term->frontend, term->osc_string);
2565             if (term->esc_args[0] == 1)
2566                 break;
2567             /* fall through: parameter 0 means set both */
2568           case 2:
2569           case 21:
2570             if (!term->no_remote_wintitle)
2571                 set_title(term->frontend, term->osc_string);
2572             break;
2573         }
2574     }
2575 }
2576
2577 /*
2578  * ANSI printing routines.
2579  */
2580 static void term_print_setup(Terminal *term, char *printer)
2581 {
2582     bufchain_clear(&term->printer_buf);
2583     term->print_job = printer_start_job(printer);
2584 }
2585 static void term_print_flush(Terminal *term)
2586 {
2587     void *data;
2588     int len;
2589     int size;
2590     while ((size = bufchain_size(&term->printer_buf)) > 5) {
2591         bufchain_prefix(&term->printer_buf, &data, &len);
2592         if (len > size-5)
2593             len = size-5;
2594         printer_job_data(term->print_job, data, len);
2595         bufchain_consume(&term->printer_buf, len);
2596     }
2597 }
2598 static void term_print_finish(Terminal *term)
2599 {
2600     void *data;
2601     int len, size;
2602     char c;
2603
2604     if (!term->printing && !term->only_printing)
2605         return;                        /* we need do nothing */
2606
2607     term_print_flush(term);
2608     while ((size = bufchain_size(&term->printer_buf)) > 0) {
2609         bufchain_prefix(&term->printer_buf, &data, &len);
2610         c = *(char *)data;
2611         if (c == '\033' || c == '\233') {
2612             bufchain_consume(&term->printer_buf, size);
2613             break;
2614         } else {
2615             printer_job_data(term->print_job, &c, 1);
2616             bufchain_consume(&term->printer_buf, 1);
2617         }
2618     }
2619     printer_finish_job(term->print_job);
2620     term->print_job = NULL;
2621     term->printing = term->only_printing = FALSE;
2622 }
2623
2624 /*
2625  * Remove everything currently in `inbuf' and stick it up on the
2626  * in-memory display. There's a big state machine in here to
2627  * process escape sequences...
2628  */
2629 static void term_out(Terminal *term)
2630 {
2631     unsigned long c;
2632     int unget;
2633     unsigned char localbuf[256], *chars;
2634     int nchars = 0;
2635
2636     unget = -1;
2637
2638     chars = NULL;                      /* placate compiler warnings */
2639     while (nchars > 0 || unget != -1 || bufchain_size(&term->inbuf) > 0) {
2640         if (unget == -1) {
2641             if (nchars == 0) {
2642                 void *ret;
2643                 bufchain_prefix(&term->inbuf, &ret, &nchars);
2644                 if (nchars > sizeof(localbuf))
2645                     nchars = sizeof(localbuf);
2646                 memcpy(localbuf, ret, nchars);
2647                 bufchain_consume(&term->inbuf, nchars);
2648                 chars = localbuf;
2649                 assert(chars != NULL);
2650             }
2651             c = *chars++;
2652             nchars--;
2653
2654             /*
2655              * Optionally log the session traffic to a file. Useful for
2656              * debugging and possibly also useful for actual logging.
2657              */
2658             if (term->logtype == LGTYP_DEBUG && term->logctx)
2659                 logtraffic(term->logctx, (unsigned char) c, LGTYP_DEBUG);
2660         } else {
2661             c = unget;
2662             unget = -1;
2663         }
2664
2665         /* Note only VT220+ are 8-bit VT102 is seven bit, it shouldn't even
2666          * be able to display 8-bit characters, but I'll let that go 'cause
2667          * of i18n.
2668          */
2669
2670         /*
2671          * If we're printing, add the character to the printer
2672          * buffer.
2673          */
2674         if (term->printing) {
2675             bufchain_add(&term->printer_buf, &c, 1);
2676
2677             /*
2678              * If we're in print-only mode, we use a much simpler
2679              * state machine designed only to recognise the ESC[4i
2680              * termination sequence.
2681              */
2682             if (term->only_printing) {
2683                 if (c == '\033')
2684                     term->print_state = 1;
2685                 else if (c == (unsigned char)'\233')
2686                     term->print_state = 2;
2687                 else if (c == '[' && term->print_state == 1)
2688                     term->print_state = 2;
2689                 else if (c == '4' && term->print_state == 2)
2690                     term->print_state = 3;
2691                 else if (c == 'i' && term->print_state == 3)
2692                     term->print_state = 4;
2693                 else
2694                     term->print_state = 0;
2695                 if (term->print_state == 4) {
2696                     term_print_finish(term);
2697                 }
2698                 continue;
2699             }
2700         }
2701
2702         /* First see about all those translations. */
2703         if (term->termstate == TOPLEVEL) {
2704             if (in_utf(term))
2705                 switch (term->utf_state) {
2706                   case 0:
2707                     if (c < 0x80) {
2708                         /* UTF-8 must be stateless so we ignore iso2022. */
2709                         if (term->ucsdata->unitab_ctrl[c] != 0xFF) 
2710                              c = term->ucsdata->unitab_ctrl[c];
2711                         else c = ((unsigned char)c) | CSET_ASCII;
2712                         break;
2713                     } else if ((c & 0xe0) == 0xc0) {
2714                         term->utf_size = term->utf_state = 1;
2715                         term->utf_char = (c & 0x1f);
2716                     } else if ((c & 0xf0) == 0xe0) {
2717                         term->utf_size = term->utf_state = 2;
2718                         term->utf_char = (c & 0x0f);
2719                     } else if ((c & 0xf8) == 0xf0) {
2720                         term->utf_size = term->utf_state = 3;
2721                         term->utf_char = (c & 0x07);
2722                     } else if ((c & 0xfc) == 0xf8) {
2723                         term->utf_size = term->utf_state = 4;
2724                         term->utf_char = (c & 0x03);
2725                     } else if ((c & 0xfe) == 0xfc) {
2726                         term->utf_size = term->utf_state = 5;
2727                         term->utf_char = (c & 0x01);
2728                     } else {
2729                         c = UCSERR;
2730                         break;
2731                     }
2732                     continue;
2733                   case 1:
2734                   case 2:
2735                   case 3:
2736                   case 4:
2737                   case 5:
2738                     if ((c & 0xC0) != 0x80) {
2739                         unget = c;
2740                         c = UCSERR;
2741                         term->utf_state = 0;
2742                         break;
2743                     }
2744                     term->utf_char = (term->utf_char << 6) | (c & 0x3f);
2745                     if (--term->utf_state)
2746                         continue;
2747
2748                     c = term->utf_char;
2749
2750                     /* Is somebody trying to be evil! */
2751                     if (c < 0x80 ||
2752                         (c < 0x800 && term->utf_size >= 2) ||
2753                         (c < 0x10000 && term->utf_size >= 3) ||
2754                         (c < 0x200000 && term->utf_size >= 4) ||
2755                         (c < 0x4000000 && term->utf_size >= 5))
2756                         c = UCSERR;
2757
2758                     /* Unicode line separator and paragraph separator are CR-LF */
2759                     if (c == 0x2028 || c == 0x2029)
2760                         c = 0x85;
2761
2762                     /* High controls are probably a Baaad idea too. */
2763                     if (c < 0xA0)
2764                         c = 0xFFFD;
2765
2766                     /* The UTF-16 surrogates are not nice either. */
2767                     /*       The standard give the option of decoding these: 
2768                      *       I don't want to! */
2769                     if (c >= 0xD800 && c < 0xE000)
2770                         c = UCSERR;
2771
2772                     /* ISO 10646 characters now limited to UTF-16 range. */
2773                     if (c > 0x10FFFF)
2774                         c = UCSERR;
2775
2776                     /* This is currently a TagPhobic application.. */
2777                     if (c >= 0xE0000 && c <= 0xE007F)
2778                         continue;
2779
2780                     /* U+FEFF is best seen as a null. */
2781                     if (c == 0xFEFF)
2782                         continue;
2783                     /* But U+FFFE is an error. */
2784                     if (c == 0xFFFE || c == 0xFFFF)
2785                         c = UCSERR;
2786
2787                     break;
2788             }
2789             /* Are we in the nasty ACS mode? Note: no sco in utf mode. */
2790             else if(term->sco_acs && 
2791                     (c!='\033' && c!='\012' && c!='\015' && c!='\b'))
2792             {
2793                if (term->sco_acs == 2) c |= 0x80;
2794                c |= CSET_SCOACS;
2795             } else {
2796                 switch (term->cset_attr[term->cset]) {
2797                     /* 
2798                      * Linedraw characters are different from 'ESC ( B'
2799                      * only for a small range. For ones outside that
2800                      * range, make sure we use the same font as well as
2801                      * the same encoding.
2802                      */
2803                   case CSET_LINEDRW:
2804                     if (term->ucsdata->unitab_ctrl[c] != 0xFF)
2805                         c = term->ucsdata->unitab_ctrl[c];
2806                     else
2807                         c = ((unsigned char) c) | CSET_LINEDRW;
2808                     break;
2809
2810                   case CSET_GBCHR:
2811                     /* If UK-ASCII, make the '#' a LineDraw Pound */
2812                     if (c == '#') {
2813                         c = '}' | CSET_LINEDRW;
2814                         break;
2815                     }
2816                   /*FALLTHROUGH*/ case CSET_ASCII:
2817                     if (term->ucsdata->unitab_ctrl[c] != 0xFF)
2818                         c = term->ucsdata->unitab_ctrl[c];
2819                     else
2820                         c = ((unsigned char) c) | CSET_ASCII;
2821                     break;
2822                 case CSET_SCOACS:
2823                     if (c>=' ') c = ((unsigned char)c) | CSET_SCOACS;
2824                     break;
2825                 }
2826             }
2827         }
2828
2829         /*
2830          * How about C1 controls? 
2831          * Explicitly ignore SCI (0x9a), which we don't translate to DECID.
2832          */
2833         if ((c & -32) == 0x80 && term->termstate < DO_CTRLS &&
2834             !term->vt52_mode && has_compat(VT220)) {
2835             if (c == 0x9a)
2836                 c = 0;
2837             else {
2838                 term->termstate = SEEN_ESC;
2839                 term->esc_query = FALSE;
2840                 c = '@' + (c & 0x1F);
2841             }
2842         }
2843
2844         /* Or the GL control. */
2845         if (c == '\177' && term->termstate < DO_CTRLS && has_compat(OTHER)) {
2846             if (term->curs.x && !term->wrapnext)
2847                 term->curs.x--;
2848             term->wrapnext = FALSE;
2849             /* destructive backspace might be disabled */
2850             if (!term->no_dbackspace) {
2851                 check_boundary(term, term->curs.x, term->curs.y);
2852                 check_boundary(term, term->curs.x+1, term->curs.y);
2853                 copy_termchar(scrlineptr(term->curs.y),
2854                               term->curs.x, &term->erase_char);
2855             }
2856         } else
2857             /* Or normal C0 controls. */
2858         if ((c & ~0x1F) == 0 && term->termstate < DO_CTRLS) {
2859             switch (c) {
2860               case '\005':             /* ENQ: terminal type query */
2861                 /* 
2862                  * Strictly speaking this is VT100 but a VT100 defaults to
2863                  * no response. Other terminals respond at their option.
2864                  *
2865                  * Don't put a CR in the default string as this tends to
2866                  * upset some weird software.
2867                  */
2868                 compatibility(ANSIMIN);
2869                 if (term->ldisc) {
2870                     lpage_send(term->ldisc, DEFAULT_CODEPAGE,
2871                                term->answerback, term->answerbacklen, 0);
2872                 }
2873                 break;
2874               case '\007':            /* BEL: Bell */
2875                 {
2876                     struct beeptime *newbeep;
2877                     unsigned long ticks;
2878
2879                     ticks = GETTICKCOUNT();
2880
2881                     if (!term->beep_overloaded) {
2882                         newbeep = snew(struct beeptime);
2883                         newbeep->ticks = ticks;
2884                         newbeep->next = NULL;
2885                         if (!term->beephead)
2886                             term->beephead = newbeep;
2887                         else
2888                             term->beeptail->next = newbeep;
2889                         term->beeptail = newbeep;
2890                         term->nbeeps++;
2891                     }
2892
2893                     /*
2894                      * Throw out any beeps that happened more than
2895                      * t seconds ago.
2896                      */
2897                     while (term->beephead &&
2898                            term->beephead->ticks < ticks - term->bellovl_t) {
2899                         struct beeptime *tmp = term->beephead;
2900                         term->beephead = tmp->next;
2901                         sfree(tmp);
2902                         if (!term->beephead)
2903                             term->beeptail = NULL;
2904                         term->nbeeps--;
2905                     }
2906
2907                     if (term->bellovl && term->beep_overloaded &&
2908                         ticks - term->lastbeep >= (unsigned)term->bellovl_s) {
2909                         /*
2910                          * If we're currently overloaded and the
2911                          * last beep was more than s seconds ago,
2912                          * leave overload mode.
2913                          */
2914                         term->beep_overloaded = FALSE;
2915                     } else if (term->bellovl && !term->beep_overloaded &&
2916                                term->nbeeps >= term->bellovl_n) {
2917                         /*
2918                          * Now, if we have n or more beeps
2919                          * remaining in the queue, go into overload
2920                          * mode.
2921                          */
2922                         term->beep_overloaded = TRUE;
2923                     }
2924                     term->lastbeep = ticks;
2925
2926                     /*
2927                      * Perform an actual beep if we're not overloaded.
2928                      */
2929                     if (!term->bellovl || !term->beep_overloaded) {
2930                         do_beep(term->frontend, term->beep);
2931
2932                         if (term->beep == BELL_VISUAL) {
2933                             term_schedule_vbell(term, FALSE, 0);
2934                         }
2935                     }
2936                     seen_disp_event(term);
2937                 }
2938                 break;
2939               case '\b':              /* BS: Back space */
2940                 if (term->curs.x == 0 &&
2941                     (term->curs.y == 0 || term->wrap == 0))
2942                     /* do nothing */ ;
2943                 else if (term->curs.x == 0 && term->curs.y > 0)
2944                     term->curs.x = term->cols - 1, term->curs.y--;
2945                 else if (term->wrapnext)
2946                     term->wrapnext = FALSE;
2947                 else
2948                     term->curs.x--;
2949                 seen_disp_event(term);
2950                 break;
2951               case '\016':            /* LS1: Locking-shift one */
2952                 compatibility(VT100);
2953                 term->cset = 1;
2954                 break;
2955               case '\017':            /* LS0: Locking-shift zero */
2956                 compatibility(VT100);
2957                 term->cset = 0;
2958                 break;
2959               case '\033':            /* ESC: Escape */
2960                 if (term->vt52_mode)
2961                     term->termstate = VT52_ESC;
2962                 else {
2963                     compatibility(ANSIMIN);
2964                     term->termstate = SEEN_ESC;
2965                     term->esc_query = FALSE;
2966                 }
2967                 break;
2968               case '\015':            /* CR: Carriage return */
2969                 term->curs.x = 0;
2970                 term->wrapnext = FALSE;
2971                 seen_disp_event(term);
2972                 term_resume_pasting(term);
2973
2974                 if (term->crhaslf) {
2975                     if (term->curs.y == term->marg_b)
2976                         scroll(term, term->marg_t, term->marg_b, 1, TRUE);
2977                     else if (term->curs.y < term->rows - 1)
2978                         term->curs.y++;
2979                 }
2980                 if (term->logctx)
2981                     logtraffic(term->logctx, (unsigned char) c, LGTYP_ASCII);
2982                 break;
2983               case '\014':            /* FF: Form feed */
2984                 if (has_compat(SCOANSI)) {
2985                     move(term, 0, 0, 0);
2986                     erase_lots(term, FALSE, FALSE, TRUE);
2987                     term->disptop = 0;
2988                     term->wrapnext = FALSE;
2989                     seen_disp_event(term);
2990                     break;
2991                 }
2992               case '\013':            /* VT: Line tabulation */
2993                 compatibility(VT100);
2994               case '\012':            /* LF: Line feed */
2995                 if (term->curs.y == term->marg_b)
2996                     scroll(term, term->marg_t, term->marg_b, 1, TRUE);
2997                 else if (term->curs.y < term->rows - 1)
2998                     term->curs.y++;
2999                 if (term->lfhascr)
3000                     term->curs.x = 0;
3001                 term->wrapnext = FALSE;
3002                 seen_disp_event(term);
3003                 term_resume_pasting(term);
3004                 if (term->logctx)
3005                     logtraffic(term->logctx, (unsigned char) c, LGTYP_ASCII);
3006                 break;
3007               case '\t':              /* HT: Character tabulation */
3008                 {
3009                     pos old_curs = term->curs;
3010                     termline *ldata = scrlineptr(term->curs.y);
3011
3012                     do {
3013                         term->curs.x++;
3014                     } while (term->curs.x < term->cols - 1 &&
3015                              !term->tabs[term->curs.x]);
3016
3017                     if ((ldata->lattr & LATTR_MODE) != LATTR_NORM) {
3018                         if (term->curs.x >= term->cols / 2)
3019                             term->curs.x = term->cols / 2 - 1;
3020                     } else {
3021                         if (term->curs.x >= term->cols)
3022                             term->curs.x = term->cols - 1;
3023                     }
3024
3025                     check_selection(term, old_curs, term->curs);
3026                 }
3027                 seen_disp_event(term);
3028                 break;
3029             }
3030         } else
3031             switch (term->termstate) {
3032               case TOPLEVEL:
3033                 /* Only graphic characters get this far;
3034                  * ctrls are stripped above */
3035                 {
3036                     termline *cline = scrlineptr(term->curs.y);
3037                     int width = 0;
3038                     if (DIRECT_CHAR(c))
3039                         width = 1;
3040                     if (!width)
3041                         width = (term->cjk_ambig_wide ?
3042                                  mk_wcwidth_cjk((unsigned int) c) :
3043                                  mk_wcwidth((unsigned int) c));
3044
3045                     if (term->wrapnext && term->wrap && width > 0) {
3046                         cline->lattr |= LATTR_WRAPPED;
3047                         if (term->curs.y == term->marg_b)
3048                             scroll(term, term->marg_t, term->marg_b, 1, TRUE);
3049                         else if (term->curs.y < term->rows - 1)
3050                             term->curs.y++;
3051                         term->curs.x = 0;
3052                         term->wrapnext = FALSE;
3053                         cline = scrlineptr(term->curs.y);
3054                     }
3055                     if (term->insert && width > 0)
3056                         insch(term, width);
3057                     if (term->selstate != NO_SELECTION) {
3058                         pos cursplus = term->curs;
3059                         incpos(cursplus);
3060                         check_selection(term, term->curs, cursplus);
3061                     }
3062                     if (((c & CSET_MASK) == CSET_ASCII ||
3063                          (c & CSET_MASK) == 0) &&
3064                         term->logctx)
3065                         logtraffic(term->logctx, (unsigned char) c,
3066                                    LGTYP_ASCII);
3067
3068                     switch (width) {
3069                       case 2:
3070                         /*
3071                          * If we're about to display a double-width
3072                          * character starting in the rightmost
3073                          * column, then we do something special
3074                          * instead. We must print a space in the
3075                          * last column of the screen, then wrap;
3076                          * and we also set LATTR_WRAPPED2 which
3077                          * instructs subsequent cut-and-pasting not
3078                          * only to splice this line to the one
3079                          * after it, but to ignore the space in the
3080                          * last character position as well.
3081                          * (Because what was actually output to the
3082                          * terminal was presumably just a sequence
3083                          * of CJK characters, and we don't want a
3084                          * space to be pasted in the middle of
3085                          * those just because they had the
3086                          * misfortune to start in the wrong parity
3087                          * column. xterm concurs.)
3088                          */
3089                         check_boundary(term, term->curs.x, term->curs.y);
3090                         check_boundary(term, term->curs.x+2, term->curs.y);
3091                         if (term->curs.x == term->cols-1) {
3092                             copy_termchar(cline, term->curs.x,
3093                                           &term->erase_char);
3094                             cline->lattr |= LATTR_WRAPPED | LATTR_WRAPPED2;
3095                             if (term->curs.y == term->marg_b)
3096                                 scroll(term, term->marg_t, term->marg_b,
3097                                        1, TRUE);
3098                             else if (term->curs.y < term->rows - 1)
3099                                 term->curs.y++;
3100                             term->curs.x = 0;
3101                             cline = scrlineptr(term->curs.y);
3102                             /* Now we must check_boundary again, of course. */
3103                             check_boundary(term, term->curs.x, term->curs.y);
3104                             check_boundary(term, term->curs.x+2, term->curs.y);
3105                         }
3106
3107                         /* FULL-TERMCHAR */
3108                         clear_cc(cline, term->curs.x);
3109                         cline->chars[term->curs.x].chr = c;
3110                         cline->chars[term->curs.x].attr = term->curr_attr;
3111
3112                         term->curs.x++;
3113
3114                         /* FULL-TERMCHAR */
3115                         clear_cc(cline, term->curs.x);
3116                         cline->chars[term->curs.x].chr = UCSWIDE;
3117                         cline->chars[term->curs.x].attr = term->curr_attr;
3118
3119                         break;
3120                       case 1:
3121                         check_boundary(term, term->curs.x, term->curs.y);
3122                         check_boundary(term, term->curs.x+1, term->curs.y);
3123
3124                         /* FULL-TERMCHAR */
3125                         clear_cc(cline, term->curs.x);
3126                         cline->chars[term->curs.x].chr = c;
3127                         cline->chars[term->curs.x].attr = term->curr_attr;
3128
3129                         break;
3130                       case 0:
3131                         if (term->curs.x > 0) {
3132                             int x = term->curs.x - 1;
3133
3134                             /* If we're in wrapnext state, the character
3135                              * to combine with is _here_, not to our left. */
3136                             if (term->wrapnext)
3137                                 x++;
3138
3139                             /*
3140                              * If the previous character is
3141                              * UCSWIDE, back up another one.
3142                              */
3143                             if (cline->chars[x].chr == UCSWIDE) {
3144                                 assert(x > 0);
3145                                 x--;
3146                             }
3147
3148                             add_cc(cline, x, c);
3149                             seen_disp_event(term);
3150                         }
3151                         continue;
3152                       default:
3153                         continue;
3154                     }
3155                     term->curs.x++;
3156                     if (term->curs.x == term->cols) {
3157                         term->curs.x--;
3158                         term->wrapnext = TRUE;
3159                         if (term->wrap && term->vt52_mode) {
3160                             cline->lattr |= LATTR_WRAPPED;
3161                             if (term->curs.y == term->marg_b)
3162                                 scroll(term, term->marg_t, term->marg_b, 1, TRUE);
3163                             else if (term->curs.y < term->rows - 1)
3164                                 term->curs.y++;
3165                             term->curs.x = 0;
3166                             term->wrapnext = FALSE;
3167                         }
3168                     }
3169                     seen_disp_event(term);
3170                 }
3171                 break;
3172
3173               case OSC_MAYBE_ST:
3174                 /*
3175                  * This state is virtually identical to SEEN_ESC, with the
3176                  * exception that we have an OSC sequence in the pipeline,
3177                  * and _if_ we see a backslash, we process it.
3178                  */
3179                 if (c == '\\') {
3180                     do_osc(term);
3181                     term->termstate = TOPLEVEL;
3182                     break;
3183                 }
3184                 /* else fall through */
3185               case SEEN_ESC:
3186                 if (c >= ' ' && c <= '/') {
3187                     if (term->esc_query)
3188                         term->esc_query = -1;
3189                     else
3190                         term->esc_query = c;
3191                     break;
3192                 }
3193                 term->termstate = TOPLEVEL;
3194                 switch (ANSI(c, term->esc_query)) {
3195                   case '[':             /* enter CSI mode */
3196                     term->termstate = SEEN_CSI;
3197                     term->esc_nargs = 1;
3198                     term->esc_args[0] = ARG_DEFAULT;
3199                     term->esc_query = FALSE;
3200                     break;
3201                   case ']':             /* OSC: xterm escape sequences */
3202                     /* Compatibility is nasty here, xterm, linux, decterm yuk! */
3203                     compatibility(OTHER);
3204                     term->termstate = SEEN_OSC;
3205                     term->esc_args[0] = 0;
3206                     break;
3207                   case '7':             /* DECSC: save cursor */
3208                     compatibility(VT100);
3209                     save_cursor(term, TRUE);
3210                     break;
3211                   case '8':             /* DECRC: restore cursor */
3212                     compatibility(VT100);
3213                     save_cursor(term, FALSE);
3214                     seen_disp_event(term);
3215                     break;
3216                   case '=':             /* DECKPAM: Keypad application mode */
3217                     compatibility(VT100);
3218                     term->app_keypad_keys = TRUE;
3219                     break;
3220                   case '>':             /* DECKPNM: Keypad numeric mode */
3221                     compatibility(VT100);
3222                     term->app_keypad_keys = FALSE;
3223                     break;
3224                   case 'D':            /* IND: exactly equivalent to LF */
3225                     compatibility(VT100);
3226                     if (term->curs.y == term->marg_b)
3227                         scroll(term, term->marg_t, term->marg_b, 1, TRUE);
3228                     else if (term->curs.y < term->rows - 1)
3229                         term->curs.y++;
3230                     term->wrapnext = FALSE;
3231                     seen_disp_event(term);
3232                     break;
3233                   case 'E':            /* NEL: exactly equivalent to CR-LF */
3234                     compatibility(VT100);
3235                     term->curs.x = 0;
3236                     if (term->curs.y == term->marg_b)
3237                         scroll(term, term->marg_t, term->marg_b, 1, TRUE);
3238                     else if (term->curs.y < term->rows - 1)
3239                         term->curs.y++;
3240                     term->wrapnext = FALSE;
3241                     seen_disp_event(term);
3242                     break;
3243                   case 'M':            /* RI: reverse index - backwards LF */
3244                     compatibility(VT100);
3245                     if (term->curs.y == term->marg_t)
3246                         scroll(term, term->marg_t, term->marg_b, -1, TRUE);
3247                     else if (term->curs.y > 0)
3248                         term->curs.y--;
3249                     term->wrapnext = FALSE;
3250                     seen_disp_event(term);
3251                     break;
3252                   case 'Z':            /* DECID: terminal type query */
3253                     compatibility(VT100);
3254                     if (term->ldisc)
3255                         ldisc_send(term->ldisc, term->id_string,
3256                                    strlen(term->id_string), 0);
3257                     break;
3258                   case 'c':            /* RIS: restore power-on settings */
3259                     compatibility(VT100);
3260                     power_on(term, TRUE);
3261                     if (term->ldisc)   /* cause ldisc to notice changes */
3262                         ldisc_send(term->ldisc, NULL, 0, 0);
3263                     if (term->reset_132) {
3264                         if (!term->no_remote_resize)
3265                             request_resize(term->frontend, 80, term->rows);
3266                         term->reset_132 = 0;
3267                     }
3268                     term->disptop = 0;
3269                     seen_disp_event(term);
3270                     break;
3271                   case 'H':            /* HTS: set a tab */
3272                     compatibility(VT100);
3273                     term->tabs[term->curs.x] = TRUE;
3274                     break;
3275
3276                   case ANSI('8', '#'):  /* DECALN: fills screen with Es :-) */
3277                     compatibility(VT100);
3278                     {
3279                         termline *ldata;
3280                         int i, j;
3281                         pos scrtop, scrbot;
3282
3283                         for (i = 0; i < term->rows; i++) {
3284                             ldata = scrlineptr(i);
3285                             for (j = 0; j < term->cols; j++) {
3286                                 copy_termchar(ldata, j,
3287                                               &term->basic_erase_char);
3288                                 ldata->chars[j].chr = 'E';
3289                             }
3290                             ldata->lattr = LATTR_NORM;
3291                         }
3292                         term->disptop = 0;
3293                         seen_disp_event(term);
3294                         scrtop.x = scrtop.y = 0;
3295                         scrbot.x = 0;
3296                         scrbot.y = term->rows;
3297                         check_selection(term, scrtop, scrbot);
3298                     }
3299                     break;
3300
3301                   case ANSI('3', '#'):
3302                   case ANSI('4', '#'):
3303                   case ANSI('5', '#'):
3304                   case ANSI('6', '#'):
3305                     compatibility(VT100);
3306                     {
3307                         int nlattr;
3308
3309                         switch (ANSI(c, term->esc_query)) {
3310                           case ANSI('3', '#'): /* DECDHL: 2*height, top */
3311                             nlattr = LATTR_TOP;
3312                             break;
3313                           case ANSI('4', '#'): /* DECDHL: 2*height, bottom */
3314                             nlattr = LATTR_BOT;
3315                             break;
3316                           case ANSI('5', '#'): /* DECSWL: normal */
3317                             nlattr = LATTR_NORM;
3318                             break;
3319                           default: /* case ANSI('6', '#'): DECDWL: 2*width */
3320                             nlattr = LATTR_WIDE;
3321                             break;
3322                         }
3323                         scrlineptr(term->curs.y)->lattr = nlattr;
3324                     }
3325                     break;
3326                   /* GZD4: G0 designate 94-set */
3327                   case ANSI('A', '('):
3328                     compatibility(VT100);
3329                     if (!term->no_remote_charset)
3330                         term->cset_attr[0] = CSET_GBCHR;
3331                     break;
3332                   case ANSI('B', '('):
3333                     compatibility(VT100);
3334                     if (!term->no_remote_charset)
3335                         term->cset_attr[0] = CSET_ASCII;
3336                     break;
3337                   case ANSI('0', '('):
3338                     compatibility(VT100);
3339                     if (!term->no_remote_charset)
3340                         term->cset_attr[0] = CSET_LINEDRW;
3341                     break;
3342                   case ANSI('U', '('): 
3343                     compatibility(OTHER);
3344                     if (!term->no_remote_charset)
3345                         term->cset_attr[0] = CSET_SCOACS; 
3346                     break;
3347                   /* G1D4: G1-designate 94-set */
3348                   case ANSI('A', ')'):
3349                     compatibility(VT100);
3350                     if (!term->no_remote_charset)
3351                         term->cset_attr[1] = CSET_GBCHR;
3352                     break;
3353                   case ANSI('B', ')'):
3354                     compatibility(VT100);
3355                     if (!term->no_remote_charset)
3356                         term->cset_attr[1] = CSET_ASCII;
3357                     break;
3358                   case ANSI('0', ')'):
3359                     compatibility(VT100);
3360                     if (!term->no_remote_charset)
3361                         term->cset_attr[1] = CSET_LINEDRW;
3362                     break;
3363                   case ANSI('U', ')'): 
3364                     compatibility(OTHER);
3365                     if (!term->no_remote_charset)
3366                         term->cset_attr[1] = CSET_SCOACS; 
3367                     break;
3368                   /* DOCS: Designate other coding system */
3369                   case ANSI('8', '%'):  /* Old Linux code */
3370                   case ANSI('G', '%'):
3371                     compatibility(OTHER);
3372                     if (!term->no_remote_charset)
3373                         term->utf = 1;
3374                     break;
3375                   case ANSI('@', '%'):
3376                     compatibility(OTHER);
3377                     if (!term->no_remote_charset)
3378                         term->utf = 0;
3379                     break;
3380                 }
3381                 break;
3382               case SEEN_CSI:
3383                 term->termstate = TOPLEVEL;  /* default */
3384                 if (isdigit(c)) {
3385                     if (term->esc_nargs <= ARGS_MAX) {
3386                         if (term->esc_args[term->esc_nargs - 1] == ARG_DEFAULT)
3387                             term->esc_args[term->esc_nargs - 1] = 0;
3388                         term->esc_args[term->esc_nargs - 1] =
3389                             10 * term->esc_args[term->esc_nargs - 1] + c - '0';
3390                     }
3391                     term->termstate = SEEN_CSI;
3392                 } else if (c == ';') {
3393                     if (term->esc_nargs < ARGS_MAX)
3394                         term->esc_args[term->esc_nargs++] = ARG_DEFAULT;
3395                     term->termstate = SEEN_CSI;
3396                 } else if (c < '@') {
3397                     if (term->esc_query)
3398                         term->esc_query = -1;
3399                     else if (c == '?')
3400                         term->esc_query = TRUE;
3401                     else
3402                         term->esc_query = c;
3403                     term->termstate = SEEN_CSI;
3404                 } else
3405                     switch (ANSI(c, term->esc_query)) {
3406                       case 'A':       /* CUU: move up N lines */
3407                         move(term, term->curs.x,
3408                              term->curs.y - def(term->esc_args[0], 1), 1);
3409                         seen_disp_event(term);
3410                         break;
3411                       case 'e':         /* VPR: move down N lines */
3412                         compatibility(ANSI);
3413                         /* FALLTHROUGH */
3414                       case 'B':         /* CUD: Cursor down */
3415                         move(term, term->curs.x,
3416                              term->curs.y + def(term->esc_args[0], 1), 1);
3417                         seen_disp_event(term);
3418                         break;
3419                       case ANSI('c', '>'):      /* DA: report xterm version */
3420                         compatibility(OTHER);
3421                         /* this reports xterm version 136 so that VIM can
3422                            use the drag messages from the mouse reporting */
3423                         if (term->ldisc)
3424                             ldisc_send(term->ldisc, "\033[>0;136;0c", 11, 0);
3425                         break;
3426                       case 'a':         /* HPR: move right N cols */
3427                         compatibility(ANSI);
3428                         /* FALLTHROUGH */
3429                       case 'C':         /* CUF: Cursor right */ 
3430                         move(term, term->curs.x + def(term->esc_args[0], 1),
3431                              term->curs.y, 1);
3432                         seen_disp_event(term);
3433                         break;
3434                       case 'D':       /* CUB: move left N cols */
3435                         move(term, term->curs.x - def(term->esc_args[0], 1),
3436                              term->curs.y, 1);
3437                         seen_disp_event(term);
3438                         break;
3439                       case 'E':       /* CNL: move down N lines and CR */
3440                         compatibility(ANSI);
3441                         move(term, 0,
3442                              term->curs.y + def(term->esc_args[0], 1), 1);
3443                         seen_disp_event(term);
3444                         break;
3445                       case 'F':       /* CPL: move up N lines and CR */
3446                         compatibility(ANSI);
3447                         move(term, 0,
3448                              term->curs.y - def(term->esc_args[0], 1), 1);
3449                         seen_disp_event(term);
3450                         break;
3451                       case 'G':       /* CHA */
3452                       case '`':       /* HPA: set horizontal posn */
3453                         compatibility(ANSI);
3454                         move(term, def(term->esc_args[0], 1) - 1,
3455                              term->curs.y, 0);
3456                         seen_disp_event(term);
3457                         break;
3458                       case 'd':       /* VPA: set vertical posn */
3459                         compatibility(ANSI);
3460                         move(term, term->curs.x,
3461                              ((term->dec_om ? term->marg_t : 0) +
3462                               def(term->esc_args[0], 1) - 1),
3463                              (term->dec_om ? 2 : 0));
3464                         seen_disp_event(term);
3465                         break;
3466                       case 'H':      /* CUP */
3467                       case 'f':      /* HVP: set horz and vert posns at once */
3468                         if (term->esc_nargs < 2)
3469                             term->esc_args[1] = ARG_DEFAULT;
3470                         move(term, def(term->esc_args[1], 1) - 1,
3471                              ((term->dec_om ? term->marg_t : 0) +
3472                               def(term->esc_args[0], 1) - 1),
3473                              (term->dec_om ? 2 : 0));
3474                         seen_disp_event(term);
3475                         break;
3476                       case 'J':       /* ED: erase screen or parts of it */
3477                         {
3478                             unsigned int i = def(term->esc_args[0], 0);
3479                             if (i == 3) {
3480                                 /* Erase Saved Lines (xterm)
3481                                  * This follows Thomas Dickey's xterm. */
3482                                 term_clrsb(term);
3483                             } else {
3484                                 i++;
3485                                 if (i > 3)
3486                                     i = 0;
3487                                 erase_lots(term, FALSE, !!(i & 2), !!(i & 1));
3488                             }
3489                         }
3490                         term->disptop = 0;
3491                         seen_disp_event(term);
3492                         break;
3493                       case 'K':       /* EL: erase line or parts of it */
3494                         {
3495                             unsigned int i = def(term->esc_args[0], 0) + 1;
3496                             if (i > 3)
3497                                 i = 0;
3498                             erase_lots(term, TRUE, !!(i & 2), !!(i & 1));
3499                         }
3500                         seen_disp_event(term);
3501                         break;
3502                       case 'L':       /* IL: insert lines */
3503                         compatibility(VT102);
3504                         if (term->curs.y <= term->marg_b)
3505                             scroll(term, term->curs.y, term->marg_b,
3506                                    -def(term->esc_args[0], 1), FALSE);
3507                         seen_disp_event(term);
3508                         break;
3509                       case 'M':       /* DL: delete lines */
3510                         compatibility(VT102);
3511                         if (term->curs.y <= term->marg_b)
3512                             scroll(term, term->curs.y, term->marg_b,
3513                                    def(term->esc_args[0], 1),
3514                                    TRUE);
3515                         seen_disp_event(term);
3516                         break;
3517                       case '@':       /* ICH: insert chars */
3518                         /* XXX VTTEST says this is vt220, vt510 manual says vt102 */
3519                         compatibility(VT102);
3520                         insch(term, def(term->esc_args[0], 1));
3521                         seen_disp_event(term);
3522                         break;
3523                       case 'P':       /* DCH: delete chars */
3524                         compatibility(VT102);
3525                         insch(term, -def(term->esc_args[0], 1));
3526                         seen_disp_event(term);
3527                         break;
3528                       case 'c':       /* DA: terminal type query */
3529                         compatibility(VT100);
3530                         /* This is the response for a VT102 */
3531                         if (term->ldisc)
3532                             ldisc_send(term->ldisc, term->id_string,
3533                                        strlen(term->id_string), 0);
3534                         break;
3535                       case 'n':       /* DSR: cursor position query */
3536                         if (term->ldisc) {
3537                             if (term->esc_args[0] == 6) {
3538                                 char buf[32];
3539                                 sprintf(buf, "\033[%d;%dR", term->curs.y + 1,
3540                                         term->curs.x + 1);
3541                                 ldisc_send(term->ldisc, buf, strlen(buf), 0);
3542                             } else if (term->esc_args[0] == 5) {
3543                                 ldisc_send(term->ldisc, "\033[0n", 4, 0);
3544                             }
3545                         }
3546                         break;
3547                       case 'h':       /* SM: toggle modes to high */
3548                       case ANSI_QUE('h'):
3549                         compatibility(VT100);
3550                         {
3551                             int i;
3552                             for (i = 0; i < term->esc_nargs; i++)
3553                                 toggle_mode(term, term->esc_args[i],
3554                                             term->esc_query, TRUE);
3555                         }
3556                         break;
3557                       case 'i':         /* MC: Media copy */
3558                       case ANSI_QUE('i'):
3559                         compatibility(VT100);
3560                         {
3561                             char *printer;
3562                             if (term->esc_nargs != 1) break;
3563                             if (term->esc_args[0] == 5 && 
3564                                 (printer = conf_get_str(term->conf,
3565                                                         CONF_printer))[0]) {
3566                                 term->printing = TRUE;
3567                                 term->only_printing = !term->esc_query;
3568                                 term->print_state = 0;
3569                                 term_print_setup(term, printer);
3570                             } else if (term->esc_args[0] == 4 &&
3571                                        term->printing) {
3572                                 term_print_finish(term);
3573                             }
3574                         }
3575                         break;                  
3576                       case 'l':       /* RM: toggle modes to low */
3577                       case ANSI_QUE('l'):
3578                         compatibility(VT100);
3579                         {
3580                             int i;
3581                             for (i = 0; i < term->esc_nargs; i++)
3582                                 toggle_mode(term, term->esc_args[i],
3583                                             term->esc_query, FALSE);
3584                         }
3585                         break;
3586                       case 'g':       /* TBC: clear tabs */
3587                         compatibility(VT100);
3588                         if (term->esc_nargs == 1) {
3589                             if (term->esc_args[0] == 0) {
3590                                 term->tabs[term->curs.x] = FALSE;
3591                             } else if (term->esc_args[0] == 3) {
3592                                 int i;
3593                                 for (i = 0; i < term->cols; i++)
3594                                     term->tabs[i] = FALSE;
3595                             }
3596                         }
3597                         break;
3598                       case 'r':       /* DECSTBM: set scroll margins */
3599                         compatibility(VT100);
3600                         if (term->esc_nargs <= 2) {
3601                             int top, bot;
3602                             top = def(term->esc_args[0], 1) - 1;
3603                             bot = (term->esc_nargs <= 1
3604                                    || term->esc_args[1] == 0 ?
3605                                    term->rows :
3606                                    def(term->esc_args[1], term->rows)) - 1;
3607                             if (bot >= term->rows)
3608                                 bot = term->rows - 1;
3609                             /* VTTEST Bug 9 - if region is less than 2 lines
3610                              * don't change region.
3611                              */
3612                             if (bot - top > 0) {
3613                                 term->marg_t = top;
3614                                 term->marg_b = bot;
3615                                 term->curs.x = 0;
3616                                 /*
3617                                  * I used to think the cursor should be
3618                                  * placed at the top of the newly marginned
3619                                  * area. Apparently not: VMS TPU falls over
3620                                  * if so.
3621                                  *
3622                                  * Well actually it should for
3623                                  * Origin mode - RDB
3624                                  */
3625                                 term->curs.y = (term->dec_om ?
3626                                                 term->marg_t : 0);
3627                                 seen_disp_event(term);
3628                             }
3629                         }
3630                         break;
3631                       case 'm':       /* SGR: set graphics rendition */
3632                         {
3633                             /* 
3634                              * A VT100 without the AVO only had one
3635                              * attribute, either underline or
3636                              * reverse video depending on the
3637                              * cursor type, this was selected by
3638                              * CSI 7m.
3639                              *
3640                              * case 2:
3641                              *  This is sometimes DIM, eg on the
3642                              *  GIGI and Linux
3643                              * case 8:
3644                              *  This is sometimes INVIS various ANSI.
3645                              * case 21:
3646                              *  This like 22 disables BOLD, DIM and INVIS
3647                              *
3648                              * The ANSI colours appear on any
3649                              * terminal that has colour (obviously)
3650                              * but the interaction between sgr0 and
3651                              * the colours varies but is usually
3652                              * related to the background colour
3653                              * erase item. The interaction between
3654                              * colour attributes and the mono ones
3655                              * is also very implementation
3656                              * dependent.
3657                              *
3658                              * The 39 and 49 attributes are likely
3659                              * to be unimplemented.
3660                              */
3661                             int i;
3662                             for (i = 0; i < term->esc_nargs; i++) {
3663                                 switch (def(term->esc_args[i], 0)) {
3664                                   case 0:       /* restore defaults */
3665                                     term->curr_attr = term->default_attr;
3666                                     break;
3667                                   case 1:       /* enable bold */
3668                                     compatibility(VT100AVO);
3669                                     term->curr_attr |= ATTR_BOLD;
3670                                     break;
3671                                   case 21:      /* (enable double underline) */
3672                                     compatibility(OTHER);
3673                                   case 4:       /* enable underline */
3674                                     compatibility(VT100AVO);
3675                                     term->curr_attr |= ATTR_UNDER;
3676                                     break;
3677                                   case 5:       /* enable blink */
3678                                     compatibility(VT100AVO);
3679                                     term->curr_attr |= ATTR_BLINK;
3680                                     break;
3681                                   case 6:       /* SCO light bkgrd */
3682                                     compatibility(SCOANSI);
3683                                     term->blink_is_real = FALSE;
3684                                     term->curr_attr |= ATTR_BLINK;
3685                                     term_schedule_tblink(term);
3686                                     break;
3687                                   case 7:       /* enable reverse video */
3688                                     term->curr_attr |= ATTR_REVERSE;
3689                                     break;
3690                                   case 10:      /* SCO acs off */
3691                                     compatibility(SCOANSI);
3692                                     if (term->no_remote_charset) break;
3693                                     term->sco_acs = 0; break;
3694                                   case 11:      /* SCO acs on */
3695                                     compatibility(SCOANSI);
3696                                     if (term->no_remote_charset) break;
3697                                     term->sco_acs = 1; break;
3698                                   case 12:      /* SCO acs on, |0x80 */
3699                                     compatibility(SCOANSI);
3700                                     if (term->no_remote_charset) break;
3701                                     term->sco_acs = 2; break;
3702                                   case 22:      /* disable bold */
3703                                     compatibility2(OTHER, VT220);
3704                                     term->curr_attr &= ~ATTR_BOLD;
3705                                     break;
3706                                   case 24:      /* disable underline */
3707                                     compatibility2(OTHER, VT220);
3708                                     term->curr_attr &= ~ATTR_UNDER;
3709                                     break;
3710                                   case 25:      /* disable blink */
3711                                     compatibility2(OTHER, VT220);
3712                                     term->curr_attr &= ~ATTR_BLINK;
3713                                     break;
3714                                   case 27:      /* disable reverse video */
3715                                     compatibility2(OTHER, VT220);
3716                                     term->curr_attr &= ~ATTR_REVERSE;
3717                                     break;
3718                                   case 30:
3719                                   case 31:
3720                                   case 32:
3721                                   case 33:
3722                                   case 34:
3723                                   case 35:
3724                                   case 36:
3725                                   case 37:
3726                                     /* foreground */
3727                                     term->curr_attr &= ~ATTR_FGMASK;
3728                                     term->curr_attr |=
3729                                         (term->esc_args[i] - 30)<<ATTR_FGSHIFT;
3730                                     break;
3731                                   case 90:
3732                                   case 91:
3733                                   case 92:
3734                                   case 93:
3735                                   case 94:
3736                                   case 95:
3737                                   case 96:
3738                                   case 97:
3739                                     /* aixterm-style bright foreground */
3740                                     term->curr_attr &= ~ATTR_FGMASK;
3741                                     term->curr_attr |=
3742                                         ((term->esc_args[i] - 90 + 8)
3743                                          << ATTR_FGSHIFT);
3744                                     break;
3745                                   case 39:      /* default-foreground */
3746                                     term->curr_attr &= ~ATTR_FGMASK;
3747                                     term->curr_attr |= ATTR_DEFFG;
3748                                     break;
3749                                   case 40:
3750                                   case 41:
3751                                   case 42:
3752                                   case 43:
3753                                   case 44:
3754                                   case 45:
3755                                   case 46:
3756                                   case 47:
3757                                     /* background */
3758                                     term->curr_attr &= ~ATTR_BGMASK;
3759                                     term->curr_attr |=
3760                                         (term->esc_args[i] - 40)<<ATTR_BGSHIFT;
3761                                     break;
3762                                   case 100:
3763                                   case 101:
3764                                   case 102:
3765                                   case 103:
3766                                   case 104:
3767                                   case 105:
3768                                   case 106:
3769                                   case 107:
3770                                     /* aixterm-style bright background */
3771                                     term->curr_attr &= ~ATTR_BGMASK;
3772                                     term->curr_attr |=
3773                                         ((term->esc_args[i] - 100 + 8)
3774                                          << ATTR_BGSHIFT);
3775                                     break;
3776                                   case 49:      /* default-background */
3777                                     term->curr_attr &= ~ATTR_BGMASK;
3778                                     term->curr_attr |= ATTR_DEFBG;
3779                                     break;
3780                                   case 38:   /* xterm 256-colour mode */
3781                                     if (i+2 < term->esc_nargs &&
3782                                         term->esc_args[i+1] == 5) {
3783                                         term->curr_attr &= ~ATTR_FGMASK;
3784                                         term->curr_attr |=
3785                                             ((term->esc_args[i+2] & 0xFF)
3786                                              << ATTR_FGSHIFT);
3787                                         i += 2;
3788                                     }
3789                                     break;
3790                                   case 48:   /* xterm 256-colour mode */
3791                                     if (i+2 < term->esc_nargs &&
3792                                         term->esc_args[i+1] == 5) {
3793                                         term->curr_attr &= ~ATTR_BGMASK;
3794                                         term->curr_attr |=
3795                                             ((term->esc_args[i+2] & 0xFF)
3796                                              << ATTR_BGSHIFT);
3797                                         i += 2;
3798                                     }
3799                                     break;
3800                                 }
3801                             }
3802                             set_erase_char(term);
3803                         }
3804                         break;
3805                       case 's':       /* save cursor */
3806                         save_cursor(term, TRUE);
3807                         break;
3808                       case 'u':       /* restore cursor */
3809                         save_cursor(term, FALSE);
3810                         seen_disp_event(term);
3811                         break;
3812                       case 't': /* DECSLPP: set page size - ie window height */
3813                         /*
3814                          * VT340/VT420 sequence DECSLPP, DEC only allows values
3815                          *  24/25/36/48/72/144 other emulators (eg dtterm) use
3816                          * illegal values (eg first arg 1..9) for window changing 
3817                          * and reports.
3818                          */
3819                         if (term->esc_nargs <= 1
3820                             && (term->esc_args[0] < 1 ||
3821                                 term->esc_args[0] >= 24)) {
3822                             compatibility(VT340TEXT);
3823                             if (!term->no_remote_resize)
3824                                 request_resize(term->frontend, term->cols,
3825                                                def(term->esc_args[0], 24));
3826                             deselect(term);
3827                         } else if (term->esc_nargs >= 1 &&
3828                                    term->esc_args[0] >= 1 &&
3829                                    term->esc_args[0] < 24) {
3830                             compatibility(OTHER);
3831
3832                             switch (term->esc_args[0]) {
3833                                 int x, y, len;
3834                                 char buf[80], *p;
3835                               case 1:
3836                                 set_iconic(term->frontend, FALSE);
3837                                 break;
3838                               case 2:
3839                                 set_iconic(term->frontend, TRUE);
3840                                 break;
3841                               case 3:
3842                                 if (term->esc_nargs >= 3) {
3843                                     if (!term->no_remote_resize)
3844                                         move_window(term->frontend,
3845                                                     def(term->esc_args[1], 0),
3846                                                     def(term->esc_args[2], 0));
3847                                 }
3848                                 break;
3849                               case 4:
3850                                 /* We should resize the window to a given
3851                                  * size in pixels here, but currently our
3852                                  * resizing code isn't healthy enough to
3853                                  * manage it. */
3854                                 break;
3855                               case 5:
3856                                 /* move to top */
3857                                 set_zorder(term->frontend, TRUE);
3858                                 break;
3859                               case 6:
3860                                 /* move to bottom */
3861                                 set_zorder(term->frontend, FALSE);
3862                                 break;
3863                               case 7:
3864                                 refresh_window(term->frontend);
3865                                 break;
3866                               case 8:
3867                                 if (term->esc_nargs >= 3) {
3868                                     if (!term->no_remote_resize)
3869                                         request_resize(term->frontend,
3870                                                        def(term->esc_args[2], term->conf_width),
3871                                                        def(term->esc_args[1], term->conf_height));
3872                                 }
3873                                 break;
3874                               case 9:
3875                                 if (term->esc_nargs >= 2)
3876                                     set_zoomed(term->frontend,
3877                                                term->esc_args[1] ?
3878                                                TRUE : FALSE);
3879                                 break;
3880                               case 11:
3881                                 if (term->ldisc)
3882                                     ldisc_send(term->ldisc,
3883                                                is_iconic(term->frontend) ?
3884                                                "\033[2t" : "\033[1t", 4, 0);
3885                                 break;
3886                               case 13:
3887                                 if (term->ldisc) {
3888                                     get_window_pos(term->frontend, &x, &y);
3889                                     len = sprintf(buf, "\033[3;%d;%dt", x, y);
3890                                     ldisc_send(term->ldisc, buf, len, 0);
3891                                 }
3892                                 break;
3893                               case 14:
3894                                 if (term->ldisc) {
3895                                     get_window_pixels(term->frontend, &x, &y);
3896                                     len = sprintf(buf, "\033[4;%d;%dt", y, x);
3897                                     ldisc_send(term->ldisc, buf, len, 0);
3898                                 }
3899                                 break;
3900                               case 18:
3901                                 if (term->ldisc) {
3902                                     len = sprintf(buf, "\033[8;%d;%dt",
3903                                                   term->rows, term->cols);
3904                                     ldisc_send(term->ldisc, buf, len, 0);
3905                                 }
3906                                 break;
3907                               case 19:
3908                                 /*
3909                                  * Hmmm. Strictly speaking we
3910                                  * should return `the size of the
3911                                  * screen in characters', but
3912                                  * that's not easy: (a) window
3913                                  * furniture being what it is it's
3914                                  * hard to compute, and (b) in
3915                                  * resize-font mode maximising the
3916                                  * window wouldn't change the
3917                                  * number of characters. *shrug*. I
3918                                  * think we'll ignore it for the
3919                                  * moment and see if anyone
3920                                  * complains, and then ask them
3921                                  * what they would like it to do.
3922                                  */
3923                                 break;
3924                               case 20:
3925                                 if (term->ldisc &&
3926                                     term->remote_qtitle_action != TITLE_NONE) {
3927                                     if(term->remote_qtitle_action == TITLE_REAL)
3928                                         p = get_window_title(term->frontend, TRUE);
3929                                     else
3930                                         p = EMPTY_WINDOW_TITLE;
3931                                     len = strlen(p);
3932                                     ldisc_send(term->ldisc, "\033]L", 3, 0);
3933                                     ldisc_send(term->ldisc, p, len, 0);
3934                                     ldisc_send(term->ldisc, "\033\\", 2, 0);
3935                                 }
3936                                 break;
3937                               case 21:
3938                                 if (term->ldisc &&
3939                                     term->remote_qtitle_action != TITLE_NONE) {
3940                                     if(term->remote_qtitle_action == TITLE_REAL)
3941                                         p = get_window_title(term->frontend, FALSE);
3942                                     else
3943                                         p = EMPTY_WINDOW_TITLE;
3944                                     len = strlen(p);
3945                                     ldisc_send(term->ldisc, "\033]l", 3, 0);
3946                                     ldisc_send(term->ldisc, p, len, 0);
3947                                     ldisc_send(term->ldisc, "\033\\", 2, 0);
3948                                 }
3949                                 break;
3950                             }
3951                         }
3952                         break;
3953                       case 'S':         /* SU: Scroll up */
3954                         compatibility(SCOANSI);
3955                         scroll(term, term->marg_t, term->marg_b,
3956                                def(term->esc_args[0], 1), TRUE);
3957                         term->wrapnext = FALSE;
3958                         seen_disp_event(term);
3959                         break;
3960                       case 'T':         /* SD: Scroll down */
3961                         compatibility(SCOANSI);
3962                         scroll(term, term->marg_t, term->marg_b,
3963                                -def(term->esc_args[0], 1), TRUE);
3964                         term->wrapnext = FALSE;
3965                         seen_disp_event(term);
3966                         break;
3967                       case ANSI('|', '*'): /* DECSNLS */
3968                         /* 
3969                          * Set number of lines on screen
3970                          * VT420 uses VGA like hardware and can
3971                          * support any size in reasonable range
3972                          * (24..49 AIUI) with no default specified.
3973                          */
3974                         compatibility(VT420);
3975                         if (term->esc_nargs == 1 && term->esc_args[0] > 0) {
3976                             if (!term->no_remote_resize)
3977                                 request_resize(term->frontend, term->cols,
3978                                                def(term->esc_args[0],
3979                                                    term->conf_height));
3980                             deselect(term);
3981                         }
3982                         break;
3983                       case ANSI('|', '$'): /* DECSCPP */
3984                         /*
3985                          * Set number of columns per page
3986                          * Docs imply range is only 80 or 132, but
3987                          * I'll allow any.
3988                          */
3989                         compatibility(VT340TEXT);
3990                         if (term->esc_nargs <= 1) {
3991                             if (!term->no_remote_resize)
3992                                 request_resize(term->frontend,
3993                                                def(term->esc_args[0],
3994                                                    term->conf_width),
3995                                                term->rows);
3996                             deselect(term);
3997                         }
3998                         break;
3999                       case 'X':     /* ECH: write N spaces w/o moving cursor */
4000                         /* XXX VTTEST says this is vt220, vt510 manual
4001                          * says vt100 */
4002                         compatibility(ANSIMIN);
4003                         {
4004                             int n = def(term->esc_args[0], 1);
4005                             pos cursplus;
4006                             int p = term->curs.x;
4007                             termline *cline = scrlineptr(term->curs.y);
4008
4009                             if (n > term->cols - term->curs.x)
4010                                 n = term->cols - term->curs.x;
4011                             cursplus = term->curs;
4012                             cursplus.x += n;
4013                             check_boundary(term, term->curs.x, term->curs.y);
4014                             check_boundary(term, term->curs.x+n, term->curs.y);
4015                             check_selection(term, term->curs, cursplus);
4016                             while (n--)
4017                                 copy_termchar(cline, p++,
4018                                               &term->erase_char);
4019                             seen_disp_event(term);
4020                         }
4021                         break;
4022                       case 'x':       /* DECREQTPARM: report terminal characteristics */
4023                         compatibility(VT100);
4024                         if (term->ldisc) {
4025                             char buf[32];
4026                             int i = def(term->esc_args[0], 0);
4027                             if (i == 0 || i == 1) {
4028                                 strcpy(buf, "\033[2;1;1;112;112;1;0x");
4029                                 buf[2] += i;
4030                                 ldisc_send(term->ldisc, buf, 20, 0);
4031                             }
4032                         }
4033                         break;
4034                       case 'Z':         /* CBT */
4035                         compatibility(OTHER);
4036                         {
4037                             int i = def(term->esc_args[0], 1);
4038                             pos old_curs = term->curs;
4039
4040                             for(;i>0 && term->curs.x>0; i--) {
4041                                 do {
4042                                     term->curs.x--;
4043                                 } while (term->curs.x >0 &&
4044                                          !term->tabs[term->curs.x]);
4045                             }
4046                             check_selection(term, old_curs, term->curs);
4047                         }
4048                         break;
4049                       case ANSI('c', '='):      /* Hide or Show Cursor */
4050                         compatibility(SCOANSI);
4051                         switch(term->esc_args[0]) {
4052                           case 0:  /* hide cursor */
4053                             term->cursor_on = FALSE;
4054                             break;
4055                           case 1:  /* restore cursor */
4056                             term->big_cursor = FALSE;
4057                             term->cursor_on = TRUE;
4058                             break;
4059                           case 2:  /* block cursor */
4060                             term->big_cursor = TRUE;
4061                             term->cursor_on = TRUE;
4062                             break;
4063                         }
4064                         break;
4065                       case ANSI('C', '='):
4066                         /*
4067                          * set cursor start on scanline esc_args[0] and
4068                          * end on scanline esc_args[1].If you set
4069                          * the bottom scan line to a value less than
4070                          * the top scan line, the cursor will disappear.
4071                          */
4072                         compatibility(SCOANSI);
4073                         if (term->esc_nargs >= 2) {
4074                             if (term->esc_args[0] > term->esc_args[1])
4075                                 term->cursor_on = FALSE;
4076                             else
4077                                 term->cursor_on = TRUE;
4078                         }
4079                         break;
4080                       case ANSI('D', '='):
4081                         compatibility(SCOANSI);
4082                         term->blink_is_real = FALSE;
4083                         term_schedule_tblink(term);
4084                         if (term->esc_args[0]>=1)
4085                             term->curr_attr |= ATTR_BLINK;
4086                         else
4087                             term->curr_attr &= ~ATTR_BLINK;
4088                         break;
4089                       case ANSI('E', '='):
4090                         compatibility(SCOANSI);
4091                         term->blink_is_real = (term->esc_args[0] >= 1);
4092                         term_schedule_tblink(term);
4093                         break;
4094                       case ANSI('F', '='):      /* set normal foreground */
4095                         compatibility(SCOANSI);
4096                         if (term->esc_args[0] >= 0 && term->esc_args[0] < 16) {
4097                             long colour =
4098                                 (sco2ansicolour[term->esc_args[0] & 0x7] |
4099                                  (term->esc_args[0] & 0x8)) <<
4100                                 ATTR_FGSHIFT;
4101                             term->curr_attr &= ~ATTR_FGMASK;
4102                             term->curr_attr |= colour;
4103                             term->default_attr &= ~ATTR_FGMASK;
4104                             term->default_attr |= colour;
4105                             set_erase_char(term);
4106                         }
4107                         break;
4108                       case ANSI('G', '='):      /* set normal background */
4109                         compatibility(SCOANSI);
4110                         if (term->esc_args[0] >= 0 && term->esc_args[0] < 16) {
4111                             long colour =
4112                                 (sco2ansicolour[term->esc_args[0] & 0x7] |
4113                                  (term->esc_args[0] & 0x8)) <<
4114                                 ATTR_BGSHIFT;
4115                             term->curr_attr &= ~ATTR_BGMASK;
4116                             term->curr_attr |= colour;
4117                             term->default_attr &= ~ATTR_BGMASK;
4118                             term->default_attr |= colour;
4119                             set_erase_char(term);
4120                         }
4121                         break;
4122                       case ANSI('L', '='):
4123                         compatibility(SCOANSI);
4124                         term->use_bce = (term->esc_args[0] <= 0);
4125                         set_erase_char(term);
4126                         break;
4127                       case ANSI('p', '"'): /* DECSCL: set compat level */
4128                         /*
4129                          * Allow the host to make this emulator a
4130                          * 'perfect' VT102. This first appeared in
4131                          * the VT220, but we do need to get back to
4132                          * PuTTY mode so I won't check it.
4133                          *
4134                          * The arg in 40..42,50 are a PuTTY extension.
4135                          * The 2nd arg, 8bit vs 7bit is not checked.
4136                          *
4137                          * Setting VT102 mode should also change
4138                          * the Fkeys to generate PF* codes as a
4139                          * real VT102 has no Fkeys. The VT220 does
4140                          * this, F11..F13 become ESC,BS,LF other
4141                          * Fkeys send nothing.
4142                          *
4143                          * Note ESC c will NOT change this!
4144                          */
4145
4146                         switch (term->esc_args[0]) {
4147                           case 61:
4148                             term->compatibility_level &= ~TM_VTXXX;
4149                             term->compatibility_level |= TM_VT102;
4150                             break;
4151                           case 62:
4152                             term->compatibility_level &= ~TM_VTXXX;
4153                             term->compatibility_level |= TM_VT220;
4154                             break;
4155
4156                           default:
4157                             if (term->esc_args[0] > 60 &&
4158                                 term->esc_args[0] < 70)
4159                                 term->compatibility_level |= TM_VTXXX;
4160                             break;
4161
4162                           case 40:
4163                             term->compatibility_level &= TM_VTXXX;
4164                             break;
4165                           case 41:
4166                             term->compatibility_level = TM_PUTTY;
4167                             break;
4168                           case 42:
4169                             term->compatibility_level = TM_SCOANSI;
4170                             break;
4171
4172                           case ARG_DEFAULT:
4173                             term->compatibility_level = TM_PUTTY;
4174                             break;
4175                           case 50:
4176                             break;
4177                         }
4178
4179                         /* Change the response to CSI c */
4180                         if (term->esc_args[0] == 50) {
4181                             int i;
4182                             char lbuf[64];
4183                             strcpy(term->id_string, "\033[?");
4184                             for (i = 1; i < term->esc_nargs; i++) {
4185                                 if (i != 1)
4186                                     strcat(term->id_string, ";");
4187                                 sprintf(lbuf, "%d", term->esc_args[i]);
4188                                 strcat(term->id_string, lbuf);
4189                             }
4190                             strcat(term->id_string, "c");
4191                         }
4192 #if 0
4193                         /* Is this a good idea ? 
4194                          * Well we should do a soft reset at this point ...
4195                          */
4196                         if (!has_compat(VT420) && has_compat(VT100)) {
4197                             if (!term->no_remote_resize) {
4198                                 if (term->reset_132)
4199                                     request_resize(132, 24);
4200                                 else
4201                                     request_resize(80, 24);
4202                             }
4203                         }
4204 #endif
4205                         break;
4206                     }
4207                 break;
4208               case SEEN_OSC:
4209                 term->osc_w = FALSE;
4210                 switch (c) {
4211                   case 'P':            /* Linux palette sequence */
4212                     term->termstate = SEEN_OSC_P;
4213                     term->osc_strlen = 0;
4214                     break;
4215                   case 'R':            /* Linux palette reset */
4216                     palette_reset(term->frontend);
4217                     term_invalidate(term);
4218                     term->termstate = TOPLEVEL;
4219                     break;
4220                   case 'W':            /* word-set */
4221                     term->termstate = SEEN_OSC_W;
4222                     term->osc_w = TRUE;
4223                     break;
4224                   case '0':
4225                   case '1':
4226                   case '2':
4227                   case '3':
4228                   case '4':
4229                   case '5':
4230                   case '6':
4231                   case '7':
4232                   case '8':
4233                   case '9':
4234                     term->esc_args[0] = 10 * term->esc_args[0] + c - '0';
4235                     break;
4236                   case 'L':
4237                     /*
4238                      * Grotty hack to support xterm and DECterm title
4239                      * sequences concurrently.
4240                      */
4241                     if (term->esc_args[0] == 2) {
4242                         term->esc_args[0] = 1;
4243                         break;
4244                     }
4245                     /* else fall through */
4246                   default:
4247                     term->termstate = OSC_STRING;
4248                     term->osc_strlen = 0;
4249                 }
4250                 break;
4251               case OSC_STRING:
4252                 /*
4253                  * This OSC stuff is EVIL. It takes just one character to get into
4254                  * sysline mode and it's not initially obvious how to get out.
4255                  * So I've added CR and LF as string aborts.
4256                  * This shouldn't effect compatibility as I believe embedded 
4257                  * control characters are supposed to be interpreted (maybe?) 
4258                  * and they don't display anything useful anyway.
4259                  *
4260                  * -- RDB
4261                  */
4262                 if (c == '\012' || c == '\015') {
4263                     term->termstate = TOPLEVEL;
4264                 } else if (c == 0234 || c == '\007') {
4265                     /*
4266                      * These characters terminate the string; ST and BEL
4267                      * terminate the sequence and trigger instant
4268                      * processing of it, whereas ESC goes back to SEEN_ESC
4269                      * mode unless it is followed by \, in which case it is
4270                      * synonymous with ST in the first place.
4271                      */
4272                     do_osc(term);
4273                     term->termstate = TOPLEVEL;
4274                 } else if (c == '\033')
4275                     term->termstate = OSC_MAYBE_ST;
4276                 else if (term->osc_strlen < OSC_STR_MAX)
4277                     term->osc_string[term->osc_strlen++] = (char)c;
4278                 break;
4279               case SEEN_OSC_P:
4280                 {
4281                     int max = (term->osc_strlen == 0 ? 21 : 15);
4282                     int val;
4283                     if ((int)c >= '0' && (int)c <= '9')
4284                         val = c - '0';
4285                     else if ((int)c >= 'A' && (int)c <= 'A' + max - 10)
4286                         val = c - 'A' + 10;
4287                     else if ((int)c >= 'a' && (int)c <= 'a' + max - 10)
4288                         val = c - 'a' + 10;
4289                     else {
4290                         term->termstate = TOPLEVEL;
4291                         break;
4292                     }
4293                     term->osc_string[term->osc_strlen++] = val;
4294                     if (term->osc_strlen >= 7) {
4295                         palette_set(term->frontend, term->osc_string[0],
4296                                     term->osc_string[1] * 16 + term->osc_string[2],
4297                                     term->osc_string[3] * 16 + term->osc_string[4],
4298                                     term->osc_string[5] * 16 + term->osc_string[6]);
4299                         term_invalidate(term);
4300                         term->termstate = TOPLEVEL;
4301                     }
4302                 }
4303                 break;
4304               case SEEN_OSC_W:
4305                 switch (c) {
4306                   case '0':
4307                   case '1':
4308                   case '2':
4309                   case '3':
4310                   case '4':
4311                   case '5':
4312                   case '6':
4313                   case '7':
4314                   case '8':
4315                   case '9':
4316                     term->esc_args[0] = 10 * term->esc_args[0] + c - '0';
4317                     break;
4318                   default:
4319                     term->termstate = OSC_STRING;
4320                     term->osc_strlen = 0;
4321                 }
4322                 break;
4323               case VT52_ESC:
4324                 term->termstate = TOPLEVEL;
4325                 seen_disp_event(term);
4326                 switch (c) {
4327                   case 'A':
4328                     move(term, term->curs.x, term->curs.y - 1, 1);
4329                     break;
4330                   case 'B':
4331                     move(term, term->curs.x, term->curs.y + 1, 1);
4332                     break;
4333                   case 'C':
4334                     move(term, term->curs.x + 1, term->curs.y, 1);
4335                     break;
4336                   case 'D':
4337                     move(term, term->curs.x - 1, term->curs.y, 1);
4338                     break;
4339                     /*
4340                      * From the VT100 Manual
4341                      * NOTE: The special graphics characters in the VT100
4342                      *       are different from those in the VT52
4343                      *
4344                      * From VT102 manual:
4345                      *       137 _  Blank             - Same
4346                      *       140 `  Reserved          - Humm.
4347                      *       141 a  Solid rectangle   - Similar
4348                      *       142 b  1/                - Top half of fraction for the
4349                      *       143 c  3/                - subscript numbers below.
4350                      *       144 d  5/
4351                      *       145 e  7/
4352                      *       146 f  Degrees           - Same
4353                      *       147 g  Plus or minus     - Same
4354                      *       150 h  Right arrow
4355                      *       151 i  Ellipsis (dots)
4356                      *       152 j  Divide by
4357                      *       153 k  Down arrow
4358                      *       154 l  Bar at scan 0
4359                      *       155 m  Bar at scan 1
4360                      *       156 n  Bar at scan 2
4361                      *       157 o  Bar at scan 3     - Similar
4362                      *       160 p  Bar at scan 4     - Similar
4363                      *       161 q  Bar at scan 5     - Similar
4364                      *       162 r  Bar at scan 6     - Same
4365                      *       163 s  Bar at scan 7     - Similar
4366                      *       164 t  Subscript 0
4367                      *       165 u  Subscript 1
4368                      *       166 v  Subscript 2
4369                      *       167 w  Subscript 3
4370                      *       170 x  Subscript 4
4371                      *       171 y  Subscript 5
4372                      *       172 z  Subscript 6
4373                      *       173 {  Subscript 7
4374                      *       174 |  Subscript 8
4375                      *       175 }  Subscript 9
4376                      *       176 ~  Paragraph
4377                      *
4378                      */
4379                   case 'F':
4380                     term->cset_attr[term->cset = 0] = CSET_LINEDRW;
4381                     break;
4382                   case 'G':
4383                     term->cset_attr[term->cset = 0] = CSET_ASCII;
4384                     break;
4385                   case 'H':
4386                     move(term, 0, 0, 0);
4387                     break;
4388                   case 'I':
4389                     if (term->curs.y == 0)
4390                         scroll(term, 0, term->rows - 1, -1, TRUE);
4391                     else if (term->curs.y > 0)
4392                         term->curs.y--;
4393                     term->wrapnext = FALSE;
4394                     break;
4395                   case 'J':
4396                     erase_lots(term, FALSE, FALSE, TRUE);
4397                     term->disptop = 0;
4398                     break;
4399                   case 'K':
4400                     erase_lots(term, TRUE, FALSE, TRUE);
4401                     break;
4402 #if 0
4403                   case 'V':
4404                     /* XXX Print cursor line */
4405                     break;
4406                   case 'W':
4407                     /* XXX Start controller mode */
4408                     break;
4409                   case 'X':
4410                     /* XXX Stop controller mode */
4411                     break;
4412 #endif
4413                   case 'Y':
4414                     term->termstate = VT52_Y1;
4415                     break;
4416                   case 'Z':
4417                     if (term->ldisc)
4418                         ldisc_send(term->ldisc, "\033/Z", 3, 0);
4419                     break;
4420                   case '=':
4421                     term->app_keypad_keys = TRUE;
4422                     break;
4423                   case '>':
4424                     term->app_keypad_keys = FALSE;
4425                     break;
4426                   case '<':
4427                     /* XXX This should switch to VT100 mode not current or default
4428                      *     VT mode. But this will only have effect in a VT220+
4429                      *     emulation.
4430                      */
4431                     term->vt52_mode = FALSE;
4432                     term->blink_is_real = term->blinktext;
4433                     term_schedule_tblink(term);
4434                     break;
4435 #if 0
4436                   case '^':
4437                     /* XXX Enter auto print mode */
4438                     break;
4439                   case '_':
4440                     /* XXX Exit auto print mode */
4441                     break;
4442                   case ']':
4443                     /* XXX Print screen */
4444                     break;
4445 #endif
4446
4447 #ifdef VT52_PLUS
4448                   case 'E':
4449                     /* compatibility(ATARI) */
4450                     move(term, 0, 0, 0);
4451                     erase_lots(term, FALSE, FALSE, TRUE);
4452                     term->disptop = 0;
4453                     break;
4454                   case 'L':
4455                     /* compatibility(ATARI) */
4456                     if (term->curs.y <= term->marg_b)
4457                         scroll(term, term->curs.y, term->marg_b, -1, FALSE);
4458                     break;
4459                   case 'M':
4460                     /* compatibility(ATARI) */
4461                     if (term->curs.y <= term->marg_b)
4462                         scroll(term, term->curs.y, term->marg_b, 1, TRUE);
4463                     break;
4464                   case 'b':
4465                     /* compatibility(ATARI) */
4466                     term->termstate = VT52_FG;
4467                     break;
4468                   case 'c':
4469                     /* compatibility(ATARI) */
4470                     term->termstate = VT52_BG;
4471                     break;
4472                   case 'd':
4473                     /* compatibility(ATARI) */
4474                     erase_lots(term, FALSE, TRUE, FALSE);
4475                     term->disptop = 0;
4476                     break;
4477                   case 'e':
4478                     /* compatibility(ATARI) */
4479                     term->cursor_on = TRUE;
4480                     break;
4481                   case 'f':
4482                     /* compatibility(ATARI) */
4483                     term->cursor_on = FALSE;
4484                     break;
4485                     /* case 'j': Save cursor position - broken on ST */
4486                     /* case 'k': Restore cursor position */
4487                   case 'l':
4488                     /* compatibility(ATARI) */
4489                     erase_lots(term, TRUE, TRUE, TRUE);
4490                     term->curs.x = 0;
4491                     term->wrapnext = FALSE;
4492                     break;
4493                   case 'o':
4494                     /* compatibility(ATARI) */
4495                     erase_lots(term, TRUE, TRUE, FALSE);
4496                     break;
4497                   case 'p':
4498                     /* compatibility(ATARI) */
4499                     term->curr_attr |= ATTR_REVERSE;
4500                     break;
4501                   case 'q':
4502                     /* compatibility(ATARI) */
4503                     term->curr_attr &= ~ATTR_REVERSE;
4504                     break;
4505                   case 'v':            /* wrap Autowrap on - Wyse style */
4506                     /* compatibility(ATARI) */
4507                     term->wrap = 1;
4508                     break;
4509                   case 'w':            /* Autowrap off */
4510                     /* compatibility(ATARI) */
4511                     term->wrap = 0;
4512                     break;
4513
4514                   case 'R':
4515                     /* compatibility(OTHER) */
4516                     term->vt52_bold = FALSE;
4517                     term->curr_attr = ATTR_DEFAULT;
4518                     set_erase_char(term);
4519                     break;
4520                   case 'S':
4521                     /* compatibility(VI50) */
4522                     term->curr_attr |= ATTR_UNDER;
4523                     break;
4524                   case 'W':
4525                     /* compatibility(VI50) */
4526                     term->curr_attr &= ~ATTR_UNDER;
4527                     break;
4528                   case 'U':
4529                     /* compatibility(VI50) */
4530                     term->vt52_bold = TRUE;
4531                     term->curr_attr |= ATTR_BOLD;
4532                     break;
4533                   case 'T':
4534                     /* compatibility(VI50) */
4535                     term->vt52_bold = FALSE;
4536                     term->curr_attr &= ~ATTR_BOLD;
4537                     break;
4538 #endif
4539                 }
4540                 break;
4541               case VT52_Y1:
4542                 term->termstate = VT52_Y2;
4543                 move(term, term->curs.x, c - ' ', 0);
4544                 break;
4545               case VT52_Y2:
4546                 term->termstate = TOPLEVEL;
4547                 move(term, c - ' ', term->curs.y, 0);
4548                 break;
4549
4550 #ifdef VT52_PLUS
4551               case VT52_FG:
4552                 term->termstate = TOPLEVEL;
4553                 term->curr_attr &= ~ATTR_FGMASK;
4554                 term->curr_attr &= ~ATTR_BOLD;
4555                 term->curr_attr |= (c & 0xF) << ATTR_FGSHIFT;
4556                 set_erase_char(term);
4557                 break;
4558               case VT52_BG:
4559                 term->termstate = TOPLEVEL;
4560                 term->curr_attr &= ~ATTR_BGMASK;
4561                 term->curr_attr &= ~ATTR_BLINK;
4562                 term->curr_attr |= (c & 0xF) << ATTR_BGSHIFT;
4563                 set_erase_char(term);
4564                 break;
4565 #endif
4566               default: break;          /* placate gcc warning about enum use */
4567             }
4568         if (term->selstate != NO_SELECTION) {
4569             pos cursplus = term->curs;
4570             incpos(cursplus);
4571             check_selection(term, term->curs, cursplus);
4572         }
4573     }
4574
4575     term_print_flush(term);
4576     if (term->logflush)
4577         logflush(term->logctx);
4578 }
4579
4580 /*
4581  * To prevent having to run the reasonably tricky bidi algorithm
4582  * too many times, we maintain a cache of the last lineful of data
4583  * fed to the algorithm on each line of the display.
4584  */
4585 static int term_bidi_cache_hit(Terminal *term, int line,
4586                                termchar *lbefore, int width)
4587 {
4588     int i;
4589
4590     if (!term->pre_bidi_cache)
4591         return FALSE;                  /* cache doesn't even exist yet! */
4592
4593     if (line >= term->bidi_cache_size)
4594         return FALSE;                  /* cache doesn't have this many lines */
4595
4596     if (!term->pre_bidi_cache[line].chars)
4597         return FALSE;                  /* cache doesn't contain _this_ line */
4598
4599     if (term->pre_bidi_cache[line].width != width)
4600         return FALSE;                  /* line is wrong width */
4601
4602     for (i = 0; i < width; i++)
4603         if (!termchars_equal(term->pre_bidi_cache[line].chars+i, lbefore+i))
4604             return FALSE;              /* line doesn't match cache */
4605
4606     return TRUE;                       /* it didn't match. */
4607 }
4608
4609 static void term_bidi_cache_store(Terminal *term, int line, termchar *lbefore,
4610                                   termchar *lafter, bidi_char *wcTo,
4611                                   int width, int size)
4612 {
4613     int i;
4614
4615     if (!term->pre_bidi_cache || term->bidi_cache_size <= line) {
4616         int j = term->bidi_cache_size;
4617         term->bidi_cache_size = line+1;
4618         term->pre_bidi_cache = sresize(term->pre_bidi_cache,
4619                                        term->bidi_cache_size,
4620                                        struct bidi_cache_entry);
4621         term->post_bidi_cache = sresize(term->post_bidi_cache,
4622                                         term->bidi_cache_size,
4623                                         struct bidi_cache_entry);
4624         while (j < term->bidi_cache_size) {
4625             term->pre_bidi_cache[j].chars =
4626                 term->post_bidi_cache[j].chars = NULL;
4627             term->pre_bidi_cache[j].width =
4628                 term->post_bidi_cache[j].width = -1;
4629             term->pre_bidi_cache[j].forward =
4630                 term->post_bidi_cache[j].forward = NULL;
4631             term->pre_bidi_cache[j].backward =
4632                 term->post_bidi_cache[j].backward = NULL;
4633             j++;
4634         }
4635     }
4636
4637     sfree(term->pre_bidi_cache[line].chars);
4638     sfree(term->post_bidi_cache[line].chars);
4639     sfree(term->post_bidi_cache[line].forward);
4640     sfree(term->post_bidi_cache[line].backward);
4641
4642     term->pre_bidi_cache[line].width = width;
4643     term->pre_bidi_cache[line].chars = snewn(size, termchar);
4644     term->post_bidi_cache[line].width = width;
4645     term->post_bidi_cache[line].chars = snewn(size, termchar);
4646     term->post_bidi_cache[line].forward = snewn(width, int);
4647     term->post_bidi_cache[line].backward = snewn(width, int);
4648
4649     memcpy(term->pre_bidi_cache[line].chars, lbefore, size * TSIZE);
4650     memcpy(term->post_bidi_cache[line].chars, lafter, size * TSIZE);
4651     memset(term->post_bidi_cache[line].forward, 0, width * sizeof(int));
4652     memset(term->post_bidi_cache[line].backward, 0, width * sizeof(int));
4653
4654     for (i = 0; i < width; i++) {
4655         int p = wcTo[i].index;
4656
4657         assert(0 <= p && p < width);
4658
4659         term->post_bidi_cache[line].backward[i] = p;
4660         term->post_bidi_cache[line].forward[p] = i;
4661     }
4662 }
4663
4664 /*
4665  * Prepare the bidi information for a screen line. Returns the
4666  * transformed list of termchars, or NULL if no transformation at
4667  * all took place (because bidi is disabled). If return was
4668  * non-NULL, auxiliary information such as the forward and reverse
4669  * mappings of permutation position are available in
4670  * term->post_bidi_cache[scr_y].*.
4671  */
4672 static termchar *term_bidi_line(Terminal *term, struct termline *ldata,
4673                                 int scr_y)
4674 {
4675     termchar *lchars;
4676     int it;
4677
4678     /* Do Arabic shaping and bidi. */
4679     if(!term->bidi || !term->arabicshaping) {
4680
4681         if (!term_bidi_cache_hit(term, scr_y, ldata->chars, term->cols)) {
4682
4683             if (term->wcFromTo_size < term->cols) {
4684                 term->wcFromTo_size = term->cols;
4685                 term->wcFrom = sresize(term->wcFrom, term->wcFromTo_size,
4686                                        bidi_char);
4687                 term->wcTo = sresize(term->wcTo, term->wcFromTo_size,
4688                                      bidi_char);
4689             }
4690
4691             for(it=0; it<term->cols ; it++)
4692             {
4693                 unsigned long uc = (ldata->chars[it].chr);
4694
4695                 switch (uc & CSET_MASK) {
4696                   case CSET_LINEDRW:
4697                     if (!term->rawcnp) {
4698                         uc = term->ucsdata->unitab_xterm[uc & 0xFF];
4699                         break;
4700                     }
4701                   case CSET_ASCII:
4702                     uc = term->ucsdata->unitab_line[uc & 0xFF];
4703                     break;
4704                   case CSET_SCOACS:
4705                     uc = term->ucsdata->unitab_scoacs[uc&0xFF];
4706                     break;
4707                 }
4708                 switch (uc & CSET_MASK) {
4709                   case CSET_ACP:
4710                     uc = term->ucsdata->unitab_font[uc & 0xFF];
4711                     break;
4712                   case CSET_OEMCP:
4713                     uc = term->ucsdata->unitab_oemcp[uc & 0xFF];
4714                     break;
4715                 }
4716
4717                 term->wcFrom[it].origwc = term->wcFrom[it].wc =
4718                     (unsigned int)uc;
4719                 term->wcFrom[it].index = it;
4720             }
4721
4722             if(!term->bidi)
4723                 do_bidi(term->wcFrom, term->cols);
4724
4725             /* this is saved iff done from inside the shaping */
4726             if(!term->bidi && term->arabicshaping)
4727                 for(it=0; it<term->cols; it++)
4728                     term->wcTo[it] = term->wcFrom[it];
4729
4730             if(!term->arabicshaping)
4731                 do_shape(term->wcFrom, term->wcTo, term->cols);
4732
4733             if (term->ltemp_size < ldata->size) {
4734                 term->ltemp_size = ldata->size;
4735                 term->ltemp = sresize(term->ltemp, term->ltemp_size,
4736                                       termchar);
4737             }
4738
4739             memcpy(term->ltemp, ldata->chars, ldata->size * TSIZE);
4740
4741             for(it=0; it<term->cols ; it++)
4742             {
4743                 term->ltemp[it] = ldata->chars[term->wcTo[it].index];
4744                 if (term->ltemp[it].cc_next)
4745                     term->ltemp[it].cc_next -=
4746                     it - term->wcTo[it].index;
4747
4748                 if (term->wcTo[it].origwc != term->wcTo[it].wc)
4749                     term->ltemp[it].chr = term->wcTo[it].wc;
4750             }
4751             term_bidi_cache_store(term, scr_y, ldata->chars,
4752                                   term->ltemp, term->wcTo,
4753                                   term->cols, ldata->size);
4754
4755             lchars = term->ltemp;
4756         } else {
4757             lchars = term->post_bidi_cache[scr_y].chars;
4758         }
4759     } else {
4760         lchars = NULL;
4761     }
4762
4763     return lchars;
4764 }
4765
4766 /*
4767  * Given a context, update the window. Out of paranoia, we don't
4768  * allow WM_PAINT responses to do scrolling optimisations.
4769  */
4770 static void do_paint(Terminal *term, Context ctx, int may_optimise)
4771 {
4772     int i, j, our_curs_y, our_curs_x;
4773     int rv, cursor;
4774     pos scrpos;
4775     wchar_t *ch;
4776     int chlen;
4777 #ifdef OPTIMISE_SCROLL
4778     struct scrollregion *sr;
4779 #endif /* OPTIMISE_SCROLL */
4780     termchar *newline;
4781
4782     chlen = 1024;
4783     ch = snewn(chlen, wchar_t);
4784
4785     newline = snewn(term->cols, termchar);
4786
4787     rv = (!term->rvideo ^ !term->in_vbell ? ATTR_REVERSE : 0);
4788
4789     /* Depends on:
4790      * screen array, disptop, scrtop,
4791      * selection, rv, 
4792      * blinkpc, blink_is_real, tblinker, 
4793      * curs.y, curs.x, cblinker, blink_cur, cursor_on, has_focus, wrapnext
4794      */
4795
4796     /* Has the cursor position or type changed ? */
4797     if (term->cursor_on) {
4798         if (term->has_focus) {
4799             if (term->cblinker || !term->blink_cur)
4800                 cursor = TATTR_ACTCURS;
4801             else
4802                 cursor = 0;
4803         } else
4804             cursor = TATTR_PASCURS;
4805         if (term->wrapnext)
4806             cursor |= TATTR_RIGHTCURS;
4807     } else
4808         cursor = 0;
4809     our_curs_y = term->curs.y - term->disptop;
4810     {
4811         /*
4812          * Adjust the cursor position:
4813          *  - for bidi
4814          *  - in the case where it's resting on the right-hand half
4815          *    of a CJK wide character. xterm's behaviour here,
4816          *    which seems adequate to me, is to display the cursor
4817          *    covering the _whole_ character, exactly as if it were
4818          *    one space to the left.
4819          */
4820         termline *ldata = lineptr(term->curs.y);
4821         termchar *lchars;
4822
4823         our_curs_x = term->curs.x;
4824
4825         if ( (lchars = term_bidi_line(term, ldata, our_curs_y)) != NULL) {
4826             our_curs_x = term->post_bidi_cache[our_curs_y].forward[our_curs_x];
4827         } else
4828             lchars = ldata->chars;
4829
4830         if (our_curs_x > 0 &&
4831             lchars[our_curs_x].chr == UCSWIDE)
4832             our_curs_x--;
4833
4834         unlineptr(ldata);
4835     }
4836
4837     /*
4838      * If the cursor is not where it was last time we painted, and
4839      * its previous position is visible on screen, invalidate its
4840      * previous position.
4841      */
4842     if (term->dispcursy >= 0 &&
4843         (term->curstype != cursor ||
4844          term->dispcursy != our_curs_y ||
4845          term->dispcursx != our_curs_x)) {
4846         termchar *dispcurs = term->disptext[term->dispcursy]->chars +
4847             term->dispcursx;
4848
4849         if (term->dispcursx > 0 && dispcurs->chr == UCSWIDE)
4850             dispcurs[-1].attr |= ATTR_INVALID;
4851         if (term->dispcursx < term->cols-1 && dispcurs[1].chr == UCSWIDE)
4852             dispcurs[1].attr |= ATTR_INVALID;
4853         dispcurs->attr |= ATTR_INVALID;
4854
4855         term->curstype = 0;
4856     }
4857     term->dispcursx = term->dispcursy = -1;
4858
4859 #ifdef OPTIMISE_SCROLL
4860     /* Do scrolls */
4861     sr = term->scrollhead;
4862     while (sr) {
4863         struct scrollregion *next = sr->next;
4864         do_scroll(ctx, sr->topline, sr->botline, sr->lines);
4865         sfree(sr);
4866         sr = next;
4867     }
4868     term->scrollhead = term->scrolltail = NULL;
4869 #endif /* OPTIMISE_SCROLL */
4870
4871     /* The normal screen data */
4872     for (i = 0; i < term->rows; i++) {
4873         termline *ldata;
4874         termchar *lchars;
4875         int dirty_line, dirty_run, selected;
4876         unsigned long attr = 0, cset = 0;
4877         int start = 0;
4878         int ccount = 0;
4879         int last_run_dirty = 0;
4880         int laststart, dirtyrect;
4881         int *backward;
4882
4883         scrpos.y = i + term->disptop;
4884         ldata = lineptr(scrpos.y);
4885
4886         /* Do Arabic shaping and bidi. */
4887         lchars = term_bidi_line(term, ldata, i);
4888         if (lchars) {
4889             backward = term->post_bidi_cache[i].backward;
4890         } else {
4891             lchars = ldata->chars;
4892             backward = NULL;
4893         }
4894
4895         /*
4896          * First loop: work along the line deciding what we want
4897          * each character cell to look like.
4898          */
4899         for (j = 0; j < term->cols; j++) {
4900             unsigned long tattr, tchar;
4901             termchar *d = lchars + j;
4902             scrpos.x = backward ? backward[j] : j;
4903
4904             tchar = d->chr;
4905             tattr = d->attr;
4906
4907             if (!term->ansi_colour)
4908                 tattr = (tattr & ~(ATTR_FGMASK | ATTR_BGMASK)) | 
4909                 ATTR_DEFFG | ATTR_DEFBG;
4910
4911             if (!term->xterm_256_colour) {
4912                 int colour;
4913                 colour = (tattr & ATTR_FGMASK) >> ATTR_FGSHIFT;
4914                 if (colour >= 16 && colour < 256)
4915                     tattr = (tattr &~ ATTR_FGMASK) | ATTR_DEFFG;
4916                 colour = (tattr & ATTR_BGMASK) >> ATTR_BGSHIFT;
4917                 if (colour >= 16 && colour < 256)
4918                     tattr = (tattr &~ ATTR_BGMASK) | ATTR_DEFBG;
4919             }
4920
4921             switch (tchar & CSET_MASK) {
4922               case CSET_ASCII:
4923                 tchar = term->ucsdata->unitab_line[tchar & 0xFF];
4924                 break;
4925               case CSET_LINEDRW:
4926                 tchar = term->ucsdata->unitab_xterm[tchar & 0xFF];
4927                 break;
4928               case CSET_SCOACS:  
4929                 tchar = term->ucsdata->unitab_scoacs[tchar&0xFF]; 
4930                 break;
4931             }
4932             if (j < term->cols-1 && d[1].chr == UCSWIDE)
4933                 tattr |= ATTR_WIDE;
4934
4935             /* Video reversing things */
4936             if (term->selstate == DRAGGING || term->selstate == SELECTED) {
4937                 if (term->seltype == LEXICOGRAPHIC)
4938                     selected = (posle(term->selstart, scrpos) &&
4939                                 poslt(scrpos, term->selend));
4940                 else
4941                     selected = (posPle(term->selstart, scrpos) &&
4942                                 posPlt(scrpos, term->selend));
4943             } else
4944                 selected = FALSE;
4945             tattr = (tattr ^ rv
4946                      ^ (selected ? ATTR_REVERSE : 0));
4947
4948             /* 'Real' blinking ? */
4949             if (term->blink_is_real && (tattr & ATTR_BLINK)) {
4950                 if (term->has_focus && term->tblinker) {
4951                     tchar = term->ucsdata->unitab_line[(unsigned char)' '];
4952                 }
4953                 tattr &= ~ATTR_BLINK;
4954             }
4955
4956             /*
4957              * Check the font we'll _probably_ be using to see if 
4958              * the character is wide when we don't want it to be.
4959              */
4960             if (tchar != term->disptext[i]->chars[j].chr ||
4961                 tattr != (term->disptext[i]->chars[j].attr &~
4962                           (ATTR_NARROW | DATTR_MASK))) {
4963                 if ((tattr & ATTR_WIDE) == 0 && char_width(ctx, tchar) == 2)
4964                     tattr |= ATTR_NARROW;
4965             } else if (term->disptext[i]->chars[j].attr & ATTR_NARROW)
4966                 tattr |= ATTR_NARROW;
4967
4968             if (i == our_curs_y && j == our_curs_x) {
4969                 tattr |= cursor;
4970                 term->curstype = cursor;
4971                 term->dispcursx = j;
4972                 term->dispcursy = i;
4973             }
4974
4975             /* FULL-TERMCHAR */
4976             newline[j].attr = tattr;
4977             newline[j].chr = tchar;
4978             /* Combining characters are still read from lchars */
4979             newline[j].cc_next = 0;
4980         }
4981
4982         /*
4983          * Now loop over the line again, noting where things have
4984          * changed.
4985          * 
4986          * During this loop, we keep track of where we last saw
4987          * DATTR_STARTRUN. Any mismatch automatically invalidates
4988          * _all_ of the containing run that was last printed: that
4989          * is, any rectangle that was drawn in one go in the
4990          * previous update should be either left completely alone
4991          * or overwritten in its entirety. This, along with the
4992          * expectation that front ends clip all text runs to their
4993          * bounding rectangle, should solve any possible problems
4994          * with fonts that overflow their character cells.
4995          */
4996         laststart = 0;
4997         dirtyrect = FALSE;
4998         for (j = 0; j < term->cols; j++) {
4999             if (term->disptext[i]->chars[j].attr & DATTR_STARTRUN) {
5000                 laststart = j;
5001                 dirtyrect = FALSE;
5002             }
5003
5004             if (term->disptext[i]->chars[j].chr != newline[j].chr ||
5005                 (term->disptext[i]->chars[j].attr &~ DATTR_MASK)
5006                 != newline[j].attr) {
5007                 int k;
5008
5009                 if (!dirtyrect) {
5010                     for (k = laststart; k < j; k++)
5011                         term->disptext[i]->chars[k].attr |= ATTR_INVALID;
5012
5013                     dirtyrect = TRUE;
5014                 }
5015             }
5016
5017             if (dirtyrect)
5018                 term->disptext[i]->chars[j].attr |= ATTR_INVALID;
5019         }
5020
5021         /*
5022          * Finally, loop once more and actually do the drawing.
5023          */
5024         dirty_run = dirty_line = (ldata->lattr !=
5025                                   term->disptext[i]->lattr);
5026         term->disptext[i]->lattr = ldata->lattr;
5027
5028         for (j = 0; j < term->cols; j++) {
5029             unsigned long tattr, tchar;
5030             int break_run, do_copy;
5031             termchar *d = lchars + j;
5032
5033             tattr = newline[j].attr;
5034             tchar = newline[j].chr;
5035
5036             if ((term->disptext[i]->chars[j].attr ^ tattr) & ATTR_WIDE)
5037                 dirty_line = TRUE;
5038
5039             break_run = ((tattr ^ attr) & term->attr_mask) != 0;
5040
5041 #ifdef USES_VTLINE_HACK
5042             /* Special hack for VT100 Linedraw glyphs */
5043             if ((tchar >= 0x23BA && tchar <= 0x23BD) ||
5044                 (j > 0 && (newline[j-1].chr >= 0x23BA &&
5045                            newline[j-1].chr <= 0x23BD)))
5046                 break_run = TRUE;
5047 #endif
5048
5049             /*
5050              * Separate out sequences of characters that have the
5051              * same CSET, if that CSET is a magic one.
5052              */
5053             if (CSET_OF(tchar) != cset)
5054                 break_run = TRUE;
5055
5056             /*
5057              * Break on both sides of any combined-character cell.
5058              */
5059             if (d->cc_next != 0 ||
5060                 (j > 0 && d[-1].cc_next != 0))
5061                 break_run = TRUE;
5062
5063             if (!term->ucsdata->dbcs_screenfont && !dirty_line) {
5064                 if (term->disptext[i]->chars[j].chr == tchar &&
5065                     (term->disptext[i]->chars[j].attr &~ DATTR_MASK) == tattr)
5066                     break_run = TRUE;
5067                 else if (!dirty_run && ccount == 1)
5068                     break_run = TRUE;
5069             }
5070
5071             if (break_run) {
5072                 if ((dirty_run || last_run_dirty) && ccount > 0) {
5073                     do_text(ctx, start, i, ch, ccount, attr,
5074                             ldata->lattr);
5075                     if (attr & (TATTR_ACTCURS | TATTR_PASCURS))
5076                         do_cursor(ctx, start, i, ch, ccount, attr,
5077                                   ldata->lattr);
5078                 }
5079                 start = j;
5080                 ccount = 0;
5081                 attr = tattr;
5082                 cset = CSET_OF(tchar);
5083                 if (term->ucsdata->dbcs_screenfont)
5084                     last_run_dirty = dirty_run;
5085                 dirty_run = dirty_line;
5086             }
5087
5088             do_copy = FALSE;
5089             if (!termchars_equal_override(&term->disptext[i]->chars[j],
5090                                           d, tchar, tattr)) {
5091                 do_copy = TRUE;
5092                 dirty_run = TRUE;
5093             }
5094
5095             if (ccount+2 > chlen) {
5096                 chlen = ccount + 256;
5097                 ch = sresize(ch, chlen, wchar_t);
5098             }
5099
5100 #ifdef PLATFORM_IS_UTF16
5101             if (tchar > 0x10000 && tchar < 0x110000) {
5102                 ch[ccount++] = (wchar_t) HIGH_SURROGATE_OF(tchar);
5103                 ch[ccount++] = (wchar_t) LOW_SURROGATE_OF(tchar);
5104             } else
5105 #endif /* PLATFORM_IS_UTF16 */
5106             ch[ccount++] = (wchar_t) tchar;
5107
5108             if (d->cc_next) {
5109                 termchar *dd = d;
5110
5111                 while (dd->cc_next) {
5112                     unsigned long schar;
5113
5114                     dd += dd->cc_next;
5115
5116                     schar = dd->chr;
5117                     switch (schar & CSET_MASK) {
5118                       case CSET_ASCII:
5119                         schar = term->ucsdata->unitab_line[schar & 0xFF];
5120                         break;
5121                       case CSET_LINEDRW:
5122                         schar = term->ucsdata->unitab_xterm[schar & 0xFF];
5123                         break;
5124                       case CSET_SCOACS:
5125                         schar = term->ucsdata->unitab_scoacs[schar&0xFF];
5126                         break;
5127                     }
5128
5129                     if (ccount+2 > chlen) {
5130                         chlen = ccount + 256;
5131                         ch = sresize(ch, chlen, wchar_t);
5132                     }
5133
5134 #ifdef PLATFORM_IS_UTF16
5135                     if (schar > 0x10000 && schar < 0x110000) {
5136                         ch[ccount++] = (wchar_t) HIGH_SURROGATE_OF(schar);
5137                         ch[ccount++] = (wchar_t) LOW_SURROGATE_OF(schar);
5138                     } else
5139 #endif /* PLATFORM_IS_UTF16 */
5140                     ch[ccount++] = (wchar_t) schar;
5141                 }
5142
5143                 attr |= TATTR_COMBINING;
5144             }
5145
5146             if (do_copy) {
5147                 copy_termchar(term->disptext[i], j, d);
5148                 term->disptext[i]->chars[j].chr = tchar;
5149                 term->disptext[i]->chars[j].attr = tattr;
5150                 if (start == j)
5151                     term->disptext[i]->chars[j].attr |= DATTR_STARTRUN;
5152             }
5153
5154             /* If it's a wide char step along to the next one. */
5155             if (tattr & ATTR_WIDE) {
5156                 if (++j < term->cols) {
5157                     d++;
5158                     /*
5159                      * By construction above, the cursor should not
5160                      * be on the right-hand half of this character.
5161                      * Ever.
5162                      */
5163                     assert(!(i == our_curs_y && j == our_curs_x));
5164                     if (!termchars_equal(&term->disptext[i]->chars[j], d))
5165                         dirty_run = TRUE;
5166                     copy_termchar(term->disptext[i], j, d);
5167                 }
5168             }
5169         }
5170         if (dirty_run && ccount > 0) {
5171             do_text(ctx, start, i, ch, ccount, attr,
5172                     ldata->lattr);
5173             if (attr & (TATTR_ACTCURS | TATTR_PASCURS))
5174                 do_cursor(ctx, start, i, ch, ccount, attr,
5175                           ldata->lattr);
5176         }
5177
5178         unlineptr(ldata);
5179     }
5180
5181     sfree(newline);
5182     sfree(ch);
5183 }
5184
5185 /*
5186  * Invalidate the whole screen so it will be repainted in full.
5187  */
5188 void term_invalidate(Terminal *term)
5189 {
5190     int i, j;
5191
5192     for (i = 0; i < term->rows; i++)
5193         for (j = 0; j < term->cols; j++)
5194             term->disptext[i]->chars[j].attr |= ATTR_INVALID;
5195
5196     term_schedule_update(term);
5197 }
5198
5199 /*
5200  * Paint the window in response to a WM_PAINT message.
5201  */
5202 void term_paint(Terminal *term, Context ctx,
5203                 int left, int top, int right, int bottom, int immediately)
5204 {
5205     int i, j;
5206     if (left < 0) left = 0;
5207     if (top < 0) top = 0;
5208     if (right >= term->cols) right = term->cols-1;
5209     if (bottom >= term->rows) bottom = term->rows-1;
5210
5211     for (i = top; i <= bottom && i < term->rows; i++) {
5212         if ((term->disptext[i]->lattr & LATTR_MODE) == LATTR_NORM)
5213             for (j = left; j <= right && j < term->cols; j++)
5214                 term->disptext[i]->chars[j].attr |= ATTR_INVALID;
5215         else
5216             for (j = left / 2; j <= right / 2 + 1 && j < term->cols; j++)
5217                 term->disptext[i]->chars[j].attr |= ATTR_INVALID;
5218     }
5219
5220     if (immediately) {
5221         do_paint (term, ctx, FALSE);
5222     } else {
5223         term_schedule_update(term);
5224     }
5225 }
5226
5227 /*
5228  * Attempt to scroll the scrollback. The second parameter gives the
5229  * position we want to scroll to; the first is +1 to denote that
5230  * this position is relative to the beginning of the scrollback, -1
5231  * to denote it is relative to the end, and 0 to denote that it is
5232  * relative to the current position.
5233  */
5234 void term_scroll(Terminal *term, int rel, int where)
5235 {
5236     int sbtop = -sblines(term);
5237 #ifdef OPTIMISE_SCROLL
5238     int olddisptop = term->disptop;
5239     int shift;
5240 #endif /* OPTIMISE_SCROLL */
5241
5242     term->disptop = (rel < 0 ? 0 : rel > 0 ? sbtop : term->disptop) + where;
5243     if (term->disptop < sbtop)
5244         term->disptop = sbtop;
5245     if (term->disptop > 0)
5246         term->disptop = 0;
5247     update_sbar(term);
5248 #ifdef OPTIMISE_SCROLL
5249     shift = (term->disptop - olddisptop);
5250     if (shift < term->rows && shift > -term->rows)
5251         scroll_display(term, 0, term->rows - 1, shift);
5252 #endif /* OPTIMISE_SCROLL */
5253     term_update(term);
5254 }
5255
5256 /*
5257  * Scroll the scrollback to centre it on the beginning or end of the
5258  * current selection, if any.
5259  */
5260 void term_scroll_to_selection(Terminal *term, int which_end)
5261 {
5262     pos target;
5263     int y;
5264     int sbtop = -sblines(term);
5265
5266     if (term->selstate != SELECTED)
5267         return;
5268     if (which_end)
5269         target = term->selend;
5270     else
5271         target = term->selstart;
5272
5273     y = target.y - term->rows/2;
5274     if (y < sbtop)
5275         y = sbtop;
5276     else if (y > 0)
5277         y = 0;
5278     term_scroll(term, -1, y);
5279 }
5280
5281 /*
5282  * Helper routine for clipme(): growing buffer.
5283  */
5284 typedef struct {
5285     int buflen;             /* amount of allocated space in textbuf/attrbuf */
5286     int bufpos;             /* amount of actual data */
5287     wchar_t *textbuf;       /* buffer for copied text */
5288     wchar_t *textptr;       /* = textbuf + bufpos (current insertion point) */
5289     int *attrbuf;           /* buffer for copied attributes */
5290     int *attrptr;           /* = attrbuf + bufpos */
5291 } clip_workbuf;
5292
5293 static void clip_addchar(clip_workbuf *b, wchar_t chr, int attr)
5294 {
5295     if (b->bufpos >= b->buflen) {
5296         b->buflen += 128;
5297         b->textbuf = sresize(b->textbuf, b->buflen, wchar_t);
5298         b->textptr = b->textbuf + b->bufpos;
5299         b->attrbuf = sresize(b->attrbuf, b->buflen, int);
5300         b->attrptr = b->attrbuf + b->bufpos;
5301     }
5302     *b->textptr++ = chr;
5303     *b->attrptr++ = attr;
5304     b->bufpos++;
5305 }
5306
5307 static void clipme(Terminal *term, pos top, pos bottom, int rect, int desel)
5308 {
5309     clip_workbuf buf;
5310     int old_top_x;
5311     int attr;
5312
5313     buf.buflen = 5120;                  
5314     buf.bufpos = 0;
5315     buf.textptr = buf.textbuf = snewn(buf.buflen, wchar_t);
5316     buf.attrptr = buf.attrbuf = snewn(buf.buflen, int);
5317
5318     old_top_x = top.x;                 /* needed for rect==1 */
5319
5320     while (poslt(top, bottom)) {
5321         int nl = FALSE;
5322         termline *ldata = lineptr(top.y);
5323         pos nlpos;
5324
5325         /*
5326          * nlpos will point at the maximum position on this line we
5327          * should copy up to. So we start it at the end of the
5328          * line...
5329          */
5330         nlpos.y = top.y;
5331         nlpos.x = term->cols;
5332
5333         /*
5334          * ... move it backwards if there's unused space at the end
5335          * of the line (and also set `nl' if this is the case,
5336          * because in normal selection mode this means we need a
5337          * newline at the end)...
5338          */
5339         if (!(ldata->lattr & LATTR_WRAPPED)) {
5340             while (nlpos.x &&
5341                    IS_SPACE_CHR(ldata->chars[nlpos.x - 1].chr) &&
5342                    !ldata->chars[nlpos.x - 1].cc_next &&
5343                    poslt(top, nlpos))
5344                 decpos(nlpos);
5345             if (poslt(nlpos, bottom))
5346                 nl = TRUE;
5347         } else if (ldata->lattr & LATTR_WRAPPED2) {
5348             /* Ignore the last char on the line in a WRAPPED2 line. */
5349             decpos(nlpos);
5350         }
5351
5352         /*
5353          * ... and then clip it to the terminal x coordinate if
5354          * we're doing rectangular selection. (In this case we
5355          * still did the above, so that copying e.g. the right-hand
5356          * column from a table doesn't fill with spaces on the
5357          * right.)
5358          */
5359         if (rect) {
5360             if (nlpos.x > bottom.x)
5361                 nlpos.x = bottom.x;
5362             nl = (top.y < bottom.y);
5363         }
5364
5365         while (poslt(top, bottom) && poslt(top, nlpos)) {
5366 #if 0
5367             char cbuf[16], *p;
5368             sprintf(cbuf, "<U+%04x>", (ldata[top.x] & 0xFFFF));
5369 #else
5370             wchar_t cbuf[16], *p;
5371             int c;
5372             int x = top.x;
5373
5374             if (ldata->chars[x].chr == UCSWIDE) {
5375                 top.x++;
5376                 continue;
5377             }
5378
5379             while (1) {
5380                 int uc = ldata->chars[x].chr;
5381                 attr = ldata->chars[x].attr;
5382
5383                 switch (uc & CSET_MASK) {
5384                   case CSET_LINEDRW:
5385                     if (!term->rawcnp) {
5386                         uc = term->ucsdata->unitab_xterm[uc & 0xFF];
5387                         break;
5388                     }
5389                   case CSET_ASCII:
5390                     uc = term->ucsdata->unitab_line[uc & 0xFF];
5391                     break;
5392                   case CSET_SCOACS:
5393                     uc = term->ucsdata->unitab_scoacs[uc&0xFF];
5394                     break;
5395                 }
5396                 switch (uc & CSET_MASK) {
5397                   case CSET_ACP:
5398                     uc = term->ucsdata->unitab_font[uc & 0xFF];
5399                     break;
5400                   case CSET_OEMCP:
5401                     uc = term->ucsdata->unitab_oemcp[uc & 0xFF];
5402                     break;
5403                 }
5404
5405                 c = (uc & ~CSET_MASK);
5406 #ifdef PLATFORM_IS_UTF16
5407                 if (uc > 0x10000 && uc < 0x110000) {
5408                     cbuf[0] = 0xD800 | ((uc - 0x10000) >> 10);
5409                     cbuf[1] = 0xDC00 | ((uc - 0x10000) & 0x3FF);
5410                     cbuf[2] = 0;
5411                 } else
5412 #endif
5413                 {
5414                     cbuf[0] = uc;
5415                     cbuf[1] = 0;
5416                 }
5417
5418                 if (DIRECT_FONT(uc)) {
5419                     if (c >= ' ' && c != 0x7F) {
5420                         char buf[4];
5421                         WCHAR wbuf[4];
5422                         int rv;
5423                         if (is_dbcs_leadbyte(term->ucsdata->font_codepage, (BYTE) c)) {
5424                             buf[0] = c;
5425                             buf[1] = (char) (0xFF & ldata->chars[top.x + 1].chr);
5426                             rv = mb_to_wc(term->ucsdata->font_codepage, 0, buf, 2, wbuf, 4);
5427                             top.x++;
5428                         } else {
5429                             buf[0] = c;
5430                             rv = mb_to_wc(term->ucsdata->font_codepage, 0, buf, 1, wbuf, 4);
5431                         }
5432
5433                         if (rv > 0) {
5434                             memcpy(cbuf, wbuf, rv * sizeof(wchar_t));
5435                             cbuf[rv] = 0;
5436                         }
5437                     }
5438                 }
5439 #endif
5440
5441                 for (p = cbuf; *p; p++)
5442                     clip_addchar(&buf, *p, attr);
5443
5444                 if (ldata->chars[x].cc_next)
5445                     x += ldata->chars[x].cc_next;
5446                 else
5447                     break;
5448             }
5449             top.x++;
5450         }
5451         if (nl) {
5452             int i;
5453             for (i = 0; i < sel_nl_sz; i++)
5454                 clip_addchar(&buf, sel_nl[i], 0);
5455         }
5456         top.y++;
5457         top.x = rect ? old_top_x : 0;
5458
5459         unlineptr(ldata);
5460     }
5461 #if SELECTION_NUL_TERMINATED
5462     clip_addchar(&buf, 0, 0);
5463 #endif
5464     /* Finally, transfer all that to the clipboard. */
5465     write_clip(term->frontend, buf.textbuf, buf.attrbuf, buf.bufpos, desel);
5466     sfree(buf.textbuf);
5467     sfree(buf.attrbuf);
5468 }
5469
5470 void term_copyall(Terminal *term)
5471 {
5472     pos top;
5473     pos bottom;
5474     tree234 *screen = term->screen;
5475     top.y = -sblines(term);
5476     top.x = 0;
5477     bottom.y = find_last_nonempty_line(term, screen);
5478     bottom.x = term->cols;
5479     clipme(term, top, bottom, 0, TRUE);
5480 }
5481
5482 /*
5483  * The wordness array is mainly for deciding the disposition of the
5484  * US-ASCII characters.
5485  */
5486 static int wordtype(Terminal *term, int uc)
5487 {
5488     struct ucsword {
5489         int start, end, ctype;
5490     };
5491     static const struct ucsword ucs_words[] = {
5492         {
5493         128, 160, 0}, {
5494         161, 191, 1}, {
5495         215, 215, 1}, {
5496         247, 247, 1}, {
5497         0x037e, 0x037e, 1},            /* Greek question mark */
5498         {
5499         0x0387, 0x0387, 1},            /* Greek ano teleia */
5500         {
5501         0x055a, 0x055f, 1},            /* Armenian punctuation */
5502         {
5503         0x0589, 0x0589, 1},            /* Armenian full stop */
5504         {
5505         0x0700, 0x070d, 1},            /* Syriac punctuation */
5506         {
5507         0x104a, 0x104f, 1},            /* Myanmar punctuation */
5508         {
5509         0x10fb, 0x10fb, 1},            /* Georgian punctuation */
5510         {
5511         0x1361, 0x1368, 1},            /* Ethiopic punctuation */
5512         {
5513         0x166d, 0x166e, 1},            /* Canadian Syl. punctuation */
5514         {
5515         0x17d4, 0x17dc, 1},            /* Khmer punctuation */
5516         {
5517         0x1800, 0x180a, 1},            /* Mongolian punctuation */
5518         {
5519         0x2000, 0x200a, 0},            /* Various spaces */
5520         {
5521         0x2070, 0x207f, 2},            /* superscript */
5522         {
5523         0x2080, 0x208f, 2},            /* subscript */
5524         {
5525         0x200b, 0x27ff, 1},            /* punctuation and symbols */
5526         {
5527         0x3000, 0x3000, 0},            /* ideographic space */
5528         {
5529         0x3001, 0x3020, 1},            /* ideographic punctuation */
5530         {
5531         0x303f, 0x309f, 3},            /* Hiragana */
5532         {
5533         0x30a0, 0x30ff, 3},            /* Katakana */
5534         {
5535         0x3300, 0x9fff, 3},            /* CJK Ideographs */
5536         {
5537         0xac00, 0xd7a3, 3},            /* Hangul Syllables */
5538         {
5539         0xf900, 0xfaff, 3},            /* CJK Ideographs */
5540         {
5541         0xfe30, 0xfe6b, 1},            /* punctuation forms */
5542         {
5543         0xff00, 0xff0f, 1},            /* half/fullwidth ASCII */
5544         {
5545         0xff1a, 0xff20, 1},            /* half/fullwidth ASCII */
5546         {
5547         0xff3b, 0xff40, 1},            /* half/fullwidth ASCII */
5548         {
5549         0xff5b, 0xff64, 1},            /* half/fullwidth ASCII */
5550         {
5551         0xfff0, 0xffff, 0},            /* half/fullwidth ASCII */
5552         {
5553         0, 0, 0}
5554     };
5555     const struct ucsword *wptr;
5556
5557     switch (uc & CSET_MASK) {
5558       case CSET_LINEDRW:
5559         uc = term->ucsdata->unitab_xterm[uc & 0xFF];
5560         break;
5561       case CSET_ASCII:
5562         uc = term->ucsdata->unitab_line[uc & 0xFF];
5563         break;
5564       case CSET_SCOACS:  
5565         uc = term->ucsdata->unitab_scoacs[uc&0xFF]; 
5566         break;
5567     }
5568     switch (uc & CSET_MASK) {
5569       case CSET_ACP:
5570         uc = term->ucsdata->unitab_font[uc & 0xFF];
5571         break;
5572       case CSET_OEMCP:
5573         uc = term->ucsdata->unitab_oemcp[uc & 0xFF];
5574         break;
5575     }
5576
5577     /* For DBCS fonts I can't do anything useful. Even this will sometimes
5578      * fail as there's such a thing as a double width space. :-(
5579      */
5580     if (term->ucsdata->dbcs_screenfont &&
5581         term->ucsdata->font_codepage == term->ucsdata->line_codepage)
5582         return (uc != ' ');
5583
5584     if (uc < 0x80)
5585         return term->wordness[uc];
5586
5587     for (wptr = ucs_words; wptr->start; wptr++) {
5588         if (uc >= wptr->start && uc <= wptr->end)
5589             return wptr->ctype;
5590     }
5591
5592     return 2;
5593 }
5594
5595 /*
5596  * Spread the selection outwards according to the selection mode.
5597  */
5598 static pos sel_spread_half(Terminal *term, pos p, int dir)
5599 {
5600     termline *ldata;
5601     short wvalue;
5602     int topy = -sblines(term);
5603
5604     ldata = lineptr(p.y);
5605
5606     switch (term->selmode) {
5607       case SM_CHAR:
5608         /*
5609          * In this mode, every character is a separate unit, except
5610          * for runs of spaces at the end of a non-wrapping line.
5611          */
5612         if (!(ldata->lattr & LATTR_WRAPPED)) {
5613             termchar *q = ldata->chars + term->cols;
5614             while (q > ldata->chars &&
5615                    IS_SPACE_CHR(q[-1].chr) && !q[-1].cc_next)
5616                 q--;
5617             if (q == ldata->chars + term->cols)
5618                 q--;
5619             if (p.x >= q - ldata->chars)
5620                 p.x = (dir == -1 ? q - ldata->chars : term->cols - 1);
5621         }
5622         break;
5623       case SM_WORD:
5624         /*
5625          * In this mode, the units are maximal runs of characters
5626          * whose `wordness' has the same value.
5627          */
5628         wvalue = wordtype(term, UCSGET(ldata->chars, p.x));
5629         if (dir == +1) {
5630             while (1) {
5631                 int maxcols = (ldata->lattr & LATTR_WRAPPED2 ?
5632                                term->cols-1 : term->cols);
5633                 if (p.x < maxcols-1) {
5634                     if (wordtype(term, UCSGET(ldata->chars, p.x+1)) == wvalue)
5635                         p.x++;
5636                     else
5637                         break;
5638                 } else {
5639                     if (p.y+1 < term->rows && 
5640                         (ldata->lattr & LATTR_WRAPPED)) {
5641                         termline *ldata2;
5642                         ldata2 = lineptr(p.y+1);
5643                         if (wordtype(term, UCSGET(ldata2->chars, 0))
5644                             == wvalue) {
5645                             p.x = 0;
5646                             p.y++;
5647                             unlineptr(ldata);
5648                             ldata = ldata2;
5649                         } else {
5650                             unlineptr(ldata2);
5651                             break;
5652                         }
5653                     } else
5654                         break;
5655                 }
5656             }
5657         } else {
5658             while (1) {
5659                 if (p.x > 0) {
5660                     if (wordtype(term, UCSGET(ldata->chars, p.x-1)) == wvalue)
5661                         p.x--;
5662                     else
5663                         break;
5664                 } else {
5665                     termline *ldata2;
5666                     int maxcols;
5667                     if (p.y <= topy)
5668                         break;
5669                     ldata2 = lineptr(p.y-1);
5670                     maxcols = (ldata2->lattr & LATTR_WRAPPED2 ?
5671                               term->cols-1 : term->cols);
5672                     if (ldata2->lattr & LATTR_WRAPPED) {
5673                         if (wordtype(term, UCSGET(ldata2->chars, maxcols-1))
5674                             == wvalue) {
5675                             p.x = maxcols-1;
5676                             p.y--;
5677                             unlineptr(ldata);
5678                             ldata = ldata2;
5679                         } else {
5680                             unlineptr(ldata2);
5681                             break;
5682                         }
5683                     } else
5684                         break;
5685                 }
5686             }
5687         }
5688         break;
5689       case SM_LINE:
5690         /*
5691          * In this mode, every line is a unit.
5692          */
5693         p.x = (dir == -1 ? 0 : term->cols - 1);
5694         break;
5695     }
5696
5697     unlineptr(ldata);
5698     return p;
5699 }
5700
5701 static void sel_spread(Terminal *term)
5702 {
5703     if (term->seltype == LEXICOGRAPHIC) {
5704         term->selstart = sel_spread_half(term, term->selstart, -1);
5705         decpos(term->selend);
5706         term->selend = sel_spread_half(term, term->selend, +1);
5707         incpos(term->selend);
5708     }
5709 }
5710
5711 static void term_resume_pasting(Terminal *term)
5712 {
5713     expire_timer_context(&term->paste_timer_ctx);
5714     term_paste_queue(term, FALSE);
5715 }
5716
5717 static void term_paste_timing_callback(void *vterm, unsigned long now)
5718 {
5719     Terminal *term = *(Terminal **)vterm;
5720     term_resume_pasting(term);
5721 }
5722
5723 static void term_paste_queue(Terminal *term, int timed)
5724 {
5725     if (timed) {
5726         /*
5727          * Delay sending the rest of the paste buffer until we have
5728          * seen a newline coming back from the server (indicating that
5729          * it's absorbed the data we've sent so far). As a fallback,
5730          * continue sending anyway after a longish timeout.
5731          *
5732          * We use the pointless structure field term->paste_timer_ctx
5733          * (which is a Terminal *, and we'll make sure it points
5734          * straight back to term) as our timer context, so that it can
5735          * be distinguished from term itself. That way, if we see a
5736          * reason to continue pasting before the timer goes off, we
5737          * can cancel just this timer and none of the other terminal
5738          * timers handling display updates, blinking text and cursor,
5739          * and visual bells.
5740          */
5741         term->paste_timer_ctx = term;
5742         schedule_timer(450, term_paste_timing_callback,
5743                        &term->paste_timer_ctx);
5744     } else {
5745         /*
5746          * Just arrange to call term_paste_callback from the top level
5747          * at the next opportunity.
5748          */
5749         queue_toplevel_callback(term_paste_callback, term);
5750     }
5751 }
5752
5753 static void term_paste_callback(void *vterm)
5754 {
5755     Terminal *term = (Terminal *)vterm;
5756
5757     if (term->paste_len == 0)
5758         return;
5759
5760     while (term->paste_pos < term->paste_len) {
5761         int n = 0;
5762         while (n + term->paste_pos < term->paste_len) {
5763             if (term->paste_buffer[term->paste_pos + n++] == '\015')
5764                 break;
5765         }
5766         if (term->ldisc)
5767             luni_send(term->ldisc, term->paste_buffer + term->paste_pos, n, 0);
5768         term->paste_pos += n;
5769
5770         if (term->paste_pos < term->paste_len) {
5771             term_paste_queue(term, TRUE);
5772             return;
5773         }
5774     }
5775     sfree(term->paste_buffer);
5776     term->paste_buffer = NULL;
5777     term->paste_len = 0;
5778 }
5779
5780 void term_do_paste(Terminal *term)
5781 {
5782     wchar_t *data;
5783     int len;
5784
5785     get_clip(term->frontend, &data, &len);
5786     if (data && len > 0) {
5787         wchar_t *p, *q;
5788
5789         term_seen_key_event(term);     /* pasted data counts */
5790
5791         if (term->paste_buffer)
5792             sfree(term->paste_buffer);
5793         term->paste_pos = term->paste_len = 0;
5794         term->paste_buffer = snewn(len + 12, wchar_t);
5795
5796         if (term->bracketed_paste) {
5797             memcpy(term->paste_buffer, L"\033[200~", 6 * sizeof(wchar_t));
5798             term->paste_len += 6;
5799         }
5800
5801         p = q = data;
5802         while (p < data + len) {
5803             while (p < data + len &&
5804                    !(p <= data + len - sel_nl_sz &&
5805                      !memcmp(p, sel_nl, sizeof(sel_nl))))
5806                 p++;
5807
5808             {
5809                 int i;
5810                 for (i = 0; i < p - q; i++) {
5811                     term->paste_buffer[term->paste_len++] = q[i];
5812                 }
5813             }
5814
5815             if (p <= data + len - sel_nl_sz &&
5816                 !memcmp(p, sel_nl, sizeof(sel_nl))) {
5817                 term->paste_buffer[term->paste_len++] = '\015';
5818                 p += sel_nl_sz;
5819             }
5820             q = p;
5821         }
5822
5823         if (term->bracketed_paste) {
5824             memcpy(term->paste_buffer + term->paste_len,
5825                    L"\033[201~", 6 * sizeof(wchar_t));
5826             term->paste_len += 6;
5827         }
5828
5829         /* Assume a small paste will be OK in one go. */
5830         if (term->paste_len < 256) {
5831             if (term->ldisc)
5832                 luni_send(term->ldisc, term->paste_buffer, term->paste_len, 0);
5833             if (term->paste_buffer)
5834                 sfree(term->paste_buffer);
5835             term->paste_buffer = 0;
5836             term->paste_pos = term->paste_len = 0;
5837         }
5838     }
5839     get_clip(term->frontend, NULL, NULL);
5840
5841     term_paste_queue(term, FALSE);
5842 }
5843
5844 void term_mouse(Terminal *term, Mouse_Button braw, Mouse_Button bcooked,
5845                 Mouse_Action a, int x, int y, int shift, int ctrl, int alt)
5846 {
5847     pos selpoint;
5848     termline *ldata;
5849     int raw_mouse = (term->xterm_mouse &&
5850                      !term->no_mouse_rep &&
5851                      !(term->mouse_override && shift));
5852     int default_seltype;
5853
5854     if (y < 0) {
5855         y = 0;
5856         if (a == MA_DRAG && !raw_mouse)
5857             term_scroll(term, 0, -1);
5858     }
5859     if (y >= term->rows) {
5860         y = term->rows - 1;
5861         if (a == MA_DRAG && !raw_mouse)
5862             term_scroll(term, 0, +1);
5863     }
5864     if (x < 0) {
5865         if (y > 0) {
5866             x = term->cols - 1;
5867             y--;
5868         } else
5869             x = 0;
5870     }
5871     if (x >= term->cols)
5872         x = term->cols - 1;
5873
5874     selpoint.y = y + term->disptop;
5875     ldata = lineptr(selpoint.y);
5876
5877     if ((ldata->lattr & LATTR_MODE) != LATTR_NORM)
5878         x /= 2;
5879
5880     /*
5881      * Transform x through the bidi algorithm to find the _logical_
5882      * click point from the physical one.
5883      */
5884     if (term_bidi_line(term, ldata, y) != NULL) {
5885         x = term->post_bidi_cache[y].backward[x];
5886     }
5887
5888     selpoint.x = x;
5889     unlineptr(ldata);
5890
5891     /*
5892      * If we're in the middle of a selection operation, we ignore raw
5893      * mouse mode until it's done (we must have been not in raw mouse
5894      * mode when it started).
5895      * This makes use of Shift for selection reliable, and avoids the
5896      * host seeing mouse releases for which they never saw corresponding
5897      * presses.
5898      */
5899     if (raw_mouse &&
5900         (term->selstate != ABOUT_TO) && (term->selstate != DRAGGING)) {
5901         int encstate = 0, r, c;
5902         char abuf[32];
5903         int len = 0;
5904
5905         if (term->ldisc) {
5906
5907             switch (braw) {
5908               case MBT_LEFT:
5909                 encstate = 0x00;               /* left button down */
5910                 break;
5911               case MBT_MIDDLE:
5912                 encstate = 0x01;
5913                 break;
5914               case MBT_RIGHT:
5915                 encstate = 0x02;
5916                 break;
5917               case MBT_WHEEL_UP:
5918                 encstate = 0x40;
5919                 break;
5920               case MBT_WHEEL_DOWN:
5921                 encstate = 0x41;
5922                 break;
5923               default: break;          /* placate gcc warning about enum use */
5924             }
5925             switch (a) {
5926               case MA_DRAG:
5927                 if (term->xterm_mouse == 1)
5928                     return;
5929                 encstate += 0x20;
5930                 break;
5931               case MA_RELEASE:
5932                 /* If multiple extensions are enabled, the xterm 1006 is used, so it's okay to check for only that */
5933                 if (!term->xterm_extended_mouse)
5934                     encstate = 0x03;
5935                 term->mouse_is_down = 0;
5936                 break;
5937               case MA_CLICK:
5938                 if (term->mouse_is_down == braw)
5939                     return;
5940                 term->mouse_is_down = braw;
5941                 break;
5942               default: break;          /* placate gcc warning about enum use */
5943             }
5944             if (shift)
5945                 encstate += 0x04;
5946             if (ctrl)
5947                 encstate += 0x10;
5948             r = y + 1;
5949             c = x + 1;
5950
5951             /* Check the extensions in decreasing order of preference. Encoding the release event above assumes that 1006 comes first. */
5952             if (term->xterm_extended_mouse) {
5953                 len = sprintf(abuf, "\033[<%d;%d;%d%c", encstate, c, r, a == MA_RELEASE ? 'm' : 'M');
5954             } else if (term->urxvt_extended_mouse) {
5955                 len = sprintf(abuf, "\033[%d;%d;%dM", encstate + 32, c, r);
5956             } else if (c <= 223 && r <= 223) {
5957                 len = sprintf(abuf, "\033[M%c%c%c", encstate + 32, c + 32, r + 32);
5958             }
5959             ldisc_send(term->ldisc, abuf, len, 0);
5960         }
5961         return;
5962     }
5963
5964     /*
5965      * Set the selection type (rectangular or normal) at the start
5966      * of a selection attempt, from the state of Alt.
5967      */
5968     if (!alt ^ !term->rect_select)
5969         default_seltype = RECTANGULAR;
5970     else
5971         default_seltype = LEXICOGRAPHIC;
5972         
5973     if (term->selstate == NO_SELECTION) {
5974         term->seltype = default_seltype;
5975     }
5976
5977     if (bcooked == MBT_SELECT && a == MA_CLICK) {
5978         deselect(term);
5979         term->selstate = ABOUT_TO;
5980         term->seltype = default_seltype;
5981         term->selanchor = selpoint;
5982         term->selmode = SM_CHAR;
5983     } else if (bcooked == MBT_SELECT && (a == MA_2CLK || a == MA_3CLK)) {
5984         deselect(term);
5985         term->selmode = (a == MA_2CLK ? SM_WORD : SM_LINE);
5986         term->selstate = DRAGGING;
5987         term->selstart = term->selanchor = selpoint;
5988         term->selend = term->selstart;
5989         incpos(term->selend);
5990         sel_spread(term);
5991     } else if ((bcooked == MBT_SELECT && a == MA_DRAG) ||
5992                (bcooked == MBT_EXTEND && a != MA_RELEASE)) {
5993         if (term->selstate == ABOUT_TO && poseq(term->selanchor, selpoint))
5994             return;
5995         if (bcooked == MBT_EXTEND && a != MA_DRAG &&
5996             term->selstate == SELECTED) {
5997             if (term->seltype == LEXICOGRAPHIC) {
5998                 /*
5999                  * For normal selection, we extend by moving
6000                  * whichever end of the current selection is closer
6001                  * to the mouse.
6002                  */
6003                 if (posdiff(selpoint, term->selstart) <
6004                     posdiff(term->selend, term->selstart) / 2) {
6005                     term->selanchor = term->selend;
6006                     decpos(term->selanchor);
6007                 } else {
6008                     term->selanchor = term->selstart;
6009                 }
6010             } else {
6011                 /*
6012                  * For rectangular selection, we have a choice of
6013                  * _four_ places to put selanchor and selpoint: the
6014                  * four corners of the selection.
6015                  */
6016                 if (2*selpoint.x < term->selstart.x + term->selend.x)
6017                     term->selanchor.x = term->selend.x-1;
6018                 else
6019                     term->selanchor.x = term->selstart.x;
6020
6021                 if (2*selpoint.y < term->selstart.y + term->selend.y)
6022                     term->selanchor.y = term->selend.y;
6023                 else
6024                     term->selanchor.y = term->selstart.y;
6025             }
6026             term->selstate = DRAGGING;
6027         }
6028         if (term->selstate != ABOUT_TO && term->selstate != DRAGGING)
6029             term->selanchor = selpoint;
6030         term->selstate = DRAGGING;
6031         if (term->seltype == LEXICOGRAPHIC) {
6032             /*
6033              * For normal selection, we set (selstart,selend) to
6034              * (selpoint,selanchor) in some order.
6035              */
6036             if (poslt(selpoint, term->selanchor)) {
6037                 term->selstart = selpoint;
6038                 term->selend = term->selanchor;
6039                 incpos(term->selend);
6040             } else {
6041                 term->selstart = term->selanchor;
6042                 term->selend = selpoint;
6043                 incpos(term->selend);
6044             }
6045         } else {
6046             /*
6047              * For rectangular selection, we may need to
6048              * interchange x and y coordinates (if the user has
6049              * dragged in the -x and +y directions, or vice versa).
6050              */
6051             term->selstart.x = min(term->selanchor.x, selpoint.x);
6052             term->selend.x = 1+max(term->selanchor.x, selpoint.x);
6053             term->selstart.y = min(term->selanchor.y, selpoint.y);
6054             term->selend.y =   max(term->selanchor.y, selpoint.y);
6055         }
6056         sel_spread(term);
6057     } else if ((bcooked == MBT_SELECT || bcooked == MBT_EXTEND) &&
6058                a == MA_RELEASE) {
6059         if (term->selstate == DRAGGING) {
6060             /*
6061              * We've completed a selection. We now transfer the
6062              * data to the clipboard.
6063              */
6064             clipme(term, term->selstart, term->selend,
6065                    (term->seltype == RECTANGULAR), FALSE);
6066             term->selstate = SELECTED;
6067         } else
6068             term->selstate = NO_SELECTION;
6069     } else if (bcooked == MBT_PASTE
6070                && (a == MA_CLICK
6071 #if MULTICLICK_ONLY_EVENT
6072                    || a == MA_2CLK || a == MA_3CLK
6073 #endif
6074                    )) {
6075         request_paste(term->frontend);
6076     }
6077
6078     /*
6079      * Since terminal output is suppressed during drag-selects, we
6080      * should make sure to write any pending output if one has just
6081      * finished.
6082      */
6083     if (term->selstate != DRAGGING)
6084         term_out(term);
6085     term_update(term);
6086 }
6087
6088 int format_arrow_key(char *buf, Terminal *term, int xkey, int ctrl)
6089 {
6090     char *p = buf;
6091
6092     if (term->vt52_mode)
6093         p += sprintf((char *) p, "\x1B%c", xkey);
6094     else {
6095         int app_flg = (term->app_cursor_keys && !term->no_applic_c);
6096 #if 0
6097         /*
6098          * RDB: VT100 & VT102 manuals both state the app cursor
6099          * keys only work if the app keypad is on.
6100          *
6101          * SGT: That may well be true, but xterm disagrees and so
6102          * does at least one application, so I've #if'ed this out
6103          * and the behaviour is back to PuTTY's original: app
6104          * cursor and app keypad are independently switchable
6105          * modes. If anyone complains about _this_ I'll have to
6106          * put in a configurable option.
6107          */
6108         if (!term->app_keypad_keys)
6109             app_flg = 0;
6110 #endif
6111         /* Useful mapping of Ctrl-arrows */
6112         if (ctrl)
6113             app_flg = !app_flg;
6114
6115         if (app_flg)
6116             p += sprintf((char *) p, "\x1BO%c", xkey);
6117         else
6118             p += sprintf((char *) p, "\x1B[%c", xkey);
6119     }
6120
6121     return p - buf;
6122 }
6123
6124 void term_nopaste(Terminal *term)
6125 {
6126     if (term->paste_len == 0)
6127         return;
6128     expire_timer_context(&term->paste_timer_ctx);
6129     sfree(term->paste_buffer);
6130     term->paste_buffer = NULL;
6131     term->paste_len = 0;
6132 }
6133
6134 static void deselect(Terminal *term)
6135 {
6136     term->selstate = NO_SELECTION;
6137     term->selstart.x = term->selstart.y = term->selend.x = term->selend.y = 0;
6138 }
6139
6140 void term_deselect(Terminal *term)
6141 {
6142     deselect(term);
6143     term_update(term);
6144
6145     /*
6146      * Since terminal output is suppressed during drag-selects, we
6147      * should make sure to write any pending output if one has just
6148      * finished.
6149      */
6150     if (term->selstate != DRAGGING)
6151         term_out(term);
6152 }
6153
6154 int term_ldisc(Terminal *term, int option)
6155 {
6156     if (option == LD_ECHO)
6157         return term->term_echoing;
6158     if (option == LD_EDIT)
6159         return term->term_editing;
6160     return FALSE;
6161 }
6162
6163 int term_data(Terminal *term, int is_stderr, const char *data, int len)
6164 {
6165     bufchain_add(&term->inbuf, data, len);
6166
6167     if (!term->in_term_out) {
6168         term->in_term_out = TRUE;
6169         term_reset_cblink(term);
6170         /*
6171          * During drag-selects, we do not process terminal input,
6172          * because the user will want the screen to hold still to
6173          * be selected.
6174          */
6175         if (term->selstate != DRAGGING)
6176             term_out(term);
6177         term->in_term_out = FALSE;
6178     }
6179
6180     /*
6181      * term_out() always completely empties inbuf. Therefore,
6182      * there's no reason at all to return anything other than zero
6183      * from this function, because there _can't_ be a question of
6184      * the remote side needing to wait until term_out() has cleared
6185      * a backlog.
6186      *
6187      * This is a slightly suboptimal way to deal with SSH-2 - in
6188      * principle, the window mechanism would allow us to continue
6189      * to accept data on forwarded ports and X connections even
6190      * while the terminal processing was going slowly - but we
6191      * can't do the 100% right thing without moving the terminal
6192      * processing into a separate thread, and that might hurt
6193      * portability. So we manage stdout buffering the old SSH-1 way:
6194      * if the terminal processing goes slowly, the whole SSH
6195      * connection stops accepting data until it's ready.
6196      *
6197      * In practice, I can't imagine this causing serious trouble.
6198      */
6199     return 0;
6200 }
6201
6202 /*
6203  * Write untrusted data to the terminal.
6204  * The only control character that should be honoured is \n (which
6205  * will behave as a CRLF).
6206  */
6207 int term_data_untrusted(Terminal *term, const char *data, int len)
6208 {
6209     int i;
6210     /* FIXME: more sophisticated checking? */
6211     for (i = 0; i < len; i++) {
6212         if (data[i] == '\n')
6213             term_data(term, 1, "\r\n", 2);
6214         else if (data[i] & 0x60)
6215             term_data(term, 1, data + i, 1);
6216     }
6217     return 0; /* assumes that term_data() always returns 0 */
6218 }
6219
6220 void term_provide_logctx(Terminal *term, void *logctx)
6221 {
6222     term->logctx = logctx;
6223 }
6224
6225 void term_set_focus(Terminal *term, int has_focus)
6226 {
6227     term->has_focus = has_focus;
6228     term_schedule_cblink(term);
6229 }
6230
6231 /*
6232  * Provide "auto" settings for remote tty modes, suitable for an
6233  * application with a terminal window.
6234  */
6235 char *term_get_ttymode(Terminal *term, const char *mode)
6236 {
6237     char *val = NULL;
6238     if (strcmp(mode, "ERASE") == 0) {
6239         val = term->bksp_is_delete ? "^?" : "^H";
6240     }
6241     /* FIXME: perhaps we should set ONLCR based on lfhascr as well? */
6242     /* FIXME: or ECHO and friends based on local echo state? */
6243     return dupstr(val);
6244 }
6245
6246 struct term_userpass_state {
6247     size_t curr_prompt;
6248     int done_prompt;    /* printed out prompt yet? */
6249     size_t pos;         /* cursor position */
6250 };
6251
6252 /*
6253  * Process some terminal data in the course of username/password
6254  * input.
6255  */
6256 int term_get_userpass_input(Terminal *term, prompts_t *p,
6257                             unsigned char *in, int inlen)
6258 {
6259     struct term_userpass_state *s = (struct term_userpass_state *)p->data;
6260     if (!s) {
6261         /*
6262          * First call. Set some stuff up.
6263          */
6264         p->data = s = snew(struct term_userpass_state);
6265         s->curr_prompt = 0;
6266         s->done_prompt = 0;
6267         /* We only print the `name' caption if we have to... */
6268         if (p->name_reqd && p->name) {
6269             size_t l = strlen(p->name);
6270             term_data_untrusted(term, p->name, l);
6271             if (p->name[l-1] != '\n')
6272                 term_data_untrusted(term, "\n", 1);
6273         }
6274         /* ...but we always print any `instruction'. */
6275         if (p->instruction) {
6276             size_t l = strlen(p->instruction);
6277             term_data_untrusted(term, p->instruction, l);
6278             if (p->instruction[l-1] != '\n')
6279                 term_data_untrusted(term, "\n", 1);
6280         }
6281         /*
6282          * Zero all the results, in case we abort half-way through.
6283          */
6284         {
6285             int i;
6286             for (i = 0; i < (int)p->n_prompts; i++)
6287                 prompt_set_result(p->prompts[i], "");
6288         }
6289     }
6290
6291     while (s->curr_prompt < p->n_prompts) {
6292
6293         prompt_t *pr = p->prompts[s->curr_prompt];
6294         int finished_prompt = 0;
6295
6296         if (!s->done_prompt) {
6297             term_data_untrusted(term, pr->prompt, strlen(pr->prompt));
6298             s->done_prompt = 1;
6299             s->pos = 0;
6300         }
6301
6302         /* Breaking out here ensures that the prompt is printed even
6303          * if we're now waiting for user data. */
6304         if (!in || !inlen) break;
6305
6306         /* FIXME: should we be using local-line-editing code instead? */
6307         while (!finished_prompt && inlen) {
6308             char c = *in++;
6309             inlen--;
6310             switch (c) {
6311               case 10:
6312               case 13:
6313                 term_data(term, 0, "\r\n", 2);
6314                 prompt_ensure_result_size(pr, s->pos + 1);
6315                 pr->result[s->pos] = '\0';
6316                 /* go to next prompt, if any */
6317                 s->curr_prompt++;
6318                 s->done_prompt = 0;
6319                 finished_prompt = 1; /* break out */
6320                 break;
6321               case 8:
6322               case 127:
6323                 if (s->pos > 0) {
6324                     if (pr->echo)
6325                         term_data(term, 0, "\b \b", 3);
6326                     s->pos--;
6327                 }
6328                 break;
6329               case 21:
6330               case 27:
6331                 while (s->pos > 0) {
6332                     if (pr->echo)
6333                         term_data(term, 0, "\b \b", 3);
6334                     s->pos--;
6335                 }
6336                 break;
6337               case 3:
6338               case 4:
6339                 /* Immediate abort. */
6340                 term_data(term, 0, "\r\n", 2);
6341                 sfree(s);
6342                 p->data = NULL;
6343                 return 0; /* user abort */
6344               default:
6345                 /*
6346                  * This simplistic check for printability is disabled
6347                  * when we're doing password input, because some people
6348                  * have control characters in their passwords.
6349                  */
6350                 if (!pr->echo || (c >= ' ' && c <= '~') ||
6351                      ((unsigned char) c >= 160)) {
6352                     prompt_ensure_result_size(pr, s->pos + 1);
6353                     pr->result[s->pos++] = c;
6354                     if (pr->echo)
6355                         term_data(term, 0, &c, 1);
6356                 }
6357                 break;
6358             }
6359         }
6360         
6361     }
6362
6363     if (s->curr_prompt < p->n_prompts) {
6364         return -1; /* more data required */
6365     } else {
6366         sfree(s);
6367         p->data = NULL;
6368         return +1; /* all done */
6369     }
6370 }