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