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