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