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