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