]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - terminal.c
#ifdef out expensive combining-character/scrollback diagnostics (for now).
[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     deselect(term);
1539     swap_screen(term, 0, FALSE, FALSE);
1540
1541     term->alt_t = term->marg_t = 0;
1542     term->alt_b = term->marg_b = newrows - 1;
1543
1544     if (term->rows == -1) {
1545         term->scrollback = newtree234(NULL);
1546         term->screen = newtree234(NULL);
1547         term->tempsblines = 0;
1548         term->rows = 0;
1549     }
1550
1551     /*
1552      * Resize the screen and scrollback. We only need to shift
1553      * lines around within our data structures, because lineptr()
1554      * will take care of resizing each individual line if
1555      * necessary. So:
1556      * 
1557      *  - If the new screen is longer, we shunt lines in from temporary
1558      *    scrollback if possible, otherwise we add new blank lines at
1559      *    the bottom.
1560      *
1561      *  - If the new screen is shorter, we remove any blank lines at
1562      *    the bottom if possible, otherwise shunt lines above the cursor
1563      *    to scrollback if possible, otherwise delete lines below the
1564      *    cursor.
1565      * 
1566      *  - Then, if the new scrollback length is less than the
1567      *    amount of scrollback we actually have, we must throw some
1568      *    away.
1569      */
1570     sblen = count234(term->scrollback);
1571     /* Do this loop to expand the screen if newrows > rows */
1572     assert(term->rows == count234(term->screen));
1573     while (term->rows < newrows) {
1574         if (term->tempsblines > 0) {
1575             unsigned char *cline;
1576             /* Insert a line from the scrollback at the top of the screen. */
1577             assert(sblen >= term->tempsblines);
1578             cline = delpos234(term->scrollback, --sblen);
1579             line = decompressline(cline, NULL);
1580             sfree(cline);
1581             line->temporary = FALSE;   /* reconstituted line is now real */
1582             term->tempsblines -= 1;
1583             addpos234(term->screen, line, 0);
1584             term->curs.y += 1;
1585             term->savecurs.y += 1;
1586         } else {
1587             /* Add a new blank line at the bottom of the screen. */
1588             line = newline(term, newcols, FALSE);
1589             addpos234(term->screen, line, count234(term->screen));
1590         }
1591         term->rows += 1;
1592     }
1593     /* Do this loop to shrink the screen if newrows < rows */
1594     while (term->rows > newrows) {
1595         if (term->curs.y < term->rows - 1) {
1596             /* delete bottom row, unless it contains the cursor */
1597             sfree(delpos234(term->screen, term->rows - 1));
1598         } else {
1599             /* push top row to scrollback */
1600             line = delpos234(term->screen, 0);
1601             addpos234(term->scrollback, compressline(line), sblen++);
1602             freeline(line);
1603             term->tempsblines += 1;
1604             term->curs.y -= 1;
1605             term->savecurs.y -= 1;
1606         }
1607         term->rows -= 1;
1608     }
1609     assert(term->rows == newrows);
1610     assert(count234(term->screen) == newrows);
1611
1612     /* Delete any excess lines from the scrollback. */
1613     while (sblen > newsavelines) {
1614         line = delpos234(term->scrollback, 0);
1615         sfree(line);
1616         sblen--;
1617     }
1618     if (sblen < term->tempsblines)
1619         term->tempsblines = sblen;
1620     assert(count234(term->scrollback) <= newsavelines);
1621     assert(count234(term->scrollback) >= term->tempsblines);
1622     term->disptop = 0;
1623
1624     /* Make a new displayed text buffer. */
1625     newdisp = snewn(newrows, termline *);
1626     for (i = 0; i < newrows; i++) {
1627         newdisp[i] = newline(term, newcols, FALSE);
1628         for (j = 0; j < newcols; j++)
1629             newdisp[i]->chars[j].attr = ATTR_INVALID;
1630     }
1631     if (term->disptext) {
1632         for (i = 0; i < oldrows; i++)
1633             freeline(term->disptext[i]);
1634     }
1635     sfree(term->disptext);
1636     term->disptext = newdisp;
1637     term->dispcursx = term->dispcursy = -1;
1638
1639     /* Make a new alternate screen. */
1640     newalt = newtree234(NULL);
1641     for (i = 0; i < newrows; i++) {
1642         line = newline(term, newcols, TRUE);
1643         addpos234(newalt, line, i);
1644     }
1645     if (term->alt_screen) {
1646         while (NULL != (line = delpos234(term->alt_screen, 0)))
1647             freeline(line);
1648         freetree234(term->alt_screen);
1649     }
1650     term->alt_screen = newalt;
1651     term->alt_sblines = 0;
1652
1653     term->tabs = sresize(term->tabs, newcols, unsigned char);
1654     {
1655         int i;
1656         for (i = (term->cols > 0 ? term->cols : 0); i < newcols; i++)
1657             term->tabs[i] = (i % 8 == 0 ? TRUE : FALSE);
1658     }
1659
1660     /* Check that the cursor positions are still valid. */
1661     if (term->savecurs.y < 0)
1662         term->savecurs.y = 0;
1663     if (term->savecurs.y >= newrows)
1664         term->savecurs.y = newrows - 1;
1665     if (term->curs.y < 0)
1666         term->curs.y = 0;
1667     if (term->curs.y >= newrows)
1668         term->curs.y = newrows - 1;
1669     if (term->curs.x >= newcols)
1670         term->curs.x = newcols - 1;
1671     term->alt_x = term->alt_y = 0;
1672     term->wrapnext = term->alt_wnext = FALSE;
1673
1674     term->rows = newrows;
1675     term->cols = newcols;
1676     term->savelines = newsavelines;
1677
1678     swap_screen(term, save_alt_which, FALSE, FALSE);
1679
1680     update_sbar(term);
1681     term_update(term);
1682     if (term->resize_fn)
1683         term->resize_fn(term->resize_ctx, term->cols, term->rows);
1684 }
1685
1686 /*
1687  * Hand a function and context pointer to the terminal which it can
1688  * use to notify a back end of resizes.
1689  */
1690 void term_provide_resize_fn(Terminal *term,
1691                             void (*resize_fn)(void *, int, int),
1692                             void *resize_ctx)
1693 {
1694     term->resize_fn = resize_fn;
1695     term->resize_ctx = resize_ctx;
1696     if (term->cols > 0 && term->rows > 0)
1697         resize_fn(resize_ctx, term->cols, term->rows);
1698 }
1699
1700 /* Find the bottom line on the screen that has any content.
1701  * If only the top line has content, returns 0.
1702  * If no lines have content, return -1.
1703  */ 
1704 static int find_last_nonempty_line(Terminal * term, tree234 * screen)
1705 {
1706     int i;
1707     for (i = count234(screen) - 1; i >= 0; i--) {
1708         termline *line = index234(screen, i);
1709         int j;
1710         for (j = 0; j < line->cols; j++)
1711             if (!termchars_equal(&line->chars[j], &term->erase_char))
1712                 break;
1713         if (j != line->cols) break;
1714     }
1715     return i;
1716 }
1717
1718 /*
1719  * Swap screens. If `reset' is TRUE and we have been asked to
1720  * switch to the alternate screen, we must bring most of its
1721  * configuration from the main screen and erase the contents of the
1722  * alternate screen completely. (This is even true if we're already
1723  * on it! Blame xterm.)
1724  */
1725 static void swap_screen(Terminal *term, int which, int reset, int keep_cur_pos)
1726 {
1727     int t;
1728     tree234 *ttr;
1729
1730     if (!which)
1731         reset = FALSE;                 /* do no weird resetting if which==0 */
1732
1733     if (which != term->alt_which) {
1734         term->alt_which = which;
1735
1736         ttr = term->alt_screen;
1737         term->alt_screen = term->screen;
1738         term->screen = ttr;
1739         term->alt_sblines = find_last_nonempty_line(term, term->alt_screen) + 1;
1740         t = term->curs.x;
1741         if (!reset && !keep_cur_pos)
1742             term->curs.x = term->alt_x;
1743         term->alt_x = t;
1744         t = term->curs.y;
1745         if (!reset && !keep_cur_pos)
1746             term->curs.y = term->alt_y;
1747         term->alt_y = t;
1748         t = term->marg_t;
1749         if (!reset) term->marg_t = term->alt_t;
1750         term->alt_t = t;
1751         t = term->marg_b;
1752         if (!reset) term->marg_b = term->alt_b;
1753         term->alt_b = t;
1754         t = term->dec_om;
1755         if (!reset) term->dec_om = term->alt_om;
1756         term->alt_om = t;
1757         t = term->wrap;
1758         if (!reset) term->wrap = term->alt_wrap;
1759         term->alt_wrap = t;
1760         t = term->wrapnext;
1761         if (!reset) term->wrapnext = term->alt_wnext;
1762         term->alt_wnext = t;
1763         t = term->insert;
1764         if (!reset) term->insert = term->alt_ins;
1765         term->alt_ins = t;
1766         t = term->cset;
1767         if (!reset) term->cset = term->alt_cset;
1768         term->alt_cset = t;
1769         t = term->utf;
1770         if (!reset) term->utf = term->alt_utf;
1771         term->alt_utf = t;
1772         t = term->sco_acs;
1773         if (!reset) term->sco_acs = term->alt_sco_acs;
1774         term->alt_sco_acs = t;
1775     }
1776
1777     if (reset && term->screen) {
1778         /*
1779          * Yes, this _is_ supposed to honour background-colour-erase.
1780          */
1781         erase_lots(term, FALSE, TRUE, TRUE);
1782     }
1783 }
1784
1785 /*
1786  * Update the scroll bar.
1787  */
1788 static void update_sbar(Terminal *term)
1789 {
1790     int nscroll = sblines(term);
1791     set_sbar(term->frontend, nscroll + term->rows,
1792              nscroll + term->disptop, term->rows);
1793 }
1794
1795 /*
1796  * Check whether the region bounded by the two pointers intersects
1797  * the scroll region, and de-select the on-screen selection if so.
1798  */
1799 static void check_selection(Terminal *term, pos from, pos to)
1800 {
1801     if (poslt(from, term->selend) && poslt(term->selstart, to))
1802         deselect(term);
1803 }
1804
1805 /*
1806  * Scroll the screen. (`lines' is +ve for scrolling forward, -ve
1807  * for backward.) `sb' is TRUE if the scrolling is permitted to
1808  * affect the scrollback buffer.
1809  */
1810 static void scroll(Terminal *term, int topline, int botline, int lines, int sb)
1811 {
1812     termline *line;
1813     int i, seltop, olddisptop, shift;
1814
1815     if (topline != 0 || term->alt_which != 0)
1816         sb = FALSE;
1817
1818     olddisptop = term->disptop;
1819     shift = lines;
1820     if (lines < 0) {
1821         while (lines < 0) {
1822             line = delpos234(term->screen, botline);
1823             resizeline(term, line, term->cols);
1824             for (i = 0; i < term->cols; i++)
1825                 copy_termchar(line, i, &term->erase_char);
1826             line->lattr = LATTR_NORM;
1827             addpos234(term->screen, line, topline);
1828
1829             if (term->selstart.y >= topline && term->selstart.y <= botline) {
1830                 term->selstart.y++;
1831                 if (term->selstart.y > botline) {
1832                     term->selstart.y = botline + 1;
1833                     term->selstart.x = 0;
1834                 }
1835             }
1836             if (term->selend.y >= topline && term->selend.y <= botline) {
1837                 term->selend.y++;
1838                 if (term->selend.y > botline) {
1839                     term->selend.y = botline + 1;
1840                     term->selend.x = 0;
1841                 }
1842             }
1843
1844             lines++;
1845         }
1846     } else {
1847         while (lines > 0) {
1848             line = delpos234(term->screen, topline);
1849 #ifdef TERM_CC_DIAGS
1850             cc_check(line);
1851 #endif
1852             if (sb && term->savelines > 0) {
1853                 int sblen = count234(term->scrollback);
1854                 /*
1855                  * We must add this line to the scrollback. We'll
1856                  * remove a line from the top of the scrollback if
1857                  * the scrollback is full.
1858                  */
1859                 if (sblen == term->savelines) {
1860                     unsigned char *cline;
1861
1862                     sblen--;
1863                     cline = delpos234(term->scrollback, 0);
1864                     sfree(cline);
1865                 } else
1866                     term->tempsblines += 1;
1867
1868                 addpos234(term->scrollback, compressline(line), sblen);
1869
1870                 /* now `line' itself can be reused as the bottom line */
1871
1872                 /*
1873                  * If the user is currently looking at part of the
1874                  * scrollback, and they haven't enabled any options
1875                  * that are going to reset the scrollback as a
1876                  * result of this movement, then the chances are
1877                  * they'd like to keep looking at the same line. So
1878                  * we move their viewpoint at the same rate as the
1879                  * scroll, at least until their viewpoint hits the
1880                  * top end of the scrollback buffer, at which point
1881                  * we don't have the choice any more.
1882                  * 
1883                  * Thanks to Jan Holmen Holsten for the idea and
1884                  * initial implementation.
1885                  */
1886                 if (term->disptop > -term->savelines && term->disptop < 0)
1887                     term->disptop--;
1888             }
1889             resizeline(term, line, term->cols);
1890             for (i = 0; i < term->cols; i++)
1891                 copy_termchar(line, i, &term->erase_char);
1892             line->lattr = LATTR_NORM;
1893             addpos234(term->screen, line, botline);
1894
1895             /*
1896              * If the selection endpoints move into the scrollback,
1897              * we keep them moving until they hit the top. However,
1898              * of course, if the line _hasn't_ moved into the
1899              * scrollback then we don't do this, and cut them off
1900              * at the top of the scroll region.
1901              * 
1902              * This applies to selstart and selend (for an existing
1903              * selection), and also selanchor (for one being
1904              * selected as we speak).
1905              */
1906             seltop = sb ? -term->savelines : topline;
1907
1908             if (term->selstate != NO_SELECTION) {
1909                 if (term->selstart.y >= seltop &&
1910                     term->selstart.y <= botline) {
1911                     term->selstart.y--;
1912                     if (term->selstart.y < seltop) {
1913                         term->selstart.y = seltop;
1914                         term->selstart.x = 0;
1915                     }
1916                 }
1917                 if (term->selend.y >= seltop && term->selend.y <= botline) {
1918                     term->selend.y--;
1919                     if (term->selend.y < seltop) {
1920                         term->selend.y = seltop;
1921                         term->selend.x = 0;
1922                     }
1923                 }
1924                 if (term->selanchor.y >= seltop &&
1925                     term->selanchor.y <= botline) {
1926                     term->selanchor.y--;
1927                     if (term->selanchor.y < seltop) {
1928                         term->selanchor.y = seltop;
1929                         term->selanchor.x = 0;
1930                     }
1931                 }
1932             }
1933
1934             lines--;
1935         }
1936     }
1937 #ifdef OPTIMISE_SCROLL
1938     shift += term->disptop - olddisptop;
1939     if (shift < term->rows && shift > -term->rows && shift != 0)
1940         scroll_display(term, topline, botline, shift);
1941 #endif /* OPTIMISE_SCROLL */
1942 }
1943
1944 #ifdef OPTIMISE_SCROLL
1945 /*
1946  * Add a scroll of a region on the screen into the pending scroll list.
1947  * `lines' is +ve for scrolling forward, -ve for backward.
1948  *
1949  * If the scroll is on the same area as the last scroll in the list,
1950  * merge them.
1951  */
1952 static void save_scroll(Terminal *term, int topline, int botline, int lines)
1953 {
1954     struct scrollregion *newscroll;
1955     if (term->scrolltail &&
1956         term->scrolltail->topline == topline && 
1957         term->scrolltail->botline == botline) {
1958         term->scrolltail->lines += lines;
1959     } else {
1960         newscroll = snew(struct scrollregion);
1961         newscroll->topline = topline;
1962         newscroll->botline = botline;
1963         newscroll->lines = lines;
1964         newscroll->next = NULL;
1965
1966         if (!term->scrollhead)
1967             term->scrollhead = newscroll;
1968         else
1969             term->scrolltail->next = newscroll;
1970         term->scrolltail = newscroll;
1971     }
1972 }
1973
1974 /*
1975  * Scroll the physical display, and our conception of it in disptext.
1976  */
1977 static void scroll_display(Terminal *term, int topline, int botline, int lines)
1978 {
1979     int distance, nlines, i, j;
1980
1981     distance = lines > 0 ? lines : -lines;
1982     nlines = botline - topline + 1 - distance;
1983     if (lines > 0) {
1984         for (i = 0; i < nlines; i++)
1985             for (j = 0; j < term->cols; j++)
1986                 copy_termchar(term->disptext[i], j,
1987                               term->disptext[i+distance]->chars+j);
1988         if (term->dispcursy >= 0 &&
1989             term->dispcursy >= topline + distance &&
1990             term->dispcursy < topline + distance + nlines)
1991             term->dispcursy -= distance;
1992         for (i = 0; i < distance; i++)
1993             for (j = 0; j < term->cols; j++)
1994                 term->disptext[nlines+i]->chars[j].attr |= ATTR_INVALID;
1995     } else {
1996         for (i = nlines; i-- ;)
1997             for (j = 0; j < term->cols; j++)
1998                 copy_termchar(term->disptext[i+distance], j,
1999                               term->disptext[i]->chars+j);
2000         if (term->dispcursy >= 0 &&
2001             term->dispcursy >= topline &&
2002             term->dispcursy < topline + nlines)
2003             term->dispcursy += distance;
2004         for (i = 0; i < distance; i++)
2005             for (j = 0; j < term->cols; j++)
2006                 term->disptext[i]->chars[j].attr |= ATTR_INVALID;
2007     }
2008     save_scroll(term, topline, botline, lines);
2009 }
2010 #endif /* OPTIMISE_SCROLL */
2011
2012 /*
2013  * Move the cursor to a given position, clipping at boundaries. We
2014  * may or may not want to clip at the scroll margin: marg_clip is 0
2015  * not to, 1 to disallow _passing_ the margins, and 2 to disallow
2016  * even _being_ outside the margins.
2017  */
2018 static void move(Terminal *term, int x, int y, int marg_clip)
2019 {
2020     if (x < 0)
2021         x = 0;
2022     if (x >= term->cols)
2023         x = term->cols - 1;
2024     if (marg_clip) {
2025         if ((term->curs.y >= term->marg_t || marg_clip == 2) &&
2026             y < term->marg_t)
2027             y = term->marg_t;
2028         if ((term->curs.y <= term->marg_b || marg_clip == 2) &&
2029             y > term->marg_b)
2030             y = term->marg_b;
2031     }
2032     if (y < 0)
2033         y = 0;
2034     if (y >= term->rows)
2035         y = term->rows - 1;
2036     term->curs.x = x;
2037     term->curs.y = y;
2038     term->wrapnext = FALSE;
2039 }
2040
2041 /*
2042  * Save or restore the cursor and SGR mode.
2043  */
2044 static void save_cursor(Terminal *term, int save)
2045 {
2046     if (save) {
2047         term->savecurs = term->curs;
2048         term->save_attr = term->curr_attr;
2049         term->save_cset = term->cset;
2050         term->save_utf = term->utf;
2051         term->save_wnext = term->wrapnext;
2052         term->save_csattr = term->cset_attr[term->cset];
2053         term->save_sco_acs = term->sco_acs;
2054     } else {
2055         term->curs = term->savecurs;
2056         /* Make sure the window hasn't shrunk since the save */
2057         if (term->curs.x >= term->cols)
2058             term->curs.x = term->cols - 1;
2059         if (term->curs.y >= term->rows)
2060             term->curs.y = term->rows - 1;
2061
2062         term->curr_attr = term->save_attr;
2063         term->cset = term->save_cset;
2064         term->utf = term->save_utf;
2065         term->wrapnext = term->save_wnext;
2066         /*
2067          * wrapnext might reset to False if the x position is no
2068          * longer at the rightmost edge.
2069          */
2070         if (term->wrapnext && term->curs.x < term->cols-1)
2071             term->wrapnext = FALSE;
2072         term->cset_attr[term->cset] = term->save_csattr;
2073         term->sco_acs = term->save_sco_acs;
2074         set_erase_char(term);
2075     }
2076 }
2077
2078 /*
2079  * This function is called before doing _anything_ which affects
2080  * only part of a line of text. It is used to mark the boundary
2081  * between two character positions, and it indicates that some sort
2082  * of effect is going to happen on only one side of that boundary.
2083  * 
2084  * The effect of this function is to check whether a CJK
2085  * double-width character is straddling the boundary, and to remove
2086  * it and replace it with two spaces if so. (Of course, one or
2087  * other of those spaces is then likely to be replaced with
2088  * something else again, as a result of whatever happens next.)
2089  * 
2090  * Also, if the boundary is at the right-hand _edge_ of the screen,
2091  * it implies something deliberate is being done to the rightmost
2092  * column position; hence we must clear LATTR_WRAPPED2.
2093  * 
2094  * The input to the function is the coordinates of the _second_
2095  * character of the pair.
2096  */
2097 static void check_boundary(Terminal *term, int x, int y)
2098 {
2099     termline *ldata;
2100
2101     /* Validate input coordinates, just in case. */
2102     if (x == 0 || x > term->cols)
2103         return;
2104
2105     ldata = scrlineptr(y);
2106     if (x == term->cols) {
2107         ldata->lattr &= ~LATTR_WRAPPED2;
2108     } else {
2109         if (ldata->chars[x].chr == UCSWIDE) {
2110             clear_cc(ldata, x-1);
2111             clear_cc(ldata, x);
2112             ldata->chars[x-1].chr = ' ' | CSET_ASCII;
2113             ldata->chars[x] = ldata->chars[x-1];
2114         }
2115     }
2116 }
2117
2118 /*
2119  * Erase a large portion of the screen: the whole screen, or the
2120  * whole line, or parts thereof.
2121  */
2122 static void erase_lots(Terminal *term,
2123                        int line_only, int from_begin, int to_end)
2124 {
2125     pos start, end;
2126     int erase_lattr;
2127     int erasing_lines_from_top = 0;
2128
2129     if (line_only) {
2130         start.y = term->curs.y;
2131         start.x = 0;
2132         end.y = term->curs.y + 1;
2133         end.x = 0;
2134         erase_lattr = FALSE;
2135     } else {
2136         start.y = 0;
2137         start.x = 0;
2138         end.y = term->rows;
2139         end.x = 0;
2140         erase_lattr = TRUE;
2141     }
2142     if (!from_begin) {
2143         start = term->curs;
2144     }
2145     if (!to_end) {
2146         end = term->curs;
2147         incpos(end);
2148     }
2149     if (!from_begin || !to_end)
2150         check_boundary(term, term->curs.x, term->curs.y);
2151     check_selection(term, start, end);
2152
2153     /* Clear screen also forces a full window redraw, just in case. */
2154     if (start.y == 0 && start.x == 0 && end.y == term->rows)
2155         term_invalidate(term);
2156
2157     /* Lines scrolled away shouldn't be brought back on if the terminal
2158      * resizes. */
2159     if (start.y == 0 && start.x == 0 && end.x == 0 && erase_lattr)
2160         erasing_lines_from_top = 1;
2161
2162     if (term->cfg.erase_to_scrollback && erasing_lines_from_top) {
2163         /* If it's a whole number of lines, starting at the top, and
2164          * we're fully erasing them, erase by scrolling and keep the
2165          * lines in the scrollback. */
2166         int scrolllines = end.y;
2167         if (end.y == term->rows) {
2168             /* Shrink until we find a non-empty row.*/
2169             scrolllines = find_last_nonempty_line(term, term->screen) + 1;
2170         }
2171         if (scrolllines > 0)
2172             scroll(term, 0, scrolllines - 1, scrolllines, TRUE);
2173     } else {
2174         termline *ldata = scrlineptr(start.y);
2175         while (poslt(start, end)) {
2176             if (start.x == term->cols) {
2177                 if (!erase_lattr)
2178                     ldata->lattr &= ~(LATTR_WRAPPED | LATTR_WRAPPED2);
2179                 else
2180                     ldata->lattr = LATTR_NORM;
2181             } else {
2182                 copy_termchar(ldata, start.x, &term->erase_char);
2183             }
2184             if (incpos(start) && start.y < term->rows) {
2185                 ldata = scrlineptr(start.y);
2186             }
2187         }
2188     }
2189
2190     /* After an erase of lines from the top of the screen, we shouldn't
2191      * bring the lines back again if the terminal enlarges (since the user or
2192      * application has explictly thrown them away). */
2193     if (erasing_lines_from_top && !(term->alt_which))
2194         term->tempsblines = 0;
2195 }
2196
2197 /*
2198  * Insert or delete characters within the current line. n is +ve if
2199  * insertion is desired, and -ve for deletion.
2200  */
2201 static void insch(Terminal *term, int n)
2202 {
2203     int dir = (n < 0 ? -1 : +1);
2204     int m, j;
2205     pos cursplus;
2206     termline *ldata;
2207
2208     n = (n < 0 ? -n : n);
2209     if (n > term->cols - term->curs.x)
2210         n = term->cols - term->curs.x;
2211     m = term->cols - term->curs.x - n;
2212     cursplus.y = term->curs.y;
2213     cursplus.x = term->curs.x + n;
2214     check_selection(term, term->curs, cursplus);
2215     check_boundary(term, term->curs.x, term->curs.y);
2216     if (dir < 0)
2217         check_boundary(term, term->curs.x + n, term->curs.y);
2218     ldata = scrlineptr(term->curs.y);
2219     if (dir < 0) {
2220         for (j = 0; j < m; j++)
2221             move_termchar(ldata,
2222                           ldata->chars + term->curs.x + j,
2223                           ldata->chars + term->curs.x + j + n);
2224         while (n--)
2225             copy_termchar(ldata, term->curs.x + m++, &term->erase_char);
2226     } else {
2227         for (j = m; j-- ;)
2228             move_termchar(ldata,
2229                           ldata->chars + term->curs.x + j + n,
2230                           ldata->chars + term->curs.x + j);
2231         while (n--)
2232             copy_termchar(ldata, term->curs.x + n, &term->erase_char);
2233     }
2234 }
2235
2236 /*
2237  * Toggle terminal mode `mode' to state `state'. (`query' indicates
2238  * whether the mode is a DEC private one or a normal one.)
2239  */
2240 static void toggle_mode(Terminal *term, int mode, int query, int state)
2241 {
2242     if (query)
2243         switch (mode) {
2244           case 1:                      /* DECCKM: application cursor keys */
2245             term->app_cursor_keys = state;
2246             break;
2247           case 2:                      /* DECANM: VT52 mode */
2248             term->vt52_mode = !state;
2249             if (term->vt52_mode) {
2250                 term->blink_is_real = FALSE;
2251                 term->vt52_bold = FALSE;
2252             } else {
2253                 term->blink_is_real = term->cfg.blinktext;
2254             }
2255             term_schedule_tblink(term);
2256             break;
2257           case 3:                      /* DECCOLM: 80/132 columns */
2258             deselect(term);
2259             if (!term->cfg.no_remote_resize)
2260                 request_resize(term->frontend, state ? 132 : 80, term->rows);
2261             term->reset_132 = state;
2262             term->alt_t = term->marg_t = 0;
2263             term->alt_b = term->marg_b = term->rows - 1;
2264             move(term, 0, 0, 0);
2265             erase_lots(term, FALSE, TRUE, TRUE);
2266             break;
2267           case 5:                      /* DECSCNM: reverse video */
2268             /*
2269              * Toggle reverse video. If we receive an OFF within the
2270              * visual bell timeout period after an ON, we trigger an
2271              * effective visual bell, so that ESC[?5hESC[?5l will
2272              * always be an actually _visible_ visual bell.
2273              */
2274             if (term->rvideo && !state) {
2275                 /* This is an OFF, so set up a vbell */
2276                 term_schedule_vbell(term, TRUE, term->rvbell_startpoint);
2277             } else if (!term->rvideo && state) {
2278                 /* This is an ON, so we notice the time and save it. */
2279                 term->rvbell_startpoint = GETTICKCOUNT();
2280             }
2281             term->rvideo = state;
2282             seen_disp_event(term);
2283             break;
2284           case 6:                      /* DECOM: DEC origin mode */
2285             term->dec_om = state;
2286             break;
2287           case 7:                      /* DECAWM: auto wrap */
2288             term->wrap = state;
2289             break;
2290           case 8:                      /* DECARM: auto key repeat */
2291             term->repeat_off = !state;
2292             break;
2293           case 10:                     /* DECEDM: set local edit mode */
2294             term->term_editing = state;
2295             if (term->ldisc)           /* cause ldisc to notice changes */
2296                 ldisc_send(term->ldisc, NULL, 0, 0);
2297             break;
2298           case 25:                     /* DECTCEM: enable/disable cursor */
2299             compatibility2(OTHER, VT220);
2300             term->cursor_on = state;
2301             seen_disp_event(term);
2302             break;
2303           case 47:                     /* alternate screen */
2304             compatibility(OTHER);
2305             deselect(term);
2306             swap_screen(term, term->cfg.no_alt_screen ? 0 : state, FALSE, FALSE);
2307             term->disptop = 0;
2308             break;
2309           case 1000:                   /* xterm mouse 1 */
2310             term->xterm_mouse = state ? 1 : 0;
2311             set_raw_mouse_mode(term->frontend, state);
2312             break;
2313           case 1002:                   /* xterm mouse 2 */
2314             term->xterm_mouse = state ? 2 : 0;
2315             set_raw_mouse_mode(term->frontend, state);
2316             break;
2317           case 1047:                   /* alternate screen */
2318             compatibility(OTHER);
2319             deselect(term);
2320             swap_screen(term, term->cfg.no_alt_screen ? 0 : state, TRUE, TRUE);
2321             term->disptop = 0;
2322             break;
2323           case 1048:                   /* save/restore cursor */
2324             if (!term->cfg.no_alt_screen)
2325                 save_cursor(term, state);
2326             if (!state) seen_disp_event(term);
2327             break;
2328           case 1049:                   /* cursor & alternate screen */
2329             if (state && !term->cfg.no_alt_screen)
2330                 save_cursor(term, state);
2331             if (!state) seen_disp_event(term);
2332             compatibility(OTHER);
2333             deselect(term);
2334             swap_screen(term, term->cfg.no_alt_screen ? 0 : state, TRUE, FALSE);
2335             if (!state && !term->cfg.no_alt_screen)
2336                 save_cursor(term, state);
2337             term->disptop = 0;
2338             break;
2339     } else
2340         switch (mode) {
2341           case 4:                      /* IRM: set insert mode */
2342             compatibility(VT102);
2343             term->insert = state;
2344             break;
2345           case 12:                     /* SRM: set echo mode */
2346             term->term_echoing = !state;
2347             if (term->ldisc)           /* cause ldisc to notice changes */
2348                 ldisc_send(term->ldisc, NULL, 0, 0);
2349             break;
2350           case 20:                     /* LNM: Return sends ... */
2351             term->cr_lf_return = state;
2352             break;
2353           case 34:                     /* WYULCURM: Make cursor BIG */
2354             compatibility2(OTHER, VT220);
2355             term->big_cursor = !state;
2356         }
2357 }
2358
2359 /*
2360  * Process an OSC sequence: set window title or icon name.
2361  */
2362 static void do_osc(Terminal *term)
2363 {
2364     if (term->osc_w) {
2365         while (term->osc_strlen--)
2366             term->wordness[(unsigned char)
2367                 term->osc_string[term->osc_strlen]] = term->esc_args[0];
2368     } else {
2369         term->osc_string[term->osc_strlen] = '\0';
2370         switch (term->esc_args[0]) {
2371           case 0:
2372           case 1:
2373             if (!term->cfg.no_remote_wintitle)
2374                 set_icon(term->frontend, term->osc_string);
2375             if (term->esc_args[0] == 1)
2376                 break;
2377             /* fall through: parameter 0 means set both */
2378           case 2:
2379           case 21:
2380             if (!term->cfg.no_remote_wintitle)
2381                 set_title(term->frontend, term->osc_string);
2382             break;
2383         }
2384     }
2385 }
2386
2387 /*
2388  * ANSI printing routines.
2389  */
2390 static void term_print_setup(Terminal *term)
2391 {
2392     bufchain_clear(&term->printer_buf);
2393     term->print_job = printer_start_job(term->cfg.printer);
2394 }
2395 static void term_print_flush(Terminal *term)
2396 {
2397     void *data;
2398     int len;
2399     int size;
2400     while ((size = bufchain_size(&term->printer_buf)) > 5) {
2401         bufchain_prefix(&term->printer_buf, &data, &len);
2402         if (len > size-5)
2403             len = size-5;
2404         printer_job_data(term->print_job, data, len);
2405         bufchain_consume(&term->printer_buf, len);
2406     }
2407 }
2408 static void term_print_finish(Terminal *term)
2409 {
2410     void *data;
2411     int len, size;
2412     char c;
2413
2414     if (!term->printing && !term->only_printing)
2415         return;                        /* we need do nothing */
2416
2417     term_print_flush(term);
2418     while ((size = bufchain_size(&term->printer_buf)) > 0) {
2419         bufchain_prefix(&term->printer_buf, &data, &len);
2420         c = *(char *)data;
2421         if (c == '\033' || c == '\233') {
2422             bufchain_consume(&term->printer_buf, size);
2423             break;
2424         } else {
2425             printer_job_data(term->print_job, &c, 1);
2426             bufchain_consume(&term->printer_buf, 1);
2427         }
2428     }
2429     printer_finish_job(term->print_job);
2430     term->print_job = NULL;
2431     term->printing = term->only_printing = FALSE;
2432 }
2433
2434 /*
2435  * Remove everything currently in `inbuf' and stick it up on the
2436  * in-memory display. There's a big state machine in here to
2437  * process escape sequences...
2438  */
2439 static void term_out(Terminal *term)
2440 {
2441     unsigned long c;
2442     int unget;
2443     unsigned char localbuf[256], *chars;
2444     int nchars = 0;
2445
2446     unget = -1;
2447
2448     chars = NULL;                      /* placate compiler warnings */
2449     while (nchars > 0 || bufchain_size(&term->inbuf) > 0) {
2450         if (unget == -1) {
2451             if (nchars == 0) {
2452                 void *ret;
2453                 bufchain_prefix(&term->inbuf, &ret, &nchars);
2454                 if (nchars > sizeof(localbuf))
2455                     nchars = sizeof(localbuf);
2456                 memcpy(localbuf, ret, nchars);
2457                 bufchain_consume(&term->inbuf, nchars);
2458                 chars = localbuf;
2459                 assert(chars != NULL);
2460             }
2461             c = *chars++;
2462             nchars--;
2463
2464             /*
2465              * Optionally log the session traffic to a file. Useful for
2466              * debugging and possibly also useful for actual logging.
2467              */
2468             if (term->cfg.logtype == LGTYP_DEBUG && term->logctx)
2469                 logtraffic(term->logctx, (unsigned char) c, LGTYP_DEBUG);
2470         } else {
2471             c = unget;
2472             unget = -1;
2473         }
2474
2475         /* Note only VT220+ are 8-bit VT102 is seven bit, it shouldn't even
2476          * be able to display 8-bit characters, but I'll let that go 'cause
2477          * of i18n.
2478          */
2479
2480         /*
2481          * If we're printing, add the character to the printer
2482          * buffer.
2483          */
2484         if (term->printing) {
2485             bufchain_add(&term->printer_buf, &c, 1);
2486
2487             /*
2488              * If we're in print-only mode, we use a much simpler
2489              * state machine designed only to recognise the ESC[4i
2490              * termination sequence.
2491              */
2492             if (term->only_printing) {
2493                 if (c == '\033')
2494                     term->print_state = 1;
2495                 else if (c == (unsigned char)'\233')
2496                     term->print_state = 2;
2497                 else if (c == '[' && term->print_state == 1)
2498                     term->print_state = 2;
2499                 else if (c == '4' && term->print_state == 2)
2500                     term->print_state = 3;
2501                 else if (c == 'i' && term->print_state == 3)
2502                     term->print_state = 4;
2503                 else
2504                     term->print_state = 0;
2505                 if (term->print_state == 4) {
2506                     term_print_finish(term);
2507                 }
2508                 continue;
2509             }
2510         }
2511
2512         /* First see about all those translations. */
2513         if (term->termstate == TOPLEVEL) {
2514             if (in_utf(term))
2515                 switch (term->utf_state) {
2516                   case 0:
2517                     if (c < 0x80) {
2518                         /* UTF-8 must be stateless so we ignore iso2022. */
2519                         if (term->ucsdata->unitab_ctrl[c] != 0xFF) 
2520                              c = term->ucsdata->unitab_ctrl[c];
2521                         else c = ((unsigned char)c) | CSET_ASCII;
2522                         break;
2523                     } else if ((c & 0xe0) == 0xc0) {
2524                         term->utf_size = term->utf_state = 1;
2525                         term->utf_char = (c & 0x1f);
2526                     } else if ((c & 0xf0) == 0xe0) {
2527                         term->utf_size = term->utf_state = 2;
2528                         term->utf_char = (c & 0x0f);
2529                     } else if ((c & 0xf8) == 0xf0) {
2530                         term->utf_size = term->utf_state = 3;
2531                         term->utf_char = (c & 0x07);
2532                     } else if ((c & 0xfc) == 0xf8) {
2533                         term->utf_size = term->utf_state = 4;
2534                         term->utf_char = (c & 0x03);
2535                     } else if ((c & 0xfe) == 0xfc) {
2536                         term->utf_size = term->utf_state = 5;
2537                         term->utf_char = (c & 0x01);
2538                     } else {
2539                         c = UCSERR;
2540                         break;
2541                     }
2542                     continue;
2543                   case 1:
2544                   case 2:
2545                   case 3:
2546                   case 4:
2547                   case 5:
2548                     if ((c & 0xC0) != 0x80) {
2549                         unget = c;
2550                         c = UCSERR;
2551                         term->utf_state = 0;
2552                         break;
2553                     }
2554                     term->utf_char = (term->utf_char << 6) | (c & 0x3f);
2555                     if (--term->utf_state)
2556                         continue;
2557
2558                     c = term->utf_char;
2559
2560                     /* Is somebody trying to be evil! */
2561                     if (c < 0x80 ||
2562                         (c < 0x800 && term->utf_size >= 2) ||
2563                         (c < 0x10000 && term->utf_size >= 3) ||
2564                         (c < 0x200000 && term->utf_size >= 4) ||
2565                         (c < 0x4000000 && term->utf_size >= 5))
2566                         c = UCSERR;
2567
2568                     /* Unicode line separator and paragraph separator are CR-LF */
2569                     if (c == 0x2028 || c == 0x2029)
2570                         c = 0x85;
2571
2572                     /* High controls are probably a Baaad idea too. */
2573                     if (c < 0xA0)
2574                         c = 0xFFFD;
2575
2576                     /* The UTF-16 surrogates are not nice either. */
2577                     /*       The standard give the option of decoding these: 
2578                      *       I don't want to! */
2579                     if (c >= 0xD800 && c < 0xE000)
2580                         c = UCSERR;
2581
2582                     /* ISO 10646 characters now limited to UTF-16 range. */
2583                     if (c > 0x10FFFF)
2584                         c = UCSERR;
2585
2586                     /* This is currently a TagPhobic application.. */
2587                     if (c >= 0xE0000 && c <= 0xE007F)
2588                         continue;
2589
2590                     /* U+FEFF is best seen as a null. */
2591                     if (c == 0xFEFF)
2592                         continue;
2593                     /* But U+FFFE is an error. */
2594                     if (c == 0xFFFE || c == 0xFFFF)
2595                         c = UCSERR;
2596
2597                     break;
2598             }
2599             /* Are we in the nasty ACS mode? Note: no sco in utf mode. */
2600             else if(term->sco_acs && 
2601                     (c!='\033' && c!='\012' && c!='\015' && c!='\b'))
2602             {
2603                if (term->sco_acs == 2) c |= 0x80;
2604                c |= CSET_SCOACS;
2605             } else {
2606                 switch (term->cset_attr[term->cset]) {
2607                     /* 
2608                      * Linedraw characters are different from 'ESC ( B'
2609                      * only for a small range. For ones outside that
2610                      * range, make sure we use the same font as well as
2611                      * the same encoding.
2612                      */
2613                   case CSET_LINEDRW:
2614                     if (term->ucsdata->unitab_ctrl[c] != 0xFF)
2615                         c = term->ucsdata->unitab_ctrl[c];
2616                     else
2617                         c = ((unsigned char) c) | CSET_LINEDRW;
2618                     break;
2619
2620                   case CSET_GBCHR:
2621                     /* If UK-ASCII, make the '#' a LineDraw Pound */
2622                     if (c == '#') {
2623                         c = '}' | CSET_LINEDRW;
2624                         break;
2625                     }
2626                   /*FALLTHROUGH*/ case CSET_ASCII:
2627                     if (term->ucsdata->unitab_ctrl[c] != 0xFF)
2628                         c = term->ucsdata->unitab_ctrl[c];
2629                     else
2630                         c = ((unsigned char) c) | CSET_ASCII;
2631                     break;
2632                 case CSET_SCOACS:
2633                     if (c>=' ') c = ((unsigned char)c) | CSET_SCOACS;
2634                     break;
2635                 }
2636             }
2637         }
2638
2639         /*
2640          * How about C1 controls? 
2641          * Explicitly ignore SCI (0x9a), which we don't translate to DECID.
2642          */
2643         if ((c & -32) == 0x80 && term->termstate < DO_CTRLS &&
2644             !term->vt52_mode && has_compat(VT220)) {
2645             if (c == 0x9a)
2646                 c = 0;
2647             else {
2648                 term->termstate = SEEN_ESC;
2649                 term->esc_query = FALSE;
2650                 c = '@' + (c & 0x1F);
2651             }
2652         }
2653
2654         /* Or the GL control. */
2655         if (c == '\177' && term->termstate < DO_CTRLS && has_compat(OTHER)) {
2656             if (term->curs.x && !term->wrapnext)
2657                 term->curs.x--;
2658             term->wrapnext = FALSE;
2659             /* destructive backspace might be disabled */
2660             if (!term->cfg.no_dbackspace) {
2661                 check_boundary(term, term->curs.x, term->curs.y);
2662                 check_boundary(term, term->curs.x+1, term->curs.y);
2663                 copy_termchar(scrlineptr(term->curs.y),
2664                               term->curs.x, &term->erase_char);
2665             }
2666         } else
2667             /* Or normal C0 controls. */
2668         if ((c & ~0x1F) == 0 && term->termstate < DO_CTRLS) {
2669             switch (c) {
2670               case '\005':             /* ENQ: terminal type query */
2671                 /* 
2672                  * Strictly speaking this is VT100 but a VT100 defaults to
2673                  * no response. Other terminals respond at their option.
2674                  *
2675                  * Don't put a CR in the default string as this tends to
2676                  * upset some weird software.
2677                  */
2678                 compatibility(ANSIMIN);
2679                 if (term->ldisc) {
2680                     char abuf[256], *s, *d;
2681                     int state = 0;
2682                     for (s = term->cfg.answerback, d = abuf; *s; s++) {
2683                         if (state) {
2684                             if (*s >= 'a' && *s <= 'z')
2685                                 *d++ = (*s - ('a' - 1));
2686                             else if ((*s >= '@' && *s <= '_') ||
2687                                      *s == '?' || (*s & 0x80))
2688                                 *d++ = ('@' ^ *s);
2689                             else if (*s == '~')
2690                                 *d++ = '^';
2691                             state = 0;
2692                         } else if (*s == '^') {
2693                             state = 1;
2694                         } else
2695                             *d++ = *s;
2696                     }
2697                     lpage_send(term->ldisc, DEFAULT_CODEPAGE,
2698                                abuf, d - abuf, 0);
2699                 }
2700                 break;
2701               case '\007':            /* BEL: Bell */
2702                 {
2703                     struct beeptime *newbeep;
2704                     unsigned long ticks;
2705
2706                     ticks = GETTICKCOUNT();
2707
2708                     if (!term->beep_overloaded) {
2709                         newbeep = snew(struct beeptime);
2710                         newbeep->ticks = ticks;
2711                         newbeep->next = NULL;
2712                         if (!term->beephead)
2713                             term->beephead = newbeep;
2714                         else
2715                             term->beeptail->next = newbeep;
2716                         term->beeptail = newbeep;
2717                         term->nbeeps++;
2718                     }
2719
2720                     /*
2721                      * Throw out any beeps that happened more than
2722                      * t seconds ago.
2723                      */
2724                     while (term->beephead &&
2725                            term->beephead->ticks < ticks - term->cfg.bellovl_t) {
2726                         struct beeptime *tmp = term->beephead;
2727                         term->beephead = tmp->next;
2728                         sfree(tmp);
2729                         if (!term->beephead)
2730                             term->beeptail = NULL;
2731                         term->nbeeps--;
2732                     }
2733
2734                     if (term->cfg.bellovl && term->beep_overloaded &&
2735                         ticks - term->lastbeep >= (unsigned)term->cfg.bellovl_s) {
2736                         /*
2737                          * If we're currently overloaded and the
2738                          * last beep was more than s seconds ago,
2739                          * leave overload mode.
2740                          */
2741                         term->beep_overloaded = FALSE;
2742                     } else if (term->cfg.bellovl && !term->beep_overloaded &&
2743                                term->nbeeps >= term->cfg.bellovl_n) {
2744                         /*
2745                          * Now, if we have n or more beeps
2746                          * remaining in the queue, go into overload
2747                          * mode.
2748                          */
2749                         term->beep_overloaded = TRUE;
2750                     }
2751                     term->lastbeep = ticks;
2752
2753                     /*
2754                      * Perform an actual beep if we're not overloaded.
2755                      */
2756                     if (!term->cfg.bellovl || !term->beep_overloaded) {
2757                         beep(term->frontend, term->cfg.beep);
2758
2759                         if (term->cfg.beep == BELL_VISUAL) {
2760                             term_schedule_vbell(term, FALSE, 0);
2761                         }
2762                     }
2763                     seen_disp_event(term);
2764                 }
2765                 break;
2766               case '\b':              /* BS: Back space */
2767                 if (term->curs.x == 0 &&
2768                     (term->curs.y == 0 || term->wrap == 0))
2769                     /* do nothing */ ;
2770                 else if (term->curs.x == 0 && term->curs.y > 0)
2771                     term->curs.x = term->cols - 1, term->curs.y--;
2772                 else if (term->wrapnext)
2773                     term->wrapnext = FALSE;
2774                 else
2775                     term->curs.x--;
2776                 seen_disp_event(term);
2777                 break;
2778               case '\016':            /* LS1: Locking-shift one */
2779                 compatibility(VT100);
2780                 term->cset = 1;
2781                 break;
2782               case '\017':            /* LS0: Locking-shift zero */
2783                 compatibility(VT100);
2784                 term->cset = 0;
2785                 break;
2786               case '\033':            /* ESC: Escape */
2787                 if (term->vt52_mode)
2788                     term->termstate = VT52_ESC;
2789                 else {
2790                     compatibility(ANSIMIN);
2791                     term->termstate = SEEN_ESC;
2792                     term->esc_query = FALSE;
2793                 }
2794                 break;
2795               case '\015':            /* CR: Carriage return */
2796                 term->curs.x = 0;
2797                 term->wrapnext = FALSE;
2798                 seen_disp_event(term);
2799                 term->paste_hold = 0;
2800                 if (term->logctx)
2801                     logtraffic(term->logctx, (unsigned char) c, LGTYP_ASCII);
2802                 break;
2803               case '\014':            /* FF: Form feed */
2804                 if (has_compat(SCOANSI)) {
2805                     move(term, 0, 0, 0);
2806                     erase_lots(term, FALSE, FALSE, TRUE);
2807                     term->disptop = 0;
2808                     term->wrapnext = FALSE;
2809                     seen_disp_event(term);
2810                     break;
2811                 }
2812               case '\013':            /* VT: Line tabulation */
2813                 compatibility(VT100);
2814               case '\012':            /* LF: Line feed */
2815                 if (term->curs.y == term->marg_b)
2816                     scroll(term, term->marg_t, term->marg_b, 1, TRUE);
2817                 else if (term->curs.y < term->rows - 1)
2818                     term->curs.y++;
2819                 if (term->cfg.lfhascr)
2820                     term->curs.x = 0;
2821                 term->wrapnext = FALSE;
2822                 seen_disp_event(term);
2823                 term->paste_hold = 0;
2824                 if (term->logctx)
2825                     logtraffic(term->logctx, (unsigned char) c, LGTYP_ASCII);
2826                 break;
2827               case '\t':              /* HT: Character tabulation */
2828                 {
2829                     pos old_curs = term->curs;
2830                     termline *ldata = scrlineptr(term->curs.y);
2831
2832                     do {
2833                         term->curs.x++;
2834                     } while (term->curs.x < term->cols - 1 &&
2835                              !term->tabs[term->curs.x]);
2836
2837                     if ((ldata->lattr & LATTR_MODE) != LATTR_NORM) {
2838                         if (term->curs.x >= term->cols / 2)
2839                             term->curs.x = term->cols / 2 - 1;
2840                     } else {
2841                         if (term->curs.x >= term->cols)
2842                             term->curs.x = term->cols - 1;
2843                     }
2844
2845                     check_selection(term, old_curs, term->curs);
2846                 }
2847                 seen_disp_event(term);
2848                 break;
2849             }
2850         } else
2851             switch (term->termstate) {
2852               case TOPLEVEL:
2853                 /* Only graphic characters get this far;
2854                  * ctrls are stripped above */
2855                 {
2856                     termline *cline = scrlineptr(term->curs.y);
2857                     int width = 0;
2858                     if (DIRECT_CHAR(c))
2859                         width = 1;
2860                     if (!width)
2861                         width = (term->cfg.cjk_ambig_wide ?
2862                                  mk_wcwidth_cjk((wchar_t) c) :
2863                                  mk_wcwidth((wchar_t) c));
2864
2865                     if (term->wrapnext && term->wrap && width > 0) {
2866                         cline->lattr |= LATTR_WRAPPED;
2867                         if (term->curs.y == term->marg_b)
2868                             scroll(term, term->marg_t, term->marg_b, 1, TRUE);
2869                         else if (term->curs.y < term->rows - 1)
2870                             term->curs.y++;
2871                         term->curs.x = 0;
2872                         term->wrapnext = FALSE;
2873                         cline = scrlineptr(term->curs.y);
2874                     }
2875                     if (term->insert && width > 0)
2876                         insch(term, width);
2877                     if (term->selstate != NO_SELECTION) {
2878                         pos cursplus = term->curs;
2879                         incpos(cursplus);
2880                         check_selection(term, term->curs, cursplus);
2881                     }
2882                     if (((c & CSET_MASK) == CSET_ASCII ||
2883                          (c & CSET_MASK) == 0) &&
2884                         term->logctx)
2885                         logtraffic(term->logctx, (unsigned char) c,
2886                                    LGTYP_ASCII);
2887
2888                     switch (width) {
2889                       case 2:
2890                         /*
2891                          * If we're about to display a double-width
2892                          * character starting in the rightmost
2893                          * column, then we do something special
2894                          * instead. We must print a space in the
2895                          * last column of the screen, then wrap;
2896                          * and we also set LATTR_WRAPPED2 which
2897                          * instructs subsequent cut-and-pasting not
2898                          * only to splice this line to the one
2899                          * after it, but to ignore the space in the
2900                          * last character position as well.
2901                          * (Because what was actually output to the
2902                          * terminal was presumably just a sequence
2903                          * of CJK characters, and we don't want a
2904                          * space to be pasted in the middle of
2905                          * those just because they had the
2906                          * misfortune to start in the wrong parity
2907                          * column. xterm concurs.)
2908                          */
2909                         check_boundary(term, term->curs.x, term->curs.y);
2910                         check_boundary(term, term->curs.x+2, term->curs.y);
2911                         if (term->curs.x == term->cols-1) {
2912                             copy_termchar(cline, term->curs.x,
2913                                           &term->erase_char);
2914                             cline->lattr |= LATTR_WRAPPED | LATTR_WRAPPED2;
2915                             if (term->curs.y == term->marg_b)
2916                                 scroll(term, term->marg_t, term->marg_b,
2917                                        1, TRUE);
2918                             else if (term->curs.y < term->rows - 1)
2919                                 term->curs.y++;
2920                             term->curs.x = 0;
2921                             cline = scrlineptr(term->curs.y);
2922                             /* Now we must check_boundary again, of course. */
2923                             check_boundary(term, term->curs.x, term->curs.y);
2924                             check_boundary(term, term->curs.x+2, term->curs.y);
2925                         }
2926
2927                         /* FULL-TERMCHAR */
2928                         clear_cc(cline, term->curs.x);
2929                         cline->chars[term->curs.x].chr = c;
2930                         cline->chars[term->curs.x].attr = term->curr_attr;
2931
2932                         term->curs.x++;
2933
2934                         /* FULL-TERMCHAR */
2935                         clear_cc(cline, term->curs.x);
2936                         cline->chars[term->curs.x].chr = UCSWIDE;
2937                         cline->chars[term->curs.x].attr = term->curr_attr;
2938
2939                         break;
2940                       case 1:
2941                         check_boundary(term, term->curs.x, term->curs.y);
2942                         check_boundary(term, term->curs.x+1, term->curs.y);
2943
2944                         /* FULL-TERMCHAR */
2945                         clear_cc(cline, term->curs.x);
2946                         cline->chars[term->curs.x].chr = c;
2947                         cline->chars[term->curs.x].attr = term->curr_attr;
2948
2949                         break;
2950                       case 0:
2951                         if (term->curs.x > 0) {
2952                             int x = term->curs.x - 1;
2953
2954                             /* If we're in wrapnext state, the character
2955                              * to combine with is _here_, not to our left. */
2956                             if (term->wrapnext)
2957                                 x++;
2958
2959                             /*
2960                              * If the previous character is
2961                              * UCSWIDE, back up another one.
2962                              */
2963                             if (cline->chars[x].chr == UCSWIDE) {
2964                                 assert(x > 0);
2965                                 x--;
2966                             }
2967
2968                             add_cc(cline, x, c);
2969                             seen_disp_event(term);
2970                         }
2971                         continue;
2972                       default:
2973                         continue;
2974                     }
2975                     term->curs.x++;
2976                     if (term->curs.x == term->cols) {
2977                         term->curs.x--;
2978                         term->wrapnext = TRUE;
2979                         if (term->wrap && term->vt52_mode) {
2980                             cline->lattr |= LATTR_WRAPPED;
2981                             if (term->curs.y == term->marg_b)
2982                                 scroll(term, term->marg_t, term->marg_b, 1, TRUE);
2983                             else if (term->curs.y < term->rows - 1)
2984                                 term->curs.y++;
2985                             term->curs.x = 0;
2986                             term->wrapnext = FALSE;
2987                         }
2988                     }
2989                     seen_disp_event(term);
2990                 }
2991                 break;
2992
2993               case OSC_MAYBE_ST:
2994                 /*
2995                  * This state is virtually identical to SEEN_ESC, with the
2996                  * exception that we have an OSC sequence in the pipeline,
2997                  * and _if_ we see a backslash, we process it.
2998                  */
2999                 if (c == '\\') {
3000                     do_osc(term);
3001                     term->termstate = TOPLEVEL;
3002                     break;
3003                 }
3004                 /* else fall through */
3005               case SEEN_ESC:
3006                 if (c >= ' ' && c <= '/') {
3007                     if (term->esc_query)
3008                         term->esc_query = -1;
3009                     else
3010                         term->esc_query = c;
3011                     break;
3012                 }
3013                 term->termstate = TOPLEVEL;
3014                 switch (ANSI(c, term->esc_query)) {
3015                   case '[':             /* enter CSI mode */
3016                     term->termstate = SEEN_CSI;
3017                     term->esc_nargs = 1;
3018                     term->esc_args[0] = ARG_DEFAULT;
3019                     term->esc_query = FALSE;
3020                     break;
3021                   case ']':             /* OSC: xterm escape sequences */
3022                     /* Compatibility is nasty here, xterm, linux, decterm yuk! */
3023                     compatibility(OTHER);
3024                     term->termstate = SEEN_OSC;
3025                     term->esc_args[0] = 0;
3026                     break;
3027                   case '7':             /* DECSC: save cursor */
3028                     compatibility(VT100);
3029                     save_cursor(term, TRUE);
3030                     break;
3031                   case '8':             /* DECRC: restore cursor */
3032                     compatibility(VT100);
3033                     save_cursor(term, FALSE);
3034                     seen_disp_event(term);
3035                     break;
3036                   case '=':             /* DECKPAM: Keypad application mode */
3037                     compatibility(VT100);
3038                     term->app_keypad_keys = TRUE;
3039                     break;
3040                   case '>':             /* DECKPNM: Keypad numeric mode */
3041                     compatibility(VT100);
3042                     term->app_keypad_keys = FALSE;
3043                     break;
3044                   case 'D':            /* IND: exactly equivalent to LF */
3045                     compatibility(VT100);
3046                     if (term->curs.y == term->marg_b)
3047                         scroll(term, term->marg_t, term->marg_b, 1, TRUE);
3048                     else if (term->curs.y < term->rows - 1)
3049                         term->curs.y++;
3050                     term->wrapnext = FALSE;
3051                     seen_disp_event(term);
3052                     break;
3053                   case 'E':            /* NEL: exactly equivalent to CR-LF */
3054                     compatibility(VT100);
3055                     term->curs.x = 0;
3056                     if (term->curs.y == term->marg_b)
3057                         scroll(term, term->marg_t, term->marg_b, 1, TRUE);
3058                     else if (term->curs.y < term->rows - 1)
3059                         term->curs.y++;
3060                     term->wrapnext = FALSE;
3061                     seen_disp_event(term);
3062                     break;
3063                   case 'M':            /* RI: reverse index - backwards LF */
3064                     compatibility(VT100);
3065                     if (term->curs.y == term->marg_t)
3066                         scroll(term, term->marg_t, term->marg_b, -1, TRUE);
3067                     else if (term->curs.y > 0)
3068                         term->curs.y--;
3069                     term->wrapnext = FALSE;
3070                     seen_disp_event(term);
3071                     break;
3072                   case 'Z':            /* DECID: terminal type query */
3073                     compatibility(VT100);
3074                     if (term->ldisc)
3075                         ldisc_send(term->ldisc, term->id_string,
3076                                    strlen(term->id_string), 0);
3077                     break;
3078                   case 'c':            /* RIS: restore power-on settings */
3079                     compatibility(VT100);
3080                     power_on(term);
3081                     if (term->ldisc)   /* cause ldisc to notice changes */
3082                         ldisc_send(term->ldisc, NULL, 0, 0);
3083                     if (term->reset_132) {
3084                         if (!term->cfg.no_remote_resize)
3085                             request_resize(term->frontend, 80, term->rows);
3086                         term->reset_132 = 0;
3087                     }
3088                     term->disptop = 0;
3089                     seen_disp_event(term);
3090                     break;
3091                   case 'H':            /* HTS: set a tab */
3092                     compatibility(VT100);
3093                     term->tabs[term->curs.x] = TRUE;
3094                     break;
3095
3096                   case ANSI('8', '#'):  /* DECALN: fills screen with Es :-) */
3097                     compatibility(VT100);
3098                     {
3099                         termline *ldata;
3100                         int i, j;
3101                         pos scrtop, scrbot;
3102
3103                         for (i = 0; i < term->rows; i++) {
3104                             ldata = scrlineptr(i);
3105                             for (j = 0; j < term->cols; j++) {
3106                                 copy_termchar(ldata, j,
3107                                               &term->basic_erase_char);
3108                                 ldata->chars[j].chr = 'E';
3109                             }
3110                             ldata->lattr = LATTR_NORM;
3111                         }
3112                         term->disptop = 0;
3113                         seen_disp_event(term);
3114                         scrtop.x = scrtop.y = 0;
3115                         scrbot.x = 0;
3116                         scrbot.y = term->rows;
3117                         check_selection(term, scrtop, scrbot);
3118                     }
3119                     break;
3120
3121                   case ANSI('3', '#'):
3122                   case ANSI('4', '#'):
3123                   case ANSI('5', '#'):
3124                   case ANSI('6', '#'):
3125                     compatibility(VT100);
3126                     {
3127                         int nlattr;
3128
3129                         switch (ANSI(c, term->esc_query)) {
3130                           case ANSI('3', '#'): /* DECDHL: 2*height, top */
3131                             nlattr = LATTR_TOP;
3132                             break;
3133                           case ANSI('4', '#'): /* DECDHL: 2*height, bottom */
3134                             nlattr = LATTR_BOT;
3135                             break;
3136                           case ANSI('5', '#'): /* DECSWL: normal */
3137                             nlattr = LATTR_NORM;
3138                             break;
3139                           default: /* case ANSI('6', '#'): DECDWL: 2*width */
3140                             nlattr = LATTR_WIDE;
3141                             break;
3142                         }
3143                         scrlineptr(term->curs.y)->lattr = nlattr;
3144                     }
3145                     break;
3146                   /* GZD4: G0 designate 94-set */
3147                   case ANSI('A', '('):
3148                     compatibility(VT100);
3149                     if (!term->cfg.no_remote_charset)
3150                         term->cset_attr[0] = CSET_GBCHR;
3151                     break;
3152                   case ANSI('B', '('):
3153                     compatibility(VT100);
3154                     if (!term->cfg.no_remote_charset)
3155                         term->cset_attr[0] = CSET_ASCII;
3156                     break;
3157                   case ANSI('0', '('):
3158                     compatibility(VT100);
3159                     if (!term->cfg.no_remote_charset)
3160                         term->cset_attr[0] = CSET_LINEDRW;
3161                     break;
3162                   case ANSI('U', '('): 
3163                     compatibility(OTHER);
3164                     if (!term->cfg.no_remote_charset)
3165                         term->cset_attr[0] = CSET_SCOACS; 
3166                     break;
3167                   /* G1D4: G1-designate 94-set */
3168                   case ANSI('A', ')'):
3169                     compatibility(VT100);
3170                     if (!term->cfg.no_remote_charset)
3171                         term->cset_attr[1] = CSET_GBCHR;
3172                     break;
3173                   case ANSI('B', ')'):
3174                     compatibility(VT100);
3175                     if (!term->cfg.no_remote_charset)
3176                         term->cset_attr[1] = CSET_ASCII;
3177                     break;
3178                   case ANSI('0', ')'):
3179                     compatibility(VT100);
3180                     if (!term->cfg.no_remote_charset)
3181                         term->cset_attr[1] = CSET_LINEDRW;
3182                     break;
3183                   case ANSI('U', ')'): 
3184                     compatibility(OTHER);
3185                     if (!term->cfg.no_remote_charset)
3186                         term->cset_attr[1] = CSET_SCOACS; 
3187                     break;
3188                   /* DOCS: Designate other coding system */
3189                   case ANSI('8', '%'):  /* Old Linux code */
3190                   case ANSI('G', '%'):
3191                     compatibility(OTHER);
3192                     if (!term->cfg.no_remote_charset)
3193                         term->utf = 1;
3194                     break;
3195                   case ANSI('@', '%'):
3196                     compatibility(OTHER);
3197                     if (!term->cfg.no_remote_charset)
3198                         term->utf = 0;
3199                     break;
3200                 }
3201                 break;
3202               case SEEN_CSI:
3203                 term->termstate = TOPLEVEL;  /* default */
3204                 if (isdigit(c)) {
3205                     if (term->esc_nargs <= ARGS_MAX) {
3206                         if (term->esc_args[term->esc_nargs - 1] == ARG_DEFAULT)
3207                             term->esc_args[term->esc_nargs - 1] = 0;
3208                         term->esc_args[term->esc_nargs - 1] =
3209                             10 * term->esc_args[term->esc_nargs - 1] + c - '0';
3210                     }
3211                     term->termstate = SEEN_CSI;
3212                 } else if (c == ';') {
3213                     if (++term->esc_nargs <= ARGS_MAX)
3214                         term->esc_args[term->esc_nargs - 1] = ARG_DEFAULT;
3215                     term->termstate = SEEN_CSI;
3216                 } else if (c < '@') {
3217                     if (term->esc_query)
3218                         term->esc_query = -1;
3219                     else if (c == '?')
3220                         term->esc_query = TRUE;
3221                     else
3222                         term->esc_query = c;
3223                     term->termstate = SEEN_CSI;
3224                 } else
3225                     switch (ANSI(c, term->esc_query)) {
3226                       case 'A':       /* CUU: move up N lines */
3227                         move(term, term->curs.x,
3228                              term->curs.y - def(term->esc_args[0], 1), 1);
3229                         seen_disp_event(term);
3230                         break;
3231                       case 'e':         /* VPR: move down N lines */
3232                         compatibility(ANSI);
3233                         /* FALLTHROUGH */
3234                       case 'B':         /* CUD: Cursor down */
3235                         move(term, term->curs.x,
3236                              term->curs.y + def(term->esc_args[0], 1), 1);
3237                         seen_disp_event(term);
3238                         break;
3239                       case ANSI('c', '>'):      /* DA: report xterm version */
3240                         compatibility(OTHER);
3241                         /* this reports xterm version 136 so that VIM can
3242                            use the drag messages from the mouse reporting */
3243                         if (term->ldisc)
3244                             ldisc_send(term->ldisc, "\033[>0;136;0c", 11, 0);
3245                         break;
3246                       case 'a':         /* HPR: move right N cols */
3247                         compatibility(ANSI);
3248                         /* FALLTHROUGH */
3249                       case 'C':         /* CUF: Cursor right */ 
3250                         move(term, term->curs.x + def(term->esc_args[0], 1),
3251                              term->curs.y, 1);
3252                         seen_disp_event(term);
3253                         break;
3254                       case 'D':       /* CUB: move left N cols */
3255                         move(term, term->curs.x - def(term->esc_args[0], 1),
3256                              term->curs.y, 1);
3257                         seen_disp_event(term);
3258                         break;
3259                       case 'E':       /* CNL: move down N lines and CR */
3260                         compatibility(ANSI);
3261                         move(term, 0,
3262                              term->curs.y + def(term->esc_args[0], 1), 1);
3263                         seen_disp_event(term);
3264                         break;
3265                       case 'F':       /* CPL: move up N lines and CR */
3266                         compatibility(ANSI);
3267                         move(term, 0,
3268                              term->curs.y - def(term->esc_args[0], 1), 1);
3269                         seen_disp_event(term);
3270                         break;
3271                       case 'G':       /* CHA */
3272                       case '`':       /* HPA: set horizontal posn */
3273                         compatibility(ANSI);
3274                         move(term, def(term->esc_args[0], 1) - 1,
3275                              term->curs.y, 0);
3276                         seen_disp_event(term);
3277                         break;
3278                       case 'd':       /* VPA: set vertical posn */
3279                         compatibility(ANSI);
3280                         move(term, term->curs.x,
3281                              ((term->dec_om ? term->marg_t : 0) +
3282                               def(term->esc_args[0], 1) - 1),
3283                              (term->dec_om ? 2 : 0));
3284                         seen_disp_event(term);
3285                         break;
3286                       case 'H':      /* CUP */
3287                       case 'f':      /* HVP: set horz and vert posns at once */
3288                         if (term->esc_nargs < 2)
3289                             term->esc_args[1] = ARG_DEFAULT;
3290                         move(term, def(term->esc_args[1], 1) - 1,
3291                              ((term->dec_om ? term->marg_t : 0) +
3292                               def(term->esc_args[0], 1) - 1),
3293                              (term->dec_om ? 2 : 0));
3294                         seen_disp_event(term);
3295                         break;
3296                       case 'J':       /* ED: erase screen or parts of it */
3297                         {
3298                             unsigned int i = def(term->esc_args[0], 0) + 1;
3299                             if (i > 3)
3300                                 i = 0;
3301                             erase_lots(term, FALSE, !!(i & 2), !!(i & 1));
3302                         }
3303                         term->disptop = 0;
3304                         seen_disp_event(term);
3305                         break;
3306                       case 'K':       /* EL: erase line or parts of it */
3307                         {
3308                             unsigned int i = def(term->esc_args[0], 0) + 1;
3309                             if (i > 3)
3310                                 i = 0;
3311                             erase_lots(term, TRUE, !!(i & 2), !!(i & 1));
3312                         }
3313                         seen_disp_event(term);
3314                         break;
3315                       case 'L':       /* IL: insert lines */
3316                         compatibility(VT102);
3317                         if (term->curs.y <= term->marg_b)
3318                             scroll(term, term->curs.y, term->marg_b,
3319                                    -def(term->esc_args[0], 1), FALSE);
3320                         seen_disp_event(term);
3321                         break;
3322                       case 'M':       /* DL: delete lines */
3323                         compatibility(VT102);
3324                         if (term->curs.y <= term->marg_b)
3325                             scroll(term, term->curs.y, term->marg_b,
3326                                    def(term->esc_args[0], 1),
3327                                    TRUE);
3328                         seen_disp_event(term);
3329                         break;
3330                       case '@':       /* ICH: insert chars */
3331                         /* XXX VTTEST says this is vt220, vt510 manual says vt102 */
3332                         compatibility(VT102);
3333                         insch(term, def(term->esc_args[0], 1));
3334                         seen_disp_event(term);
3335                         break;
3336                       case 'P':       /* DCH: delete chars */
3337                         compatibility(VT102);
3338                         insch(term, -def(term->esc_args[0], 1));
3339                         seen_disp_event(term);
3340                         break;
3341                       case 'c':       /* DA: terminal type query */
3342                         compatibility(VT100);
3343                         /* This is the response for a VT102 */
3344                         if (term->ldisc)
3345                             ldisc_send(term->ldisc, term->id_string,
3346                                        strlen(term->id_string), 0);
3347                         break;
3348                       case 'n':       /* DSR: cursor position query */
3349                         if (term->ldisc) {
3350                             if (term->esc_args[0] == 6) {
3351                                 char buf[32];
3352                                 sprintf(buf, "\033[%d;%dR", term->curs.y + 1,
3353                                         term->curs.x + 1);
3354                                 ldisc_send(term->ldisc, buf, strlen(buf), 0);
3355                             } else if (term->esc_args[0] == 5) {
3356                                 ldisc_send(term->ldisc, "\033[0n", 4, 0);
3357                             }
3358                         }
3359                         break;
3360                       case 'h':       /* SM: toggle modes to high */
3361                       case ANSI_QUE('h'):
3362                         compatibility(VT100);
3363                         {
3364                             int i;
3365                             for (i = 0; i < term->esc_nargs; i++)
3366                                 toggle_mode(term, term->esc_args[i],
3367                                             term->esc_query, TRUE);
3368                         }
3369                         break;
3370                       case 'i':         /* MC: Media copy */
3371                       case ANSI_QUE('i'):
3372                         compatibility(VT100);
3373                         {
3374                             if (term->esc_nargs != 1) break;
3375                             if (term->esc_args[0] == 5 && *term->cfg.printer) {
3376                                 term->printing = TRUE;
3377                                 term->only_printing = !term->esc_query;
3378                                 term->print_state = 0;
3379                                 term_print_setup(term);
3380                             } else if (term->esc_args[0] == 4 &&
3381                                        term->printing) {
3382                                 term_print_finish(term);
3383                             }
3384                         }
3385                         break;                  
3386                       case 'l':       /* RM: toggle modes to low */
3387                       case ANSI_QUE('l'):
3388                         compatibility(VT100);
3389                         {
3390                             int i;
3391                             for (i = 0; i < term->esc_nargs; i++)
3392                                 toggle_mode(term, term->esc_args[i],
3393                                             term->esc_query, FALSE);
3394                         }
3395                         break;
3396                       case 'g':       /* TBC: clear tabs */
3397                         compatibility(VT100);
3398                         if (term->esc_nargs == 1) {
3399                             if (term->esc_args[0] == 0) {
3400                                 term->tabs[term->curs.x] = FALSE;
3401                             } else if (term->esc_args[0] == 3) {
3402                                 int i;
3403                                 for (i = 0; i < term->cols; i++)
3404                                     term->tabs[i] = FALSE;
3405                             }
3406                         }
3407                         break;
3408                       case 'r':       /* DECSTBM: set scroll margins */
3409                         compatibility(VT100);
3410                         if (term->esc_nargs <= 2) {
3411                             int top, bot;
3412                             top = def(term->esc_args[0], 1) - 1;
3413                             bot = (term->esc_nargs <= 1
3414                                    || term->esc_args[1] == 0 ?
3415                                    term->rows :
3416                                    def(term->esc_args[1], term->rows)) - 1;
3417                             if (bot >= term->rows)
3418                                 bot = term->rows - 1;
3419                             /* VTTEST Bug 9 - if region is less than 2 lines
3420                              * don't change region.
3421                              */
3422                             if (bot - top > 0) {
3423                                 term->marg_t = top;
3424                                 term->marg_b = bot;
3425                                 term->curs.x = 0;
3426                                 /*
3427                                  * I used to think the cursor should be
3428                                  * placed at the top of the newly marginned
3429                                  * area. Apparently not: VMS TPU falls over
3430                                  * if so.
3431                                  *
3432                                  * Well actually it should for
3433                                  * Origin mode - RDB
3434                                  */
3435                                 term->curs.y = (term->dec_om ?
3436                                                 term->marg_t : 0);
3437                                 seen_disp_event(term);
3438                             }
3439                         }
3440                         break;
3441                       case 'm':       /* SGR: set graphics rendition */
3442                         {
3443                             /* 
3444                              * A VT100 without the AVO only had one
3445                              * attribute, either underline or
3446                              * reverse video depending on the
3447                              * cursor type, this was selected by
3448                              * CSI 7m.
3449                              *
3450                              * case 2:
3451                              *  This is sometimes DIM, eg on the
3452                              *  GIGI and Linux
3453                              * case 8:
3454                              *  This is sometimes INVIS various ANSI.
3455                              * case 21:
3456                              *  This like 22 disables BOLD, DIM and INVIS
3457                              *
3458                              * The ANSI colours appear on any
3459                              * terminal that has colour (obviously)
3460                              * but the interaction between sgr0 and
3461                              * the colours varies but is usually
3462                              * related to the background colour
3463                              * erase item. The interaction between
3464                              * colour attributes and the mono ones
3465                              * is also very implementation
3466                              * dependent.
3467                              *
3468                              * The 39 and 49 attributes are likely
3469                              * to be unimplemented.
3470                              */
3471                             int i;
3472                             for (i = 0; i < term->esc_nargs; i++) {
3473                                 switch (def(term->esc_args[i], 0)) {
3474                                   case 0:       /* restore defaults */
3475                                     term->curr_attr = term->default_attr;
3476                                     break;
3477                                   case 1:       /* enable bold */
3478                                     compatibility(VT100AVO);
3479                                     term->curr_attr |= ATTR_BOLD;
3480                                     break;
3481                                   case 21:      /* (enable double underline) */
3482                                     compatibility(OTHER);
3483                                   case 4:       /* enable underline */
3484                                     compatibility(VT100AVO);
3485                                     term->curr_attr |= ATTR_UNDER;
3486                                     break;
3487                                   case 5:       /* enable blink */
3488                                     compatibility(VT100AVO);
3489                                     term->curr_attr |= ATTR_BLINK;
3490                                     break;
3491                                   case 6:       /* SCO light bkgrd */
3492                                     compatibility(SCOANSI);
3493                                     term->blink_is_real = FALSE;
3494                                     term->curr_attr |= ATTR_BLINK;
3495                                     term_schedule_tblink(term);
3496                                     break;
3497                                   case 7:       /* enable reverse video */
3498                                     term->curr_attr |= ATTR_REVERSE;
3499                                     break;
3500                                   case 10:      /* SCO acs off */
3501                                     compatibility(SCOANSI);
3502                                     if (term->cfg.no_remote_charset) break;
3503                                     term->sco_acs = 0; break;
3504                                   case 11:      /* SCO acs on */
3505                                     compatibility(SCOANSI);
3506                                     if (term->cfg.no_remote_charset) break;
3507                                     term->sco_acs = 1; break;
3508                                   case 12:      /* SCO acs on, |0x80 */
3509                                     compatibility(SCOANSI);
3510                                     if (term->cfg.no_remote_charset) break;
3511                                     term->sco_acs = 2; break;
3512                                   case 22:      /* disable bold */
3513                                     compatibility2(OTHER, VT220);
3514                                     term->curr_attr &= ~ATTR_BOLD;
3515                                     break;
3516                                   case 24:      /* disable underline */
3517                                     compatibility2(OTHER, VT220);
3518                                     term->curr_attr &= ~ATTR_UNDER;
3519                                     break;
3520                                   case 25:      /* disable blink */
3521                                     compatibility2(OTHER, VT220);
3522                                     term->curr_attr &= ~ATTR_BLINK;
3523                                     break;
3524                                   case 27:      /* disable reverse video */
3525                                     compatibility2(OTHER, VT220);
3526                                     term->curr_attr &= ~ATTR_REVERSE;
3527                                     break;
3528                                   case 30:
3529                                   case 31:
3530                                   case 32:
3531                                   case 33:
3532                                   case 34:
3533                                   case 35:
3534                                   case 36:
3535                                   case 37:
3536                                     /* foreground */
3537                                     term->curr_attr &= ~ATTR_FGMASK;
3538                                     term->curr_attr |=
3539                                         (term->esc_args[i] - 30)<<ATTR_FGSHIFT;
3540                                     break;
3541                                   case 90:
3542                                   case 91:
3543                                   case 92:
3544                                   case 93:
3545                                   case 94:
3546                                   case 95:
3547                                   case 96:
3548                                   case 97:
3549                                     /* aixterm-style bright foreground */
3550                                     term->curr_attr &= ~ATTR_FGMASK;
3551                                     term->curr_attr |=
3552                                         ((term->esc_args[i] - 90 + 8)
3553                                          << ATTR_FGSHIFT);
3554                                     break;
3555                                   case 39:      /* default-foreground */
3556                                     term->curr_attr &= ~ATTR_FGMASK;
3557                                     term->curr_attr |= ATTR_DEFFG;
3558                                     break;
3559                                   case 40:
3560                                   case 41:
3561                                   case 42:
3562                                   case 43:
3563                                   case 44:
3564                                   case 45:
3565                                   case 46:
3566                                   case 47:
3567                                     /* background */
3568                                     term->curr_attr &= ~ATTR_BGMASK;
3569                                     term->curr_attr |=
3570                                         (term->esc_args[i] - 40)<<ATTR_BGSHIFT;
3571                                     break;
3572                                   case 100:
3573                                   case 101:
3574                                   case 102:
3575                                   case 103:
3576                                   case 104:
3577                                   case 105:
3578                                   case 106:
3579                                   case 107:
3580                                     /* aixterm-style bright background */
3581                                     term->curr_attr &= ~ATTR_BGMASK;
3582                                     term->curr_attr |=
3583                                         ((term->esc_args[i] - 100 + 8)
3584                                          << ATTR_BGSHIFT);
3585                                     break;
3586                                   case 49:      /* default-background */
3587                                     term->curr_attr &= ~ATTR_BGMASK;
3588                                     term->curr_attr |= ATTR_DEFBG;
3589                                     break;
3590                                   case 38:   /* xterm 256-colour mode */
3591                                     if (i+2 < term->esc_nargs &&
3592                                         term->esc_args[i+1] == 5) {
3593                                         term->curr_attr &= ~ATTR_FGMASK;
3594                                         term->curr_attr |=
3595                                             ((term->esc_args[i+2] & 0xFF)
3596                                              << ATTR_FGSHIFT);
3597                                         i += 2;
3598                                     }
3599                                     break;
3600                                   case 48:   /* xterm 256-colour mode */
3601                                     if (i+2 < term->esc_nargs &&
3602                                         term->esc_args[i+1] == 5) {
3603                                         term->curr_attr &= ~ATTR_BGMASK;
3604                                         term->curr_attr |=
3605                                             ((term->esc_args[i+2] & 0xFF)
3606                                              << ATTR_BGSHIFT);
3607                                         i += 2;
3608                                     }
3609                                     break;
3610                                 }
3611                             }
3612                             set_erase_char(term);
3613                         }
3614                         break;
3615                       case 's':       /* save cursor */
3616                         save_cursor(term, TRUE);
3617                         break;
3618                       case 'u':       /* restore cursor */
3619                         save_cursor(term, FALSE);
3620                         seen_disp_event(term);
3621                         break;
3622                       case 't': /* DECSLPP: set page size - ie window height */
3623                         /*
3624                          * VT340/VT420 sequence DECSLPP, DEC only allows values
3625                          *  24/25/36/48/72/144 other emulators (eg dtterm) use
3626                          * illegal values (eg first arg 1..9) for window changing 
3627                          * and reports.
3628                          */
3629                         if (term->esc_nargs <= 1
3630                             && (term->esc_args[0] < 1 ||
3631                                 term->esc_args[0] >= 24)) {
3632                             compatibility(VT340TEXT);
3633                             if (!term->cfg.no_remote_resize)
3634                                 request_resize(term->frontend, term->cols,
3635                                                def(term->esc_args[0], 24));
3636                             deselect(term);
3637                         } else if (term->esc_nargs >= 1 &&
3638                                    term->esc_args[0] >= 1 &&
3639                                    term->esc_args[0] < 24) {
3640                             compatibility(OTHER);
3641
3642                             switch (term->esc_args[0]) {
3643                                 int x, y, len;
3644                                 char buf[80], *p;
3645                               case 1:
3646                                 set_iconic(term->frontend, FALSE);
3647                                 break;
3648                               case 2:
3649                                 set_iconic(term->frontend, TRUE);
3650                                 break;
3651                               case 3:
3652                                 if (term->esc_nargs >= 3) {
3653                                     if (!term->cfg.no_remote_resize)
3654                                         move_window(term->frontend,
3655                                                     def(term->esc_args[1], 0),
3656                                                     def(term->esc_args[2], 0));
3657                                 }
3658                                 break;
3659                               case 4:
3660                                 /* We should resize the window to a given
3661                                  * size in pixels here, but currently our
3662                                  * resizing code isn't healthy enough to
3663                                  * manage it. */
3664                                 break;
3665                               case 5:
3666                                 /* move to top */
3667                                 set_zorder(term->frontend, TRUE);
3668                                 break;
3669                               case 6:
3670                                 /* move to bottom */
3671                                 set_zorder(term->frontend, FALSE);
3672                                 break;
3673                               case 7:
3674                                 refresh_window(term->frontend);
3675                                 break;
3676                               case 8:
3677                                 if (term->esc_nargs >= 3) {
3678                                     if (!term->cfg.no_remote_resize)
3679                                         request_resize(term->frontend,
3680                                                        def(term->esc_args[2], term->cfg.width),
3681                                                        def(term->esc_args[1], term->cfg.height));
3682                                 }
3683                                 break;
3684                               case 9:
3685                                 if (term->esc_nargs >= 2)
3686                                     set_zoomed(term->frontend,
3687                                                term->esc_args[1] ?
3688                                                TRUE : FALSE);
3689                                 break;
3690                               case 11:
3691                                 if (term->ldisc)
3692                                     ldisc_send(term->ldisc,
3693                                                is_iconic(term->frontend) ?
3694                                                "\033[1t" : "\033[2t", 4, 0);
3695                                 break;
3696                               case 13:
3697                                 if (term->ldisc) {
3698                                     get_window_pos(term->frontend, &x, &y);
3699                                     len = sprintf(buf, "\033[3;%d;%dt", x, y);
3700                                     ldisc_send(term->ldisc, buf, len, 0);
3701                                 }
3702                                 break;
3703                               case 14:
3704                                 if (term->ldisc) {
3705                                     get_window_pixels(term->frontend, &x, &y);
3706                                     len = sprintf(buf, "\033[4;%d;%dt", x, y);
3707                                     ldisc_send(term->ldisc, buf, len, 0);
3708                                 }
3709                                 break;
3710                               case 18:
3711                                 if (term->ldisc) {
3712                                     len = sprintf(buf, "\033[8;%d;%dt",
3713                                                   term->rows, term->cols);
3714                                     ldisc_send(term->ldisc, buf, len, 0);
3715                                 }
3716                                 break;
3717                               case 19:
3718                                 /*
3719                                  * Hmmm. Strictly speaking we
3720                                  * should return `the size of the
3721                                  * screen in characters', but
3722                                  * that's not easy: (a) window
3723                                  * furniture being what it is it's
3724                                  * hard to compute, and (b) in
3725                                  * resize-font mode maximising the
3726                                  * window wouldn't change the
3727                                  * number of characters. *shrug*. I
3728                                  * think we'll ignore it for the
3729                                  * moment and see if anyone
3730                                  * complains, and then ask them
3731                                  * what they would like it to do.
3732                                  */
3733                                 break;
3734                               case 20:
3735                                 if (term->ldisc &&
3736                                     !term->cfg.no_remote_qtitle) {
3737                                     p = get_window_title(term->frontend, TRUE);
3738                                     len = strlen(p);
3739                                     ldisc_send(term->ldisc, "\033]L", 3, 0);
3740                                     ldisc_send(term->ldisc, p, len, 0);
3741                                     ldisc_send(term->ldisc, "\033\\", 2, 0);
3742                                 }
3743                                 break;
3744                               case 21:
3745                                 if (term->ldisc &&
3746                                     !term->cfg.no_remote_qtitle) {
3747                                     p = get_window_title(term->frontend,FALSE);
3748                                     len = strlen(p);
3749                                     ldisc_send(term->ldisc, "\033]l", 3, 0);
3750                                     ldisc_send(term->ldisc, p, len, 0);
3751                                     ldisc_send(term->ldisc, "\033\\", 2, 0);
3752                                 }
3753                                 break;
3754                             }
3755                         }
3756                         break;
3757                       case 'S':         /* SU: Scroll up */
3758                         compatibility(SCOANSI);
3759                         scroll(term, term->marg_t, term->marg_b,
3760                                def(term->esc_args[0], 1), TRUE);
3761                         term->wrapnext = FALSE;
3762                         seen_disp_event(term);
3763                         break;
3764                       case 'T':         /* SD: Scroll down */
3765                         compatibility(SCOANSI);
3766                         scroll(term, term->marg_t, term->marg_b,
3767                                -def(term->esc_args[0], 1), TRUE);
3768                         term->wrapnext = FALSE;
3769                         seen_disp_event(term);
3770                         break;
3771                       case ANSI('|', '*'): /* DECSNLS */
3772                         /* 
3773                          * Set number of lines on screen
3774                          * VT420 uses VGA like hardware and can
3775                          * support any size in reasonable range
3776                          * (24..49 AIUI) with no default specified.
3777                          */
3778                         compatibility(VT420);
3779                         if (term->esc_nargs == 1 && term->esc_args[0] > 0) {
3780                             if (!term->cfg.no_remote_resize)
3781                                 request_resize(term->frontend, term->cols,
3782                                                def(term->esc_args[0],
3783                                                    term->cfg.height));
3784                             deselect(term);
3785                         }
3786                         break;
3787                       case ANSI('|', '$'): /* DECSCPP */
3788                         /*
3789                          * Set number of columns per page
3790                          * Docs imply range is only 80 or 132, but
3791                          * I'll allow any.
3792                          */
3793                         compatibility(VT340TEXT);
3794                         if (term->esc_nargs <= 1) {
3795                             if (!term->cfg.no_remote_resize)
3796                                 request_resize(term->frontend,
3797                                                def(term->esc_args[0],
3798                                                    term->cfg.width), term->rows);
3799                             deselect(term);
3800                         }
3801                         break;
3802                       case 'X':     /* ECH: write N spaces w/o moving cursor */
3803                         /* XXX VTTEST says this is vt220, vt510 manual
3804                          * says vt100 */
3805                         compatibility(ANSIMIN);
3806                         {
3807                             int n = def(term->esc_args[0], 1);
3808                             pos cursplus;
3809                             int p = term->curs.x;
3810                             termline *cline = scrlineptr(term->curs.y);
3811
3812                             if (n > term->cols - term->curs.x)
3813                                 n = term->cols - term->curs.x;
3814                             cursplus = term->curs;
3815                             cursplus.x += n;
3816                             check_boundary(term, term->curs.x, term->curs.y);
3817                             check_boundary(term, term->curs.x+n, term->curs.y);
3818                             check_selection(term, term->curs, cursplus);
3819                             while (n--)
3820                                 copy_termchar(cline, p++,
3821                                               &term->erase_char);
3822                             seen_disp_event(term);
3823                         }
3824                         break;
3825                       case 'x':       /* DECREQTPARM: report terminal characteristics */
3826                         compatibility(VT100);
3827                         if (term->ldisc) {
3828                             char buf[32];
3829                             int i = def(term->esc_args[0], 0);
3830                             if (i == 0 || i == 1) {
3831                                 strcpy(buf, "\033[2;1;1;112;112;1;0x");
3832                                 buf[2] += i;
3833                                 ldisc_send(term->ldisc, buf, 20, 0);
3834                             }
3835                         }
3836                         break;
3837                       case 'Z':         /* CBT */
3838                         compatibility(OTHER);
3839                         {
3840                             int i = def(term->esc_args[0], 1);
3841                             pos old_curs = term->curs;
3842
3843                             for(;i>0 && term->curs.x>0; i--) {
3844                                 do {
3845                                     term->curs.x--;
3846                                 } while (term->curs.x >0 &&
3847                                          !term->tabs[term->curs.x]);
3848                             }
3849                             check_selection(term, old_curs, term->curs);
3850                         }
3851                         break;
3852                       case ANSI('c', '='):      /* Hide or Show Cursor */
3853                         compatibility(SCOANSI);
3854                         switch(term->esc_args[0]) {
3855                           case 0:  /* hide cursor */
3856                             term->cursor_on = FALSE;
3857                             break;
3858                           case 1:  /* restore cursor */
3859                             term->big_cursor = FALSE;
3860                             term->cursor_on = TRUE;
3861                             break;
3862                           case 2:  /* block cursor */
3863                             term->big_cursor = TRUE;
3864                             term->cursor_on = TRUE;
3865                             break;
3866                         }
3867                         break;
3868                       case ANSI('C', '='):
3869                         /*
3870                          * set cursor start on scanline esc_args[0] and
3871                          * end on scanline esc_args[1].If you set
3872                          * the bottom scan line to a value less than
3873                          * the top scan line, the cursor will disappear.
3874                          */
3875                         compatibility(SCOANSI);
3876                         if (term->esc_nargs >= 2) {
3877                             if (term->esc_args[0] > term->esc_args[1])
3878                                 term->cursor_on = FALSE;
3879                             else
3880                                 term->cursor_on = TRUE;
3881                         }
3882                         break;
3883                       case ANSI('D', '='):
3884                         compatibility(SCOANSI);
3885                         term->blink_is_real = FALSE;
3886                         term_schedule_tblink(term);
3887                         if (term->esc_args[0]>=1)
3888                             term->curr_attr |= ATTR_BLINK;
3889                         else
3890                             term->curr_attr &= ~ATTR_BLINK;
3891                         break;
3892                       case ANSI('E', '='):
3893                         compatibility(SCOANSI);
3894                         term->blink_is_real = (term->esc_args[0] >= 1);
3895                         term_schedule_tblink(term);
3896                         break;
3897                       case ANSI('F', '='):      /* set normal foreground */
3898                         compatibility(SCOANSI);
3899                         if (term->esc_args[0] >= 0 && term->esc_args[0] < 16) {
3900                             long colour =
3901                                 (sco2ansicolour[term->esc_args[0] & 0x7] |
3902                                  (term->esc_args[0] & 0x8)) <<
3903                                 ATTR_FGSHIFT;
3904                             term->curr_attr &= ~ATTR_FGMASK;
3905                             term->curr_attr |= colour;
3906                             term->default_attr &= ~ATTR_FGMASK;
3907                             term->default_attr |= colour;
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                         }
3922                         break;
3923                       case ANSI('L', '='):
3924                         compatibility(SCOANSI);
3925                         term->use_bce = (term->esc_args[0] <= 0);
3926                         set_erase_char(term);
3927                         break;
3928                       case ANSI('p', '"'): /* DECSCL: set compat level */
3929                         /*
3930                          * Allow the host to make this emulator a
3931                          * 'perfect' VT102. This first appeared in
3932                          * the VT220, but we do need to get back to
3933                          * PuTTY mode so I won't check it.
3934                          *
3935                          * The arg in 40..42,50 are a PuTTY extension.
3936                          * The 2nd arg, 8bit vs 7bit is not checked.
3937                          *
3938                          * Setting VT102 mode should also change
3939                          * the Fkeys to generate PF* codes as a
3940                          * real VT102 has no Fkeys. The VT220 does
3941                          * this, F11..F13 become ESC,BS,LF other
3942                          * Fkeys send nothing.
3943                          *
3944                          * Note ESC c will NOT change this!
3945                          */
3946
3947                         switch (term->esc_args[0]) {
3948                           case 61:
3949                             term->compatibility_level &= ~TM_VTXXX;
3950                             term->compatibility_level |= TM_VT102;
3951                             break;
3952                           case 62:
3953                             term->compatibility_level &= ~TM_VTXXX;
3954                             term->compatibility_level |= TM_VT220;
3955                             break;
3956
3957                           default:
3958                             if (term->esc_args[0] > 60 &&
3959                                 term->esc_args[0] < 70)
3960                                 term->compatibility_level |= TM_VTXXX;
3961                             break;
3962
3963                           case 40:
3964                             term->compatibility_level &= TM_VTXXX;
3965                             break;
3966                           case 41:
3967                             term->compatibility_level = TM_PUTTY;
3968                             break;
3969                           case 42:
3970                             term->compatibility_level = TM_SCOANSI;
3971                             break;
3972
3973                           case ARG_DEFAULT:
3974                             term->compatibility_level = TM_PUTTY;
3975                             break;
3976                           case 50:
3977                             break;
3978                         }
3979
3980                         /* Change the response to CSI c */
3981                         if (term->esc_args[0] == 50) {
3982                             int i;
3983                             char lbuf[64];
3984                             strcpy(term->id_string, "\033[?");
3985                             for (i = 1; i < term->esc_nargs; i++) {
3986                                 if (i != 1)
3987                                     strcat(term->id_string, ";");
3988                                 sprintf(lbuf, "%d", term->esc_args[i]);
3989                                 strcat(term->id_string, lbuf);
3990                             }
3991                             strcat(term->id_string, "c");
3992                         }
3993 #if 0
3994                         /* Is this a good idea ? 
3995                          * Well we should do a soft reset at this point ...
3996                          */
3997                         if (!has_compat(VT420) && has_compat(VT100)) {
3998                             if (!term->cfg.no_remote_resize) {
3999                                 if (term->reset_132)
4000                                     request_resize(132, 24);
4001                                 else
4002                                     request_resize(80, 24);
4003                             }
4004                         }
4005 #endif
4006                         break;
4007                     }
4008                 break;
4009               case SEEN_OSC:
4010                 term->osc_w = FALSE;
4011                 switch (c) {
4012                   case 'P':            /* Linux palette sequence */
4013                     term->termstate = SEEN_OSC_P;
4014                     term->osc_strlen = 0;
4015                     break;
4016                   case 'R':            /* Linux palette reset */
4017                     palette_reset(term->frontend);
4018                     term_invalidate(term);
4019                     term->termstate = TOPLEVEL;
4020                     break;
4021                   case 'W':            /* word-set */
4022                     term->termstate = SEEN_OSC_W;
4023                     term->osc_w = TRUE;
4024                     break;
4025                   case '0':
4026                   case '1':
4027                   case '2':
4028                   case '3':
4029                   case '4':
4030                   case '5':
4031                   case '6':
4032                   case '7':
4033                   case '8':
4034                   case '9':
4035                     term->esc_args[0] = 10 * term->esc_args[0] + c - '0';
4036                     break;
4037                   case 'L':
4038                     /*
4039                      * Grotty hack to support xterm and DECterm title
4040                      * sequences concurrently.
4041                      */
4042                     if (term->esc_args[0] == 2) {
4043                         term->esc_args[0] = 1;
4044                         break;
4045                     }
4046                     /* else fall through */
4047                   default:
4048                     term->termstate = OSC_STRING;
4049                     term->osc_strlen = 0;
4050                 }
4051                 break;
4052               case OSC_STRING:
4053                 /*
4054                  * This OSC stuff is EVIL. It takes just one character to get into
4055                  * sysline mode and it's not initially obvious how to get out.
4056                  * So I've added CR and LF as string aborts.
4057                  * This shouldn't effect compatibility as I believe embedded 
4058                  * control characters are supposed to be interpreted (maybe?) 
4059                  * and they don't display anything useful anyway.
4060                  *
4061                  * -- RDB
4062                  */
4063                 if (c == '\012' || c == '\015') {
4064                     term->termstate = TOPLEVEL;
4065                 } else if (c == 0234 || c == '\007') {
4066                     /*
4067                      * These characters terminate the string; ST and BEL
4068                      * terminate the sequence and trigger instant
4069                      * processing of it, whereas ESC goes back to SEEN_ESC
4070                      * mode unless it is followed by \, in which case it is
4071                      * synonymous with ST in the first place.
4072                      */
4073                     do_osc(term);
4074                     term->termstate = TOPLEVEL;
4075                 } else if (c == '\033')
4076                     term->termstate = OSC_MAYBE_ST;
4077                 else if (term->osc_strlen < OSC_STR_MAX)
4078                     term->osc_string[term->osc_strlen++] = (char)c;
4079                 break;
4080               case SEEN_OSC_P:
4081                 {
4082                     int max = (term->osc_strlen == 0 ? 21 : 16);
4083                     int val;
4084                     if ((int)c >= '0' && (int)c <= '9')
4085                         val = c - '0';
4086                     else if ((int)c >= 'A' && (int)c <= 'A' + max - 10)
4087                         val = c - 'A' + 10;
4088                     else if ((int)c >= 'a' && (int)c <= 'a' + max - 10)
4089                         val = c - 'a' + 10;
4090                     else {
4091                         term->termstate = TOPLEVEL;
4092                         break;
4093                     }
4094                     term->osc_string[term->osc_strlen++] = val;
4095                     if (term->osc_strlen >= 7) {
4096                         palette_set(term->frontend, term->osc_string[0],
4097                                     term->osc_string[1] * 16 + term->osc_string[2],
4098                                     term->osc_string[3] * 16 + term->osc_string[4],
4099                                     term->osc_string[5] * 16 + term->osc_string[6]);
4100                         term_invalidate(term);
4101                         term->termstate = TOPLEVEL;
4102                     }
4103                 }
4104                 break;
4105               case SEEN_OSC_W:
4106                 switch (c) {
4107                   case '0':
4108                   case '1':
4109                   case '2':
4110                   case '3':
4111                   case '4':
4112                   case '5':
4113                   case '6':
4114                   case '7':
4115                   case '8':
4116                   case '9':
4117                     term->esc_args[0] = 10 * term->esc_args[0] + c - '0';
4118                     break;
4119                   default:
4120                     term->termstate = OSC_STRING;
4121                     term->osc_strlen = 0;
4122                 }
4123                 break;
4124               case VT52_ESC:
4125                 term->termstate = TOPLEVEL;
4126                 seen_disp_event(term);
4127                 switch (c) {
4128                   case 'A':
4129                     move(term, term->curs.x, term->curs.y - 1, 1);
4130                     break;
4131                   case 'B':
4132                     move(term, term->curs.x, term->curs.y + 1, 1);
4133                     break;
4134                   case 'C':
4135                     move(term, term->curs.x + 1, term->curs.y, 1);
4136                     break;
4137                   case 'D':
4138                     move(term, term->curs.x - 1, term->curs.y, 1);
4139                     break;
4140                     /*
4141                      * From the VT100 Manual
4142                      * NOTE: The special graphics characters in the VT100
4143                      *       are different from those in the VT52
4144                      *
4145                      * From VT102 manual:
4146                      *       137 _  Blank             - Same
4147                      *       140 `  Reserved          - Humm.
4148                      *       141 a  Solid rectangle   - Similar
4149                      *       142 b  1/                - Top half of fraction for the
4150                      *       143 c  3/                - subscript numbers below.
4151                      *       144 d  5/
4152                      *       145 e  7/
4153                      *       146 f  Degrees           - Same
4154                      *       147 g  Plus or minus     - Same
4155                      *       150 h  Right arrow
4156                      *       151 i  Ellipsis (dots)
4157                      *       152 j  Divide by
4158                      *       153 k  Down arrow
4159                      *       154 l  Bar at scan 0
4160                      *       155 m  Bar at scan 1
4161                      *       156 n  Bar at scan 2
4162                      *       157 o  Bar at scan 3     - Similar
4163                      *       160 p  Bar at scan 4     - Similar
4164                      *       161 q  Bar at scan 5     - Similar
4165                      *       162 r  Bar at scan 6     - Same
4166                      *       163 s  Bar at scan 7     - Similar
4167                      *       164 t  Subscript 0
4168                      *       165 u  Subscript 1
4169                      *       166 v  Subscript 2
4170                      *       167 w  Subscript 3
4171                      *       170 x  Subscript 4
4172                      *       171 y  Subscript 5
4173                      *       172 z  Subscript 6
4174                      *       173 {  Subscript 7
4175                      *       174 |  Subscript 8
4176                      *       175 }  Subscript 9
4177                      *       176 ~  Paragraph
4178                      *
4179                      */
4180                   case 'F':
4181                     term->cset_attr[term->cset = 0] = CSET_LINEDRW;
4182                     break;
4183                   case 'G':
4184                     term->cset_attr[term->cset = 0] = CSET_ASCII;
4185                     break;
4186                   case 'H':
4187                     move(term, 0, 0, 0);
4188                     break;
4189                   case 'I':
4190                     if (term->curs.y == 0)
4191                         scroll(term, 0, term->rows - 1, -1, TRUE);
4192                     else if (term->curs.y > 0)
4193                         term->curs.y--;
4194                     term->wrapnext = FALSE;
4195                     break;
4196                   case 'J':
4197                     erase_lots(term, FALSE, FALSE, TRUE);
4198                     term->disptop = 0;
4199                     break;
4200                   case 'K':
4201                     erase_lots(term, TRUE, FALSE, TRUE);
4202                     break;
4203 #if 0
4204                   case 'V':
4205                     /* XXX Print cursor line */
4206                     break;
4207                   case 'W':
4208                     /* XXX Start controller mode */
4209                     break;
4210                   case 'X':
4211                     /* XXX Stop controller mode */
4212                     break;
4213 #endif
4214                   case 'Y':
4215                     term->termstate = VT52_Y1;
4216                     break;
4217                   case 'Z':
4218                     if (term->ldisc)
4219                         ldisc_send(term->ldisc, "\033/Z", 3, 0);
4220                     break;
4221                   case '=':
4222                     term->app_keypad_keys = TRUE;
4223                     break;
4224                   case '>':
4225                     term->app_keypad_keys = FALSE;
4226                     break;
4227                   case '<':
4228                     /* XXX This should switch to VT100 mode not current or default
4229                      *     VT mode. But this will only have effect in a VT220+
4230                      *     emulation.
4231                      */
4232                     term->vt52_mode = FALSE;
4233                     term->blink_is_real = term->cfg.blinktext;
4234                     term_schedule_tblink(term);
4235                     break;
4236 #if 0
4237                   case '^':
4238                     /* XXX Enter auto print mode */
4239                     break;
4240                   case '_':
4241                     /* XXX Exit auto print mode */
4242                     break;
4243                   case ']':
4244                     /* XXX Print screen */
4245                     break;
4246 #endif
4247
4248 #ifdef VT52_PLUS
4249                   case 'E':
4250                     /* compatibility(ATARI) */
4251                     move(term, 0, 0, 0);
4252                     erase_lots(term, FALSE, FALSE, TRUE);
4253                     term->disptop = 0;
4254                     break;
4255                   case 'L':
4256                     /* compatibility(ATARI) */
4257                     if (term->curs.y <= term->marg_b)
4258                         scroll(term, term->curs.y, term->marg_b, -1, FALSE);
4259                     break;
4260                   case 'M':
4261                     /* compatibility(ATARI) */
4262                     if (term->curs.y <= term->marg_b)
4263                         scroll(term, term->curs.y, term->marg_b, 1, TRUE);
4264                     break;
4265                   case 'b':
4266                     /* compatibility(ATARI) */
4267                     term->termstate = VT52_FG;
4268                     break;
4269                   case 'c':
4270                     /* compatibility(ATARI) */
4271                     term->termstate = VT52_BG;
4272                     break;
4273                   case 'd':
4274                     /* compatibility(ATARI) */
4275                     erase_lots(term, FALSE, TRUE, FALSE);
4276                     term->disptop = 0;
4277                     break;
4278                   case 'e':
4279                     /* compatibility(ATARI) */
4280                     term->cursor_on = TRUE;
4281                     break;
4282                   case 'f':
4283                     /* compatibility(ATARI) */
4284                     term->cursor_on = FALSE;
4285                     break;
4286                     /* case 'j': Save cursor position - broken on ST */
4287                     /* case 'k': Restore cursor position */
4288                   case 'l':
4289                     /* compatibility(ATARI) */
4290                     erase_lots(term, TRUE, TRUE, TRUE);
4291                     term->curs.x = 0;
4292                     term->wrapnext = FALSE;
4293                     break;
4294                   case 'o':
4295                     /* compatibility(ATARI) */
4296                     erase_lots(term, TRUE, TRUE, FALSE);
4297                     break;
4298                   case 'p':
4299                     /* compatibility(ATARI) */
4300                     term->curr_attr |= ATTR_REVERSE;
4301                     break;
4302                   case 'q':
4303                     /* compatibility(ATARI) */
4304                     term->curr_attr &= ~ATTR_REVERSE;
4305                     break;
4306                   case 'v':            /* wrap Autowrap on - Wyse style */
4307                     /* compatibility(ATARI) */
4308                     term->wrap = 1;
4309                     break;
4310                   case 'w':            /* Autowrap off */
4311                     /* compatibility(ATARI) */
4312                     term->wrap = 0;
4313                     break;
4314
4315                   case 'R':
4316                     /* compatibility(OTHER) */
4317                     term->vt52_bold = FALSE;
4318                     term->curr_attr = ATTR_DEFAULT;
4319                     set_erase_char(term);
4320                     break;
4321                   case 'S':
4322                     /* compatibility(VI50) */
4323                     term->curr_attr |= ATTR_UNDER;
4324                     break;
4325                   case 'W':
4326                     /* compatibility(VI50) */
4327                     term->curr_attr &= ~ATTR_UNDER;
4328                     break;
4329                   case 'U':
4330                     /* compatibility(VI50) */
4331                     term->vt52_bold = TRUE;
4332                     term->curr_attr |= ATTR_BOLD;
4333                     break;
4334                   case 'T':
4335                     /* compatibility(VI50) */
4336                     term->vt52_bold = FALSE;
4337                     term->curr_attr &= ~ATTR_BOLD;
4338                     break;
4339 #endif
4340                 }
4341                 break;
4342               case VT52_Y1:
4343                 term->termstate = VT52_Y2;
4344                 move(term, term->curs.x, c - ' ', 0);
4345                 break;
4346               case VT52_Y2:
4347                 term->termstate = TOPLEVEL;
4348                 move(term, c - ' ', term->curs.y, 0);
4349                 break;
4350
4351 #ifdef VT52_PLUS
4352               case VT52_FG:
4353                 term->termstate = TOPLEVEL;
4354                 term->curr_attr &= ~ATTR_FGMASK;
4355                 term->curr_attr &= ~ATTR_BOLD;
4356                 term->curr_attr |= (c & 0xF) << ATTR_FGSHIFT;
4357                 set_erase_char(term);
4358                 break;
4359               case VT52_BG:
4360                 term->termstate = TOPLEVEL;
4361                 term->curr_attr &= ~ATTR_BGMASK;
4362                 term->curr_attr &= ~ATTR_BLINK;
4363                 term->curr_attr |= (c & 0xF) << ATTR_BGSHIFT;
4364                 set_erase_char(term);
4365                 break;
4366 #endif
4367               default: break;          /* placate gcc warning about enum use */
4368             }
4369         if (term->selstate != NO_SELECTION) {
4370             pos cursplus = term->curs;
4371             incpos(cursplus);
4372             check_selection(term, term->curs, cursplus);
4373         }
4374     }
4375
4376     term_print_flush(term);
4377     if (term->cfg.logflush)
4378         logflush(term->logctx);
4379 }
4380
4381 /*
4382  * To prevent having to run the reasonably tricky bidi algorithm
4383  * too many times, we maintain a cache of the last lineful of data
4384  * fed to the algorithm on each line of the display.
4385  */
4386 static int term_bidi_cache_hit(Terminal *term, int line,
4387                                termchar *lbefore, int width)
4388 {
4389     int i;
4390
4391     if (!term->pre_bidi_cache)
4392         return FALSE;                  /* cache doesn't even exist yet! */
4393
4394     if (line >= term->bidi_cache_size)
4395         return FALSE;                  /* cache doesn't have this many lines */
4396
4397     if (!term->pre_bidi_cache[line].chars)
4398         return FALSE;                  /* cache doesn't contain _this_ line */
4399
4400     if (term->pre_bidi_cache[line].width != width)
4401         return FALSE;                  /* line is wrong width */
4402
4403     for (i = 0; i < width; i++)
4404         if (!termchars_equal(term->pre_bidi_cache[line].chars+i, lbefore+i))
4405             return FALSE;              /* line doesn't match cache */
4406
4407     return TRUE;                       /* it didn't match. */
4408 }
4409
4410 static void term_bidi_cache_store(Terminal *term, int line, termchar *lbefore,
4411                                   termchar *lafter, bidi_char *wcTo,
4412                                   int width, int size)
4413 {
4414     int i;
4415
4416     if (!term->pre_bidi_cache || term->bidi_cache_size <= line) {
4417         int j = term->bidi_cache_size;
4418         term->bidi_cache_size = line+1;
4419         term->pre_bidi_cache = sresize(term->pre_bidi_cache,
4420                                        term->bidi_cache_size,
4421                                        struct bidi_cache_entry);
4422         term->post_bidi_cache = sresize(term->post_bidi_cache,
4423                                         term->bidi_cache_size,
4424                                         struct bidi_cache_entry);
4425         while (j < term->bidi_cache_size) {
4426             term->pre_bidi_cache[j].chars =
4427                 term->post_bidi_cache[j].chars = NULL;
4428             term->pre_bidi_cache[j].width =
4429                 term->post_bidi_cache[j].width = -1;
4430             term->pre_bidi_cache[j].forward =
4431                 term->post_bidi_cache[j].forward = NULL;
4432             term->pre_bidi_cache[j].backward =
4433                 term->post_bidi_cache[j].backward = NULL;
4434             j++;
4435         }
4436     }
4437
4438     sfree(term->pre_bidi_cache[line].chars);
4439     sfree(term->post_bidi_cache[line].chars);
4440     sfree(term->post_bidi_cache[line].forward);
4441     sfree(term->post_bidi_cache[line].backward);
4442
4443     term->pre_bidi_cache[line].width = width;
4444     term->pre_bidi_cache[line].chars = snewn(size, termchar);
4445     term->post_bidi_cache[line].width = width;
4446     term->post_bidi_cache[line].chars = snewn(size, termchar);
4447     term->post_bidi_cache[line].forward = snewn(width, int);
4448     term->post_bidi_cache[line].backward = snewn(width, int);
4449
4450     memcpy(term->pre_bidi_cache[line].chars, lbefore, size * TSIZE);
4451     memcpy(term->post_bidi_cache[line].chars, lafter, size * TSIZE);
4452     memset(term->post_bidi_cache[line].forward, 0, width * sizeof(int));
4453     memset(term->post_bidi_cache[line].backward, 0, width * sizeof(int));
4454
4455     for (i = 0; i < width; i++) {
4456         int p = wcTo[i].index;
4457
4458         assert(0 <= p && p < width);
4459
4460         term->post_bidi_cache[line].backward[i] = p;
4461         term->post_bidi_cache[line].forward[p] = i;
4462     }
4463 }
4464
4465 /*
4466  * Prepare the bidi information for a screen line. Returns the
4467  * transformed list of termchars, or NULL if no transformation at
4468  * all took place (because bidi is disabled). If return was
4469  * non-NULL, auxiliary information such as the forward and reverse
4470  * mappings of permutation position are available in
4471  * term->post_bidi_cache[scr_y].*.
4472  */
4473 static termchar *term_bidi_line(Terminal *term, struct termline *ldata,
4474                                 int scr_y)
4475 {
4476     termchar *lchars;
4477     int it;
4478
4479     /* Do Arabic shaping and bidi. */
4480     if(!term->cfg.bidi || !term->cfg.arabicshaping) {
4481
4482         if (!term_bidi_cache_hit(term, scr_y, ldata->chars, term->cols)) {
4483
4484             if (term->wcFromTo_size < term->cols) {
4485                 term->wcFromTo_size = term->cols;
4486                 term->wcFrom = sresize(term->wcFrom, term->wcFromTo_size,
4487                                        bidi_char);
4488                 term->wcTo = sresize(term->wcTo, term->wcFromTo_size,
4489                                      bidi_char);
4490             }
4491
4492             for(it=0; it<term->cols ; it++)
4493             {
4494                 unsigned long uc = (ldata->chars[it].chr);
4495
4496                 switch (uc & CSET_MASK) {
4497                   case CSET_LINEDRW:
4498                     if (!term->cfg.rawcnp) {
4499                         uc = term->ucsdata->unitab_xterm[uc & 0xFF];
4500                         break;
4501                     }
4502                   case CSET_ASCII:
4503                     uc = term->ucsdata->unitab_line[uc & 0xFF];
4504                     break;
4505                   case CSET_SCOACS:
4506                     uc = term->ucsdata->unitab_scoacs[uc&0xFF];
4507                     break;
4508                 }
4509                 switch (uc & CSET_MASK) {
4510                   case CSET_ACP:
4511                     uc = term->ucsdata->unitab_font[uc & 0xFF];
4512                     break;
4513                   case CSET_OEMCP:
4514                     uc = term->ucsdata->unitab_oemcp[uc & 0xFF];
4515                     break;
4516                 }
4517
4518                 term->wcFrom[it].origwc = term->wcFrom[it].wc =
4519                     (wchar_t)uc;
4520                 term->wcFrom[it].index = it;
4521             }
4522
4523             if(!term->cfg.bidi)
4524                 do_bidi(term->wcFrom, term->cols);
4525
4526             /* this is saved iff done from inside the shaping */
4527             if(!term->cfg.bidi && term->cfg.arabicshaping)
4528                 for(it=0; it<term->cols; it++)
4529                     term->wcTo[it] = term->wcFrom[it];
4530
4531             if(!term->cfg.arabicshaping)
4532                 do_shape(term->wcFrom, term->wcTo, term->cols);
4533
4534             if (term->ltemp_size < ldata->size) {
4535                 term->ltemp_size = ldata->size;
4536                 term->ltemp = sresize(term->ltemp, term->ltemp_size,
4537                                       termchar);
4538             }
4539
4540             memcpy(term->ltemp, ldata->chars, ldata->size * TSIZE);
4541
4542             for(it=0; it<term->cols ; it++)
4543             {
4544                 term->ltemp[it] = ldata->chars[term->wcTo[it].index];
4545                 if (term->ltemp[it].cc_next)
4546                     term->ltemp[it].cc_next -=
4547                     it - term->wcTo[it].index;
4548
4549                 if (term->wcTo[it].origwc != term->wcTo[it].wc)
4550                     term->ltemp[it].chr = term->wcTo[it].wc;
4551             }
4552             term_bidi_cache_store(term, scr_y, ldata->chars,
4553                                   term->ltemp, term->wcTo,
4554                                   term->cols, ldata->size);
4555
4556             lchars = term->ltemp;
4557         } else {
4558             lchars = term->post_bidi_cache[scr_y].chars;
4559         }
4560     } else {
4561         lchars = NULL;
4562     }
4563
4564     return lchars;
4565 }
4566
4567 /*
4568  * Given a context, update the window. Out of paranoia, we don't
4569  * allow WM_PAINT responses to do scrolling optimisations.
4570  */
4571 static void do_paint(Terminal *term, Context ctx, int may_optimise)
4572 {
4573     int i, j, our_curs_y, our_curs_x;
4574     int rv, cursor;
4575     pos scrpos;
4576     wchar_t *ch;
4577     int chlen;
4578 #ifdef OPTIMISE_SCROLL
4579     struct scrollregion *sr;
4580 #endif /* OPTIMISE_SCROLL */
4581     termchar *newline;
4582
4583     chlen = 1024;
4584     ch = snewn(chlen, wchar_t);
4585
4586     newline = snewn(term->cols, termchar);
4587
4588     rv = (!term->rvideo ^ !term->in_vbell ? ATTR_REVERSE : 0);
4589
4590     /* Depends on:
4591      * screen array, disptop, scrtop,
4592      * selection, rv, 
4593      * cfg.blinkpc, blink_is_real, tblinker, 
4594      * curs.y, curs.x, cblinker, cfg.blink_cur, cursor_on, has_focus, wrapnext
4595      */
4596
4597     /* Has the cursor position or type changed ? */
4598     if (term->cursor_on) {
4599         if (term->has_focus) {
4600             if (term->cblinker || !term->cfg.blink_cur)
4601                 cursor = TATTR_ACTCURS;
4602             else
4603                 cursor = 0;
4604         } else
4605             cursor = TATTR_PASCURS;
4606         if (term->wrapnext)
4607             cursor |= TATTR_RIGHTCURS;
4608     } else
4609         cursor = 0;
4610     our_curs_y = term->curs.y - term->disptop;
4611     {
4612         /*
4613          * Adjust the cursor position:
4614          *  - for bidi
4615          *  - in the case where it's resting on the right-hand half
4616          *    of a CJK wide character. xterm's behaviour here,
4617          *    which seems adequate to me, is to display the cursor
4618          *    covering the _whole_ character, exactly as if it were
4619          *    one space to the left.
4620          */
4621         termline *ldata = lineptr(term->curs.y);
4622         termchar *lchars;
4623
4624         our_curs_x = term->curs.x;
4625
4626         if ( (lchars = term_bidi_line(term, ldata, our_curs_y)) != NULL) {
4627             our_curs_x = term->post_bidi_cache[our_curs_y].forward[our_curs_x];
4628         } else
4629             lchars = ldata->chars;
4630
4631         if (our_curs_x > 0 &&
4632             lchars[our_curs_x].chr == UCSWIDE)
4633             our_curs_x--;
4634
4635         unlineptr(ldata);
4636     }
4637
4638     /*
4639      * If the cursor is not where it was last time we painted, and
4640      * its previous position is visible on screen, invalidate its
4641      * previous position.
4642      */
4643     if (term->dispcursy >= 0 &&
4644         (term->curstype != cursor ||
4645          term->dispcursy != our_curs_y ||
4646          term->dispcursx != our_curs_x)) {
4647         termchar *dispcurs = term->disptext[term->dispcursy]->chars +
4648             term->dispcursx;
4649
4650         if (term->dispcursx > 0 && dispcurs->chr == UCSWIDE)
4651             dispcurs[-1].attr |= ATTR_INVALID;
4652         if (term->dispcursx < term->cols-1 && dispcurs[1].chr == UCSWIDE)
4653             dispcurs[1].attr |= ATTR_INVALID;
4654         dispcurs->attr |= ATTR_INVALID;
4655
4656         term->curstype = 0;
4657     }
4658     term->dispcursx = term->dispcursy = -1;
4659
4660 #ifdef OPTIMISE_SCROLL
4661     /* Do scrolls */
4662     sr = term->scrollhead;
4663     while (sr) {
4664         struct scrollregion *next = sr->next;
4665         do_scroll(ctx, sr->topline, sr->botline, sr->lines);
4666         sfree(sr);
4667         sr = next;
4668     }
4669     term->scrollhead = term->scrolltail = NULL;
4670 #endif /* OPTIMISE_SCROLL */
4671
4672     /* The normal screen data */
4673     for (i = 0; i < term->rows; i++) {
4674         termline *ldata;
4675         termchar *lchars;
4676         int dirty_line, dirty_run, selected;
4677         unsigned long attr = 0, cset = 0;
4678         int updated_line = 0;
4679         int start = 0;
4680         int ccount = 0;
4681         int last_run_dirty = 0;
4682         int laststart, dirtyrect;
4683         int *backward;
4684
4685         scrpos.y = i + term->disptop;
4686         ldata = lineptr(scrpos.y);
4687
4688         /* Do Arabic shaping and bidi. */
4689         lchars = term_bidi_line(term, ldata, i);
4690         if (lchars) {
4691             backward = term->post_bidi_cache[i].backward;
4692         } else {
4693             lchars = ldata->chars;
4694             backward = NULL;
4695         }
4696
4697         /*
4698          * First loop: work along the line deciding what we want
4699          * each character cell to look like.
4700          */
4701         for (j = 0; j < term->cols; j++) {
4702             unsigned long tattr, tchar;
4703             termchar *d = lchars + j;
4704             scrpos.x = backward ? backward[j] : j;
4705
4706             tchar = d->chr;
4707             tattr = d->attr;
4708
4709             if (!term->cfg.ansi_colour)
4710                 tattr = (tattr & ~(ATTR_FGMASK | ATTR_BGMASK)) | 
4711                 ATTR_DEFFG | ATTR_DEFBG;
4712
4713             if (!term->cfg.xterm_256_colour) {
4714                 int colour;
4715                 colour = (tattr & ATTR_FGMASK) >> ATTR_FGSHIFT;
4716                 if (colour >= 16 && colour < 256)
4717                     tattr = (tattr &~ ATTR_FGMASK) | ATTR_DEFFG;
4718                 colour = (tattr & ATTR_BGMASK) >> ATTR_BGSHIFT;
4719                 if (colour >= 16 && colour < 256)
4720                     tattr = (tattr &~ ATTR_BGMASK) | ATTR_DEFBG;
4721             }
4722
4723             switch (tchar & CSET_MASK) {
4724               case CSET_ASCII:
4725                 tchar = term->ucsdata->unitab_line[tchar & 0xFF];
4726                 break;
4727               case CSET_LINEDRW:
4728                 tchar = term->ucsdata->unitab_xterm[tchar & 0xFF];
4729                 break;
4730               case CSET_SCOACS:  
4731                 tchar = term->ucsdata->unitab_scoacs[tchar&0xFF]; 
4732                 break;
4733             }
4734             if (j < term->cols-1 && d[1].chr == UCSWIDE)
4735                 tattr |= ATTR_WIDE;
4736
4737             /* Video reversing things */
4738             if (term->selstate == DRAGGING || term->selstate == SELECTED) {
4739                 if (term->seltype == LEXICOGRAPHIC)
4740                     selected = (posle(term->selstart, scrpos) &&
4741                                 poslt(scrpos, term->selend));
4742                 else
4743                     selected = (posPle(term->selstart, scrpos) &&
4744                                 posPlt(scrpos, term->selend));
4745             } else
4746                 selected = FALSE;
4747             tattr = (tattr ^ rv
4748                      ^ (selected ? ATTR_REVERSE : 0));
4749
4750             /* 'Real' blinking ? */
4751             if (term->blink_is_real && (tattr & ATTR_BLINK)) {
4752                 if (term->has_focus && term->tblinker) {
4753                     tchar = term->ucsdata->unitab_line[(unsigned char)' '];
4754                 }
4755                 tattr &= ~ATTR_BLINK;
4756             }
4757
4758             /*
4759              * Check the font we'll _probably_ be using to see if 
4760              * the character is wide when we don't want it to be.
4761              */
4762             if (tchar != term->disptext[i]->chars[j].chr ||
4763                 tattr != (term->disptext[i]->chars[j].attr &~
4764                           (ATTR_NARROW | DATTR_MASK))) {
4765                 if ((tattr & ATTR_WIDE) == 0 && char_width(ctx, tchar) == 2)
4766                     tattr |= ATTR_NARROW;
4767             } else if (term->disptext[i]->chars[j].attr & ATTR_NARROW)
4768                 tattr |= ATTR_NARROW;
4769
4770             if (i == our_curs_y && j == our_curs_x) {
4771                 tattr |= cursor;
4772                 term->curstype = cursor;
4773                 term->dispcursx = j;
4774                 term->dispcursy = i;
4775             }
4776
4777             /* FULL-TERMCHAR */
4778             newline[j].attr = tattr;
4779             newline[j].chr = tchar;
4780             /* Combining characters are still read from lchars */
4781             newline[j].cc_next = 0;
4782         }
4783
4784         /*
4785          * Now loop over the line again, noting where things have
4786          * changed.
4787          * 
4788          * During this loop, we keep track of where we last saw
4789          * DATTR_STARTRUN. Any mismatch automatically invalidates
4790          * _all_ of the containing run that was last printed: that
4791          * is, any rectangle that was drawn in one go in the
4792          * previous update should be either left completely alone
4793          * or overwritten in its entirety. This, along with the
4794          * expectation that front ends clip all text runs to their
4795          * bounding rectangle, should solve any possible problems
4796          * with fonts that overflow their character cells.
4797          */
4798         laststart = 0;
4799         dirtyrect = FALSE;
4800         for (j = 0; j < term->cols; j++) {
4801             if (term->disptext[i]->chars[j].attr & DATTR_STARTRUN) {
4802                 laststart = j;
4803                 dirtyrect = FALSE;
4804             }
4805
4806             if (term->disptext[i]->chars[j].chr != newline[j].chr ||
4807                 (term->disptext[i]->chars[j].attr &~ DATTR_MASK)
4808                 != newline[j].attr) {
4809                 int k;
4810
4811                 for (k = laststart; k < j; k++)
4812                     term->disptext[i]->chars[k].attr |= ATTR_INVALID;
4813
4814                 dirtyrect = TRUE;
4815             }
4816
4817             if (dirtyrect)
4818                 term->disptext[i]->chars[j].attr |= ATTR_INVALID;
4819         }
4820
4821         /*
4822          * Finally, loop once more and actually do the drawing.
4823          */
4824         dirty_run = dirty_line = (ldata->lattr !=
4825                                   term->disptext[i]->lattr);
4826         term->disptext[i]->lattr = ldata->lattr;
4827
4828         for (j = 0; j < term->cols; j++) {
4829             unsigned long tattr, tchar;
4830             int break_run, do_copy;
4831             termchar *d = lchars + j;
4832
4833             tattr = newline[j].attr;
4834             tchar = newline[j].chr;
4835
4836             if ((term->disptext[i]->chars[j].attr ^ tattr) & ATTR_WIDE)
4837                 dirty_line = TRUE;
4838
4839             break_run = ((tattr ^ attr) & term->attr_mask) != 0;
4840
4841             /* Special hack for VT100 Linedraw glyphs */
4842             if (tchar >= 0x23BA && tchar <= 0x23BD)
4843                 break_run = TRUE;
4844
4845             /*
4846              * Separate out sequences of characters that have the
4847              * same CSET, if that CSET is a magic one.
4848              */
4849             if (CSET_OF(tchar) != cset)
4850                 break_run = TRUE;
4851
4852             /*
4853              * Break on both sides of any combined-character cell.
4854              */
4855             if (d->cc_next != 0 ||
4856                 (j > 0 && d[-1].cc_next != 0))
4857                 break_run = TRUE;
4858
4859             if (!term->ucsdata->dbcs_screenfont && !dirty_line) {
4860                 if (term->disptext[i]->chars[j].chr == tchar &&
4861                     (term->disptext[i]->chars[j].attr &~ DATTR_MASK) == tattr)
4862                     break_run = TRUE;
4863                 else if (!dirty_run && ccount == 1)
4864                     break_run = TRUE;
4865             }
4866
4867             if (break_run) {
4868                 if ((dirty_run || last_run_dirty) && ccount > 0) {
4869                     do_text(ctx, start, i, ch, ccount, attr,
4870                             ldata->lattr);
4871                     if (attr & (TATTR_ACTCURS | TATTR_PASCURS))
4872                         do_cursor(ctx, start, i, ch, ccount, attr,
4873                                   ldata->lattr);
4874
4875                     updated_line = 1;
4876                 }
4877                 start = j;
4878                 ccount = 0;
4879                 attr = tattr;
4880                 cset = CSET_OF(tchar);
4881                 if (term->ucsdata->dbcs_screenfont)
4882                     last_run_dirty = dirty_run;
4883                 dirty_run = dirty_line;
4884             }
4885
4886             do_copy = FALSE;
4887             if (!termchars_equal_override(&term->disptext[i]->chars[j],
4888                                           d, tchar, tattr)) {
4889                 do_copy = TRUE;
4890                 dirty_run = TRUE;
4891             }
4892
4893             if (ccount >= chlen) {
4894                 chlen = ccount + 256;
4895                 ch = sresize(ch, chlen, wchar_t);
4896             }
4897             ch[ccount++] = (wchar_t) tchar;
4898
4899             if (d->cc_next) {
4900                 termchar *dd = d;
4901
4902                 while (dd->cc_next) {
4903                     unsigned long schar;
4904
4905                     dd += dd->cc_next;
4906
4907                     schar = dd->chr;
4908                     switch (schar & CSET_MASK) {
4909                       case CSET_ASCII:
4910                         schar = term->ucsdata->unitab_line[schar & 0xFF];
4911                         break;
4912                       case CSET_LINEDRW:
4913                         schar = term->ucsdata->unitab_xterm[schar & 0xFF];
4914                         break;
4915                       case CSET_SCOACS:
4916                         schar = term->ucsdata->unitab_scoacs[schar&0xFF];
4917                         break;
4918                     }
4919
4920                     if (ccount >= chlen) {
4921                         chlen = ccount + 256;
4922                         ch = sresize(ch, chlen, wchar_t);
4923                     }
4924                     ch[ccount++] = (wchar_t) schar;
4925                 }
4926
4927                 attr |= TATTR_COMBINING;
4928             }
4929
4930             if (do_copy) {
4931                 copy_termchar(term->disptext[i], j, d);
4932                 term->disptext[i]->chars[j].chr = tchar;
4933                 term->disptext[i]->chars[j].attr = tattr;
4934                 if (start == j)
4935                     term->disptext[i]->chars[j].attr |= DATTR_STARTRUN;
4936             }
4937
4938             /* If it's a wide char step along to the next one. */
4939             if (tattr & ATTR_WIDE) {
4940                 if (++j < term->cols) {
4941                     d++;
4942                     /*
4943                      * By construction above, the cursor should not
4944                      * be on the right-hand half of this character.
4945                      * Ever.
4946                      */
4947                     assert(!(i == our_curs_y && j == our_curs_x));
4948                     if (!termchars_equal(&term->disptext[i]->chars[j], d))
4949                         dirty_run = TRUE;
4950                     copy_termchar(term->disptext[i], j, d);
4951                 }
4952             }
4953         }
4954         if (dirty_run && ccount > 0) {
4955             do_text(ctx, start, i, ch, ccount, attr,
4956                     ldata->lattr);
4957             if (attr & (TATTR_ACTCURS | TATTR_PASCURS))
4958                 do_cursor(ctx, start, i, ch, ccount, attr,
4959                           ldata->lattr);
4960
4961             updated_line = 1;
4962         }
4963
4964         unlineptr(ldata);
4965     }
4966
4967     sfree(newline);
4968     sfree(ch);
4969 }
4970
4971 /*
4972  * Invalidate the whole screen so it will be repainted in full.
4973  */
4974 void term_invalidate(Terminal *term)
4975 {
4976     int i, j;
4977
4978     for (i = 0; i < term->rows; i++)
4979         for (j = 0; j < term->cols; j++)
4980             term->disptext[i]->chars[j].attr |= ATTR_INVALID;
4981
4982     term_schedule_update(term);
4983 }
4984
4985 /*
4986  * Paint the window in response to a WM_PAINT message.
4987  */
4988 void term_paint(Terminal *term, Context ctx,
4989                 int left, int top, int right, int bottom, int immediately)
4990 {
4991     int i, j;
4992     if (left < 0) left = 0;
4993     if (top < 0) top = 0;
4994     if (right >= term->cols) right = term->cols-1;
4995     if (bottom >= term->rows) bottom = term->rows-1;
4996
4997     for (i = top; i <= bottom && i < term->rows; i++) {
4998         if ((term->disptext[i]->lattr & LATTR_MODE) == LATTR_NORM)
4999             for (j = left; j <= right && j < term->cols; j++)
5000                 term->disptext[i]->chars[j].attr |= ATTR_INVALID;
5001         else
5002             for (j = left / 2; j <= right / 2 + 1 && j < term->cols; j++)
5003                 term->disptext[i]->chars[j].attr |= ATTR_INVALID;
5004     }
5005
5006     if (immediately) {
5007         do_paint (term, ctx, FALSE);
5008     } else {
5009         term_schedule_update(term);
5010     }
5011 }
5012
5013 /*
5014  * Attempt to scroll the scrollback. The second parameter gives the
5015  * position we want to scroll to; the first is +1 to denote that
5016  * this position is relative to the beginning of the scrollback, -1
5017  * to denote it is relative to the end, and 0 to denote that it is
5018  * relative to the current position.
5019  */
5020 void term_scroll(Terminal *term, int rel, int where)
5021 {
5022     int sbtop = -sblines(term);
5023 #ifdef OPTIMISE_SCROLL
5024     int olddisptop = term->disptop;
5025     int shift;
5026 #endif /* OPTIMISE_SCROLL */
5027
5028     term->disptop = (rel < 0 ? 0 : rel > 0 ? sbtop : term->disptop) + where;
5029     if (term->disptop < sbtop)
5030         term->disptop = sbtop;
5031     if (term->disptop > 0)
5032         term->disptop = 0;
5033     update_sbar(term);
5034 #ifdef OPTIMISE_SCROLL
5035     shift = (term->disptop - olddisptop);
5036     if (shift < term->rows && shift > -term->rows)
5037         scroll_display(term, 0, term->rows - 1, shift);
5038 #endif /* OPTIMISE_SCROLL */
5039     term_update(term);
5040 }
5041
5042 static void clipme(Terminal *term, pos top, pos bottom, int rect, int desel)
5043 {
5044     wchar_t *workbuf;
5045     wchar_t *wbptr;                    /* where next char goes within workbuf */
5046     int old_top_x;
5047     int wblen = 0;                     /* workbuf len */
5048     int buflen;                        /* amount of memory allocated to workbuf */
5049
5050     buflen = 5120;                     /* Default size */
5051     workbuf = snewn(buflen, wchar_t);
5052     wbptr = workbuf;                   /* start filling here */
5053     old_top_x = top.x;                 /* needed for rect==1 */
5054
5055     while (poslt(top, bottom)) {
5056         int nl = FALSE;
5057         termline *ldata = lineptr(top.y);
5058         pos nlpos;
5059
5060         /*
5061          * nlpos will point at the maximum position on this line we
5062          * should copy up to. So we start it at the end of the
5063          * line...
5064          */
5065         nlpos.y = top.y;
5066         nlpos.x = term->cols;
5067
5068         /*
5069          * ... move it backwards if there's unused space at the end
5070          * of the line (and also set `nl' if this is the case,
5071          * because in normal selection mode this means we need a
5072          * newline at the end)...
5073          */
5074         if (!(ldata->lattr & LATTR_WRAPPED)) {
5075             while (IS_SPACE_CHR(ldata->chars[nlpos.x - 1].chr) &&
5076                    !ldata->chars[nlpos.x - 1].cc_next &&
5077                    poslt(top, nlpos))
5078                 decpos(nlpos);
5079             if (poslt(nlpos, bottom))
5080                 nl = TRUE;
5081         } else if (ldata->lattr & LATTR_WRAPPED2) {
5082             /* Ignore the last char on the line in a WRAPPED2 line. */
5083             decpos(nlpos);
5084         }
5085
5086         /*
5087          * ... and then clip it to the terminal x coordinate if
5088          * we're doing rectangular selection. (In this case we
5089          * still did the above, so that copying e.g. the right-hand
5090          * column from a table doesn't fill with spaces on the
5091          * right.)
5092          */
5093         if (rect) {
5094             if (nlpos.x > bottom.x)
5095                 nlpos.x = bottom.x;
5096             nl = (top.y < bottom.y);
5097         }
5098
5099         while (poslt(top, bottom) && poslt(top, nlpos)) {
5100 #if 0
5101             char cbuf[16], *p;
5102             sprintf(cbuf, "<U+%04x>", (ldata[top.x] & 0xFFFF));
5103 #else
5104             wchar_t cbuf[16], *p;
5105             int set, c;
5106             int x = top.x;
5107
5108             if (ldata->chars[x].chr == UCSWIDE) {
5109                 top.x++;
5110                 continue;
5111             }
5112
5113             while (1) {
5114                 int uc = ldata->chars[x].chr;
5115
5116                 switch (uc & CSET_MASK) {
5117                   case CSET_LINEDRW:
5118                     if (!term->cfg.rawcnp) {
5119                         uc = term->ucsdata->unitab_xterm[uc & 0xFF];
5120                         break;
5121                     }
5122                   case CSET_ASCII:
5123                     uc = term->ucsdata->unitab_line[uc & 0xFF];
5124                     break;
5125                   case CSET_SCOACS:
5126                     uc = term->ucsdata->unitab_scoacs[uc&0xFF];
5127                     break;
5128                 }
5129                 switch (uc & CSET_MASK) {
5130                   case CSET_ACP:
5131                     uc = term->ucsdata->unitab_font[uc & 0xFF];
5132                     break;
5133                   case CSET_OEMCP:
5134                     uc = term->ucsdata->unitab_oemcp[uc & 0xFF];
5135                     break;
5136                 }
5137
5138                 set = (uc & CSET_MASK);
5139                 c = (uc & ~CSET_MASK);
5140                 cbuf[0] = uc;
5141                 cbuf[1] = 0;
5142
5143                 if (DIRECT_FONT(uc)) {
5144                     if (c >= ' ' && c != 0x7F) {
5145                         char buf[4];
5146                         WCHAR wbuf[4];
5147                         int rv;
5148                         if (is_dbcs_leadbyte(term->ucsdata->font_codepage, (BYTE) c)) {
5149                             buf[0] = c;
5150                             buf[1] = (char) (0xFF & ldata->chars[top.x + 1].chr);
5151                             rv = mb_to_wc(term->ucsdata->font_codepage, 0, buf, 2, wbuf, 4);
5152                             top.x++;
5153                         } else {
5154                             buf[0] = c;
5155                             rv = mb_to_wc(term->ucsdata->font_codepage, 0, buf, 1, wbuf, 4);
5156                         }
5157
5158                         if (rv > 0) {
5159                             memcpy(cbuf, wbuf, rv * sizeof(wchar_t));
5160                             cbuf[rv] = 0;
5161                         }
5162                     }
5163                 }
5164 #endif
5165
5166                 for (p = cbuf; *p; p++) {
5167                     /* Enough overhead for trailing NL and nul */
5168                     if (wblen >= buflen - 16) {
5169                         buflen += 100;
5170                         workbuf = sresize(workbuf, buflen, wchar_t);
5171                         wbptr = workbuf + wblen;
5172                     }
5173                     wblen++;
5174                     *wbptr++ = *p;
5175                 }
5176
5177                 if (ldata->chars[x].cc_next)
5178                     x += ldata->chars[x].cc_next;
5179                 else
5180                     break;
5181             }
5182             top.x++;
5183         }
5184         if (nl) {
5185             int i;
5186             for (i = 0; i < sel_nl_sz; i++) {
5187                 wblen++;
5188                 *wbptr++ = sel_nl[i];
5189             }
5190         }
5191         top.y++;
5192         top.x = rect ? old_top_x : 0;
5193
5194         unlineptr(ldata);
5195     }
5196 #if SELECTION_NUL_TERMINATED
5197     wblen++;
5198     *wbptr++ = 0;
5199 #endif
5200     write_clip(term->frontend, workbuf, wblen, desel); /* transfer to clipbd */
5201     if (buflen > 0)                    /* indicates we allocated this buffer */
5202         sfree(workbuf);
5203 }
5204
5205 void term_copyall(Terminal *term)
5206 {
5207     pos top;
5208     pos bottom;
5209     tree234 *screen = term->screen;
5210     top.y = -sblines(term);
5211     top.x = 0;
5212     bottom.y = find_last_nonempty_line(term, screen);
5213     bottom.x = term->cols;
5214     clipme(term, top, bottom, 0, TRUE);
5215 }
5216
5217 /*
5218  * The wordness array is mainly for deciding the disposition of the
5219  * US-ASCII characters.
5220  */
5221 static int wordtype(Terminal *term, int uc)
5222 {
5223     struct ucsword {
5224         int start, end, ctype;
5225     };
5226     static const struct ucsword ucs_words[] = {
5227         {
5228         128, 160, 0}, {
5229         161, 191, 1}, {
5230         215, 215, 1}, {
5231         247, 247, 1}, {
5232         0x037e, 0x037e, 1},            /* Greek question mark */
5233         {
5234         0x0387, 0x0387, 1},            /* Greek ano teleia */
5235         {
5236         0x055a, 0x055f, 1},            /* Armenian punctuation */
5237         {
5238         0x0589, 0x0589, 1},            /* Armenian full stop */
5239         {
5240         0x0700, 0x070d, 1},            /* Syriac punctuation */
5241         {
5242         0x104a, 0x104f, 1},            /* Myanmar punctuation */
5243         {
5244         0x10fb, 0x10fb, 1},            /* Georgian punctuation */
5245         {
5246         0x1361, 0x1368, 1},            /* Ethiopic punctuation */
5247         {
5248         0x166d, 0x166e, 1},            /* Canadian Syl. punctuation */
5249         {
5250         0x17d4, 0x17dc, 1},            /* Khmer punctuation */
5251         {
5252         0x1800, 0x180a, 1},            /* Mongolian punctuation */
5253         {
5254         0x2000, 0x200a, 0},            /* Various spaces */
5255         {
5256         0x2070, 0x207f, 2},            /* superscript */
5257         {
5258         0x2080, 0x208f, 2},            /* subscript */
5259         {
5260         0x200b, 0x27ff, 1},            /* punctuation and symbols */
5261         {
5262         0x3000, 0x3000, 0},            /* ideographic space */
5263         {
5264         0x3001, 0x3020, 1},            /* ideographic punctuation */
5265         {
5266         0x303f, 0x309f, 3},            /* Hiragana */
5267         {
5268         0x30a0, 0x30ff, 3},            /* Katakana */
5269         {
5270         0x3300, 0x9fff, 3},            /* CJK Ideographs */
5271         {
5272         0xac00, 0xd7a3, 3},            /* Hangul Syllables */
5273         {
5274         0xf900, 0xfaff, 3},            /* CJK Ideographs */
5275         {
5276         0xfe30, 0xfe6b, 1},            /* punctuation forms */
5277         {
5278         0xff00, 0xff0f, 1},            /* half/fullwidth ASCII */
5279         {
5280         0xff1a, 0xff20, 1},            /* half/fullwidth ASCII */
5281         {
5282         0xff3b, 0xff40, 1},            /* half/fullwidth ASCII */
5283         {
5284         0xff5b, 0xff64, 1},            /* half/fullwidth ASCII */
5285         {
5286         0xfff0, 0xffff, 0},            /* half/fullwidth ASCII */
5287         {
5288         0, 0, 0}
5289     };
5290     const struct ucsword *wptr;
5291
5292     switch (uc & CSET_MASK) {
5293       case CSET_LINEDRW:
5294         uc = term->ucsdata->unitab_xterm[uc & 0xFF];
5295         break;
5296       case CSET_ASCII:
5297         uc = term->ucsdata->unitab_line[uc & 0xFF];
5298         break;
5299       case CSET_SCOACS:  
5300         uc = term->ucsdata->unitab_scoacs[uc&0xFF]; 
5301         break;
5302     }
5303     switch (uc & CSET_MASK) {
5304       case CSET_ACP:
5305         uc = term->ucsdata->unitab_font[uc & 0xFF];
5306         break;
5307       case CSET_OEMCP:
5308         uc = term->ucsdata->unitab_oemcp[uc & 0xFF];
5309         break;
5310     }
5311
5312     /* For DBCS fonts I can't do anything useful. Even this will sometimes
5313      * fail as there's such a thing as a double width space. :-(
5314      */
5315     if (term->ucsdata->dbcs_screenfont &&
5316         term->ucsdata->font_codepage == term->ucsdata->line_codepage)
5317         return (uc != ' ');
5318
5319     if (uc < 0x80)
5320         return term->wordness[uc];
5321
5322     for (wptr = ucs_words; wptr->start; wptr++) {
5323         if (uc >= wptr->start && uc <= wptr->end)
5324             return wptr->ctype;
5325     }
5326
5327     return 2;
5328 }
5329
5330 /*
5331  * Spread the selection outwards according to the selection mode.
5332  */
5333 static pos sel_spread_half(Terminal *term, pos p, int dir)
5334 {
5335     termline *ldata;
5336     short wvalue;
5337     int topy = -sblines(term);
5338
5339     ldata = lineptr(p.y);
5340
5341     switch (term->selmode) {
5342       case SM_CHAR:
5343         /*
5344          * In this mode, every character is a separate unit, except
5345          * for runs of spaces at the end of a non-wrapping line.
5346          */
5347         if (!(ldata->lattr & LATTR_WRAPPED)) {
5348             termchar *q = ldata->chars + term->cols;
5349             while (q > ldata->chars &&
5350                    IS_SPACE_CHR(q[-1].chr) && !q[-1].cc_next)
5351                 q--;
5352             if (q == ldata->chars + term->cols)
5353                 q--;
5354             if (p.x >= q - ldata->chars)
5355                 p.x = (dir == -1 ? q - ldata->chars : term->cols - 1);
5356         }
5357         break;
5358       case SM_WORD:
5359         /*
5360          * In this mode, the units are maximal runs of characters
5361          * whose `wordness' has the same value.
5362          */
5363         wvalue = wordtype(term, UCSGET(ldata->chars, p.x));
5364         if (dir == +1) {
5365             while (1) {
5366                 int maxcols = (ldata->lattr & LATTR_WRAPPED2 ?
5367                                term->cols-1 : term->cols);
5368                 if (p.x < maxcols-1) {
5369                     if (wordtype(term, UCSGET(ldata->chars, p.x+1)) == wvalue)
5370                         p.x++;
5371                     else
5372                         break;
5373                 } else {
5374                     if (ldata->lattr & LATTR_WRAPPED) {
5375                         termline *ldata2;
5376                         ldata2 = lineptr(p.y+1);
5377                         if (wordtype(term, UCSGET(ldata2->chars, 0))
5378                             == wvalue) {
5379                             p.x = 0;
5380                             p.y++;
5381                             unlineptr(ldata);
5382                             ldata = ldata2;
5383                         } else {
5384                             unlineptr(ldata2);
5385                             break;
5386                         }
5387                     } else
5388                         break;
5389                 }
5390             }
5391         } else {
5392             while (1) {
5393                 if (p.x > 0) {
5394                     if (wordtype(term, UCSGET(ldata->chars, p.x-1)) == wvalue)
5395                         p.x--;
5396                     else
5397                         break;
5398                 } else {
5399                     termline *ldata2;
5400                     int maxcols;
5401                     if (p.y <= topy)
5402                         break;
5403                     ldata2 = lineptr(p.y-1);
5404                     maxcols = (ldata2->lattr & LATTR_WRAPPED2 ?
5405                               term->cols-1 : term->cols);
5406                     if (ldata2->lattr & LATTR_WRAPPED) {
5407                         if (wordtype(term, UCSGET(ldata2->chars, maxcols-1))
5408                             == wvalue) {
5409                             p.x = maxcols-1;
5410                             p.y--;
5411                             unlineptr(ldata);
5412                             ldata = ldata2;
5413                         } else {
5414                             unlineptr(ldata2);
5415                             break;
5416                         }
5417                     } else
5418                         break;
5419                 }
5420             }
5421         }
5422         break;
5423       case SM_LINE:
5424         /*
5425          * In this mode, every line is a unit.
5426          */
5427         p.x = (dir == -1 ? 0 : term->cols - 1);
5428         break;
5429     }
5430
5431     unlineptr(ldata);
5432     return p;
5433 }
5434
5435 static void sel_spread(Terminal *term)
5436 {
5437     if (term->seltype == LEXICOGRAPHIC) {
5438         term->selstart = sel_spread_half(term, term->selstart, -1);
5439         decpos(term->selend);
5440         term->selend = sel_spread_half(term, term->selend, +1);
5441         incpos(term->selend);
5442     }
5443 }
5444
5445 void term_do_paste(Terminal *term)
5446 {
5447     wchar_t *data;
5448     int len;
5449
5450     get_clip(term->frontend, &data, &len);
5451     if (data && len > 0) {
5452         wchar_t *p, *q;
5453
5454         term_seen_key_event(term);     /* pasted data counts */
5455
5456         if (term->paste_buffer)
5457             sfree(term->paste_buffer);
5458         term->paste_pos = term->paste_hold = term->paste_len = 0;
5459         term->paste_buffer = snewn(len, wchar_t);
5460
5461         p = q = data;
5462         while (p < data + len) {
5463             while (p < data + len &&
5464                    !(p <= data + len - sel_nl_sz &&
5465                      !memcmp(p, sel_nl, sizeof(sel_nl))))
5466                 p++;
5467
5468             {
5469                 int i;
5470                 for (i = 0; i < p - q; i++) {
5471                     term->paste_buffer[term->paste_len++] = q[i];
5472                 }
5473             }
5474
5475             if (p <= data + len - sel_nl_sz &&
5476                 !memcmp(p, sel_nl, sizeof(sel_nl))) {
5477                 term->paste_buffer[term->paste_len++] = '\015';
5478                 p += sel_nl_sz;
5479             }
5480             q = p;
5481         }
5482
5483         /* Assume a small paste will be OK in one go. */
5484         if (term->paste_len < 256) {
5485             if (term->ldisc)
5486                 luni_send(term->ldisc, term->paste_buffer, term->paste_len, 0);
5487             if (term->paste_buffer)
5488                 sfree(term->paste_buffer);
5489             term->paste_buffer = 0;
5490             term->paste_pos = term->paste_hold = term->paste_len = 0;
5491         }
5492     }
5493     get_clip(term->frontend, NULL, NULL);
5494 }
5495
5496 void term_mouse(Terminal *term, Mouse_Button braw, Mouse_Button bcooked,
5497                 Mouse_Action a, int x, int y, int shift, int ctrl, int alt)
5498 {
5499     pos selpoint;
5500     termline *ldata;
5501     int raw_mouse = (term->xterm_mouse &&
5502                      !term->cfg.no_mouse_rep &&
5503                      !(term->cfg.mouse_override && shift));
5504     int default_seltype;
5505
5506     if (y < 0) {
5507         y = 0;
5508         if (a == MA_DRAG && !raw_mouse)
5509             term_scroll(term, 0, -1);
5510     }
5511     if (y >= term->rows) {
5512         y = term->rows - 1;
5513         if (a == MA_DRAG && !raw_mouse)
5514             term_scroll(term, 0, +1);
5515     }
5516     if (x < 0) {
5517         if (y > 0) {
5518             x = term->cols - 1;
5519             y--;
5520         } else
5521             x = 0;
5522     }
5523     if (x >= term->cols)
5524         x = term->cols - 1;
5525
5526     selpoint.y = y + term->disptop;
5527     ldata = lineptr(selpoint.y);
5528
5529     if ((ldata->lattr & LATTR_MODE) != LATTR_NORM)
5530         x /= 2;
5531
5532     /*
5533      * Transform x through the bidi algorithm to find the _logical_
5534      * click point from the physical one.
5535      */
5536     if (term_bidi_line(term, ldata, y) != NULL) {
5537         x = term->post_bidi_cache[y].backward[x];
5538     }
5539
5540     selpoint.x = x;
5541     unlineptr(ldata);
5542
5543     if (raw_mouse) {
5544         int encstate = 0, r, c;
5545         char abuf[16];
5546
5547         if (term->ldisc) {
5548
5549             switch (braw) {
5550               case MBT_LEFT:
5551                 encstate = 0x20;               /* left button down */
5552                 break;
5553               case MBT_MIDDLE:
5554                 encstate = 0x21;
5555                 break;
5556               case MBT_RIGHT:
5557                 encstate = 0x22;
5558                 break;
5559               case MBT_WHEEL_UP:
5560                 encstate = 0x60;
5561                 break;
5562               case MBT_WHEEL_DOWN:
5563                 encstate = 0x61;
5564                 break;
5565               default: break;          /* placate gcc warning about enum use */
5566             }
5567             switch (a) {
5568               case MA_DRAG:
5569                 if (term->xterm_mouse == 1)
5570                     return;
5571                 encstate += 0x20;
5572                 break;
5573               case MA_RELEASE:
5574                 encstate = 0x23;
5575                 term->mouse_is_down = 0;
5576                 break;
5577               case MA_CLICK:
5578                 if (term->mouse_is_down == braw)
5579                     return;
5580                 term->mouse_is_down = braw;
5581                 break;
5582               default: break;          /* placate gcc warning about enum use */
5583             }
5584             if (shift)
5585                 encstate += 0x04;
5586             if (ctrl)
5587                 encstate += 0x10;
5588             r = y + 33;
5589             c = x + 33;
5590
5591             sprintf(abuf, "\033[M%c%c%c", encstate, c, r);
5592             ldisc_send(term->ldisc, abuf, 6, 0);
5593         }
5594         return;
5595     }
5596
5597     /*
5598      * Set the selection type (rectangular or normal) at the start
5599      * of a selection attempt, from the state of Alt.
5600      */
5601     if (!alt ^ !term->cfg.rect_select)
5602         default_seltype = RECTANGULAR;
5603     else
5604         default_seltype = LEXICOGRAPHIC;
5605         
5606     if (term->selstate == NO_SELECTION) {
5607         term->seltype = default_seltype;
5608     }
5609
5610     if (bcooked == MBT_SELECT && a == MA_CLICK) {
5611         deselect(term);
5612         term->selstate = ABOUT_TO;
5613         term->seltype = default_seltype;
5614         term->selanchor = selpoint;
5615         term->selmode = SM_CHAR;
5616     } else if (bcooked == MBT_SELECT && (a == MA_2CLK || a == MA_3CLK)) {
5617         deselect(term);
5618         term->selmode = (a == MA_2CLK ? SM_WORD : SM_LINE);
5619         term->selstate = DRAGGING;
5620         term->selstart = term->selanchor = selpoint;
5621         term->selend = term->selstart;
5622         incpos(term->selend);
5623         sel_spread(term);
5624     } else if ((bcooked == MBT_SELECT && a == MA_DRAG) ||
5625                (bcooked == MBT_EXTEND && a != MA_RELEASE)) {
5626         if (term->selstate == ABOUT_TO && poseq(term->selanchor, selpoint))
5627             return;
5628         if (bcooked == MBT_EXTEND && a != MA_DRAG &&
5629             term->selstate == SELECTED) {
5630             if (term->seltype == LEXICOGRAPHIC) {
5631                 /*
5632                  * For normal selection, we extend by moving
5633                  * whichever end of the current selection is closer
5634                  * to the mouse.
5635                  */
5636                 if (posdiff(selpoint, term->selstart) <
5637                     posdiff(term->selend, term->selstart) / 2) {
5638                     term->selanchor = term->selend;
5639                     decpos(term->selanchor);
5640                 } else {
5641                     term->selanchor = term->selstart;
5642                 }
5643             } else {
5644                 /*
5645                  * For rectangular selection, we have a choice of
5646                  * _four_ places to put selanchor and selpoint: the
5647                  * four corners of the selection.
5648                  */
5649                 if (2*selpoint.x < term->selstart.x + term->selend.x)
5650                     term->selanchor.x = term->selend.x-1;
5651                 else
5652                     term->selanchor.x = term->selstart.x;
5653
5654                 if (2*selpoint.y < term->selstart.y + term->selend.y)
5655                     term->selanchor.y = term->selend.y;
5656                 else
5657                     term->selanchor.y = term->selstart.y;
5658             }
5659             term->selstate = DRAGGING;
5660         }
5661         if (term->selstate != ABOUT_TO && term->selstate != DRAGGING)
5662             term->selanchor = selpoint;
5663         term->selstate = DRAGGING;
5664         if (term->seltype == LEXICOGRAPHIC) {
5665             /*
5666              * For normal selection, we set (selstart,selend) to
5667              * (selpoint,selanchor) in some order.
5668              */
5669             if (poslt(selpoint, term->selanchor)) {
5670                 term->selstart = selpoint;
5671                 term->selend = term->selanchor;
5672                 incpos(term->selend);
5673             } else {
5674                 term->selstart = term->selanchor;
5675                 term->selend = selpoint;
5676                 incpos(term->selend);
5677             }
5678         } else {
5679             /*
5680              * For rectangular selection, we may need to
5681              * interchange x and y coordinates (if the user has
5682              * dragged in the -x and +y directions, or vice versa).
5683              */
5684             term->selstart.x = min(term->selanchor.x, selpoint.x);
5685             term->selend.x = 1+max(term->selanchor.x, selpoint.x);
5686             term->selstart.y = min(term->selanchor.y, selpoint.y);
5687             term->selend.y =   max(term->selanchor.y, selpoint.y);
5688         }
5689         sel_spread(term);
5690     } else if ((bcooked == MBT_SELECT || bcooked == MBT_EXTEND) &&
5691                a == MA_RELEASE) {
5692         if (term->selstate == DRAGGING) {
5693             /*
5694              * We've completed a selection. We now transfer the
5695              * data to the clipboard.
5696              */
5697             clipme(term, term->selstart, term->selend,
5698                    (term->seltype == RECTANGULAR), FALSE);
5699             term->selstate = SELECTED;
5700         } else
5701             term->selstate = NO_SELECTION;
5702     } else if (bcooked == MBT_PASTE
5703                && (a == MA_CLICK
5704 #if MULTICLICK_ONLY_EVENT
5705                    || a == MA_2CLK || a == MA_3CLK
5706 #endif
5707                    )) {
5708         request_paste(term->frontend);
5709     }
5710
5711     term_update(term);
5712 }
5713
5714 void term_key(Terminal *term, Key_Sym keysym, wchar_t *text, size_t tlen,
5715               unsigned int modifiers, unsigned int flags)
5716 {
5717     char output[10];
5718     char *p = output;
5719     int prependesc = FALSE;
5720 #if 0
5721     int i;
5722
5723     fprintf(stderr, "keysym = %d, %d chars:", keysym, tlen);
5724     for (i = 0; i < tlen; i++)
5725         fprintf(stderr, " %04x", (unsigned)text[i]);
5726     fprintf(stderr, "\n");
5727 #endif
5728
5729     /* XXX Num Lock */
5730     if ((flags & PKF_REPEAT) && term->repeat_off)
5731         return;
5732
5733     /* Currently, Meta always just prefixes everything with ESC. */
5734     if (modifiers & PKM_META)
5735         prependesc = TRUE;
5736     modifiers &= ~PKM_META;
5737
5738     /*
5739      * Alt is only used for Alt+keypad, which isn't supported yet, so
5740      * ignore it.
5741      */
5742     modifiers &= ~PKM_ALT;
5743
5744     /* Standard local function keys */
5745     switch (modifiers & (PKM_SHIFT | PKM_CONTROL)) {
5746       case PKM_SHIFT:
5747         if (keysym == PK_PAGEUP)
5748             /* scroll up one page */;
5749         if (keysym == PK_PAGEDOWN)
5750             /* scroll down on page */;
5751         if (keysym == PK_INSERT)
5752             term_do_paste(term);
5753         break;
5754       case PKM_CONTROL:
5755         if (keysym == PK_PAGEUP)
5756             /* scroll up one line */;
5757         if (keysym == PK_PAGEDOWN)
5758             /* scroll down one line */;
5759         /* Control-Numlock for app-keypad mode switch */
5760         if (keysym == PK_PF1)
5761             term->app_keypad_keys ^= 1;
5762         break;
5763     }
5764
5765     if (modifiers & PKM_ALT) {
5766         /* Alt+F4 (close) */
5767         /* Alt+Return (full screen) */
5768         /* Alt+Space (system menu) */
5769     }
5770
5771     if (keysym == PK_NULL && (modifiers & PKM_CONTROL) && tlen == 1 &&
5772         text[0] >= 0x20 && text[0] <= 0x7e) {
5773         /* ASCII chars + Control */
5774         if ((text[0] >= 0x40 && text[0] <= 0x5f) ||
5775             (text[0] >= 0x61 && text[0] <= 0x7a))
5776             text[0] &= 0x1f;
5777         else {
5778             /*
5779              * Control-2 should return ^@ (0x00), Control-6 should return
5780              * ^^ (0x1E), and Control-Minus should return ^_ (0x1F). Since
5781              * the DOS keyboard handling did it, and we have nothing better
5782              * to do with the key combo in question, we'll also map
5783              * Control-Backquote to ^\ (0x1C).
5784              */
5785             switch (text[0]) {
5786               case ' ': text[0] = 0x00; break;
5787               case '-': text[0] = 0x1f; break;
5788               case '/': text[0] = 0x1f; break;
5789               case '2': text[0] = 0x00; break;
5790               case '3': text[0] = 0x1b; break;
5791               case '4': text[0] = 0x1c; break;
5792               case '5': text[0] = 0x1d; break;
5793               case '6': text[0] = 0x1e; break;
5794               case '7': text[0] = 0x1f; break;
5795               case '8': text[0] = 0x7f; break;
5796               case '`': text[0] = 0x1c; break;
5797             }
5798         }
5799     }
5800
5801     /* Nethack keypad */
5802     if (term->cfg.nethack_keypad) {
5803         char c = 0;
5804         switch (keysym) {
5805           case PK_KP1: c = 'b'; break;
5806           case PK_KP2: c = 'j'; break;
5807           case PK_KP3: c = 'n'; break;
5808           case PK_KP4: c = 'h'; break;
5809           case PK_KP5: c = '.'; break;
5810           case PK_KP6: c = 'l'; break;
5811           case PK_KP7: c = 'y'; break;
5812           case PK_KP8: c = 'k'; break;
5813           case PK_KP9: c = 'u'; break;
5814           default: break; /* else gcc warns `enum value not used' */
5815         }
5816         if (c != 0) {
5817             if (c != '.') {
5818                 if (modifiers & PKM_CONTROL)
5819                     c &= 0x1f;
5820                 else if (modifiers & PKM_SHIFT)
5821                     c = toupper(c);
5822             }
5823             *p++ = c;
5824             goto done;
5825         }
5826     }
5827
5828     /* Numeric Keypad */
5829     if (PK_ISKEYPAD(keysym)) {
5830         int xkey = 0;
5831
5832         /*
5833          * In VT400 mode, PFn always emits an escape sequence.  In
5834          * Linux and tilde modes, this only happens in app keypad mode.
5835          */
5836         if (term->cfg.funky_type == FUNKY_VT400 ||
5837             ((term->cfg.funky_type == FUNKY_LINUX ||
5838               term->cfg.funky_type == FUNKY_TILDE) &&
5839              term->app_keypad_keys && !term->cfg.no_applic_k)) {
5840             switch (keysym) {
5841               case PK_PF1: xkey = 'P'; break;
5842               case PK_PF2: xkey = 'Q'; break;
5843               case PK_PF3: xkey = 'R'; break;
5844               case PK_PF4: xkey = 'S'; break;
5845               default: break; /* else gcc warns `enum value not used' */
5846             }
5847         }
5848         if (term->app_keypad_keys && !term->cfg.no_applic_k) {
5849             switch (keysym) {
5850               case PK_KP0: xkey = 'p'; break;
5851               case PK_KP1: xkey = 'q'; break;
5852               case PK_KP2: xkey = 'r'; break;
5853               case PK_KP3: xkey = 's'; break;
5854               case PK_KP4: xkey = 't'; break;
5855               case PK_KP5: xkey = 'u'; break;
5856               case PK_KP6: xkey = 'v'; break;
5857               case PK_KP7: xkey = 'w'; break;
5858               case PK_KP8: xkey = 'x'; break;
5859               case PK_KP9: xkey = 'y'; break;
5860               case PK_KPDECIMAL: xkey = 'n'; break;
5861               case PK_KPENTER: xkey = 'M'; break;
5862               default: break; /* else gcc warns `enum value not used' */
5863             }
5864             if (term->cfg.funky_type == FUNKY_XTERM && tlen > 0) {
5865                 /*
5866                  * xterm can't see the layout of the keypad, so it has
5867                  * to rely on the X keysyms returned by the keys.
5868                  * Hence, we look at the strings here, not the PuTTY
5869                  * keysyms (which describe the layout).
5870                  */
5871                 switch (text[0]) {
5872                   case '+':
5873                     if (modifiers & PKM_SHIFT)
5874                         xkey = 'l';
5875                     else
5876                         xkey = 'k';
5877                     break;
5878                   case '/': xkey = 'o'; break;
5879                   case '*': xkey = 'j'; break;
5880                   case '-': xkey = 'm'; break;
5881                 }
5882             } else {
5883                 /*
5884                  * In all other modes, we try to retain the layout of
5885                  * the DEC keypad in application mode.
5886                  */
5887                 switch (keysym) {
5888                   case PK_KPBIGPLUS:
5889                     /* This key covers the '-' and ',' keys on a VT220 */
5890                     if (modifiers & PKM_SHIFT)
5891                         xkey = 'm'; /* VT220 '-' */
5892                     else
5893                         xkey = 'l'; /* VT220 ',' */
5894                     break;
5895                   case PK_KPMINUS: xkey = 'm'; break;
5896                   case PK_KPCOMMA: xkey = 'l'; break;
5897                   default: break; /* else gcc warns `enum value not used' */
5898                 }
5899             }
5900         }
5901         if (xkey) {
5902             if (term->vt52_mode) {
5903                 if (xkey >= 'P' && xkey <= 'S')
5904                     p += sprintf((char *) p, "\x1B%c", xkey);
5905                 else
5906                     p += sprintf((char *) p, "\x1B?%c", xkey);
5907             } else
5908                 p += sprintf((char *) p, "\x1BO%c", xkey);
5909             goto done;
5910         }
5911         /* Not in application mode -- treat the number pad as arrow keys? */
5912         if ((flags & PKF_NUMLOCK) == 0) {
5913             switch (keysym) {
5914               case PK_KP0: keysym = PK_INSERT; break;
5915               case PK_KP1: keysym = PK_END; break;
5916               case PK_KP2: keysym = PK_DOWN; break;
5917               case PK_KP3: keysym = PK_PAGEDOWN; break;
5918               case PK_KP4: keysym = PK_LEFT; break;
5919               case PK_KP5: keysym = PK_REST; break;
5920               case PK_KP6: keysym = PK_RIGHT; break;
5921               case PK_KP7: keysym = PK_HOME; break;
5922               case PK_KP8: keysym = PK_UP; break;
5923               case PK_KP9: keysym = PK_PAGEUP; break;
5924               default: break; /* else gcc warns `enum value not used' */
5925             }
5926         }
5927     }
5928
5929     /* Miscellaneous keys */
5930     switch (keysym) {
5931       case PK_ESCAPE:
5932         *p++ = 0x1b;
5933         goto done;
5934       case PK_BACKSPACE:
5935             if (modifiers == 0)
5936                 *p++ = (term->cfg.bksp_is_delete ? 0x7F : 0x08);
5937             else if (modifiers == PKM_SHIFT)
5938                 /* We do the opposite of what is configured */
5939                 *p++ = (term->cfg.bksp_is_delete ? 0x08 : 0x7F);
5940             else break;
5941             goto done;
5942       case PK_TAB:
5943         if (modifiers == 0)
5944             *p++ = 0x09;
5945         else if (modifiers == PKM_SHIFT)
5946             *p++ = 0x1B, *p++ = '[', *p++ = 'Z';
5947         else break;
5948         goto done;
5949         /* XXX window.c has ctrl+shift+space sending 0xa0 */
5950       case PK_PAUSE:
5951         if (modifiers == PKM_CONTROL)
5952             *p++ = 26;
5953         else break;
5954         goto done;
5955       case PK_RETURN:
5956       case PK_KPENTER: /* Odd keypad modes handled above */
5957         if (modifiers == 0) {
5958             *p++ = 0x0d;
5959             if (term->cr_lf_return)
5960                 *p++ = 0x0a;
5961             goto done;
5962         }
5963       default: break; /* else gcc warns `enum value not used' */
5964     }
5965
5966     /* SCO function keys and editing keys */
5967     if (term->cfg.funky_type == FUNKY_SCO) {
5968         if (PK_ISFKEY(keysym) && keysym <= PK_F12) {
5969             static char const codes[] =
5970                 "MNOPQRSTUVWX" "YZabcdefghij" "klmnopqrstuv" "wxyz@[\\]^_`{";
5971             int index = keysym - PK_F1;
5972
5973             if (modifiers & PKM_SHIFT) index += 12;
5974             if (modifiers & PKM_CONTROL) index += 24;
5975             p += sprintf((char *) p, "\x1B[%c", codes[index]);
5976             goto done;
5977         }
5978         if (PK_ISEDITING(keysym)) {
5979             int xkey = 0;
5980
5981             switch (keysym) {
5982               case PK_DELETE:   *p++ = 0x7f; goto done;
5983               case PK_HOME:     xkey = 'H'; break;
5984               case PK_INSERT:   xkey = 'L'; break;
5985               case PK_END:      xkey = 'F'; break;
5986               case PK_PAGEUP:   xkey = 'I'; break;
5987               case PK_PAGEDOWN: xkey = 'G'; break;
5988               default: break; /* else gcc warns `enum value not used' */
5989             }
5990             p += sprintf((char *) p, "\x1B[%c", xkey);
5991         }
5992     }
5993
5994     if (PK_ISEDITING(keysym) && (modifiers & PKM_SHIFT) == 0) {
5995         int code;
5996
5997         if (term->cfg.funky_type == FUNKY_XTERM) {
5998             /* Xterm shuffles these keys, apparently. */
5999             switch (keysym) {
6000               case PK_HOME:     keysym = PK_INSERT;   break;
6001               case PK_INSERT:   keysym = PK_HOME;     break;
6002               case PK_DELETE:   keysym = PK_END;      break;
6003               case PK_END:      keysym = PK_PAGEUP;   break;
6004               case PK_PAGEUP:   keysym = PK_DELETE;   break;
6005               case PK_PAGEDOWN: keysym = PK_PAGEDOWN; break;
6006               default: break; /* else gcc warns `enum value not used' */
6007             }
6008         }
6009
6010         /* RXVT Home/End */
6011         if (term->cfg.rxvt_homeend &&
6012             (keysym == PK_HOME || keysym == PK_END)) {
6013             p += sprintf((char *) p, keysym == PK_HOME ? "\x1B[H" : "\x1BOw");
6014             goto done;
6015         }
6016
6017         if (term->vt52_mode) {
6018             int xkey;
6019
6020             /*
6021              * A real VT52 doesn't have these, and a VT220 doesn't
6022              * send anything for them in VT52 mode.
6023              */
6024             switch (keysym) {
6025               case PK_HOME:     xkey = 'H'; break;
6026               case PK_INSERT:   xkey = 'L'; break;
6027               case PK_DELETE:   xkey = 'M'; break;
6028               case PK_END:      xkey = 'E'; break;
6029               case PK_PAGEUP:   xkey = 'I'; break;
6030               case PK_PAGEDOWN: xkey = 'G'; break;
6031               default: xkey=0; break; /* else gcc warns `enum value not used'*/
6032             }
6033             p += sprintf((char *) p, "\x1B%c", xkey);
6034             goto done;
6035         }
6036
6037         switch (keysym) {
6038           case PK_HOME:     code = 1; break;
6039           case PK_INSERT:   code = 2; break;
6040           case PK_DELETE:   code = 3; break;
6041           case PK_END:      code = 4; break;
6042           case PK_PAGEUP:   code = 5; break;
6043           case PK_PAGEDOWN: code = 6; break;
6044           default: code = 0; break; /* else gcc warns `enum value not used' */
6045         }
6046         p += sprintf((char *) p, "\x1B[%d~", code);
6047         goto done;
6048     }
6049
6050     if (PK_ISFKEY(keysym)) {
6051         /* Map Shift+F1-F10 to F11-F20 */
6052         if (keysym >= PK_F1 && keysym <= PK_F10 && (modifiers & PKM_SHIFT))
6053             keysym += 10;
6054         if ((term->vt52_mode || term->cfg.funky_type == FUNKY_VT100P) &&
6055             keysym <= PK_F14) {
6056             /* XXX This overrides the XTERM/VT52 mode below */
6057             int offt = 0;
6058             if (keysym >= PK_F6)  offt++;
6059             if (keysym >= PK_F12) offt++;
6060             p += sprintf((char *) p, term->vt52_mode ? "\x1B%c" : "\x1BO%c",
6061                          'P' + keysym - PK_F1 - offt);
6062             goto done;
6063         }
6064         if (term->cfg.funky_type == FUNKY_LINUX && keysym <= PK_F5) {
6065             p += sprintf((char *) p, "\x1B[[%c", 'A' + keysym - PK_F1);
6066             goto done;
6067         }
6068         if (term->cfg.funky_type == FUNKY_XTERM && keysym <= PK_F4) {
6069             if (term->vt52_mode)
6070                 p += sprintf((char *) p, "\x1B%c", 'P' + keysym - PK_F1);
6071             else
6072                 p += sprintf((char *) p, "\x1BO%c", 'P' + keysym - PK_F1);
6073             goto done;
6074         }
6075         p += sprintf((char *) p, "\x1B[%d~", 11 + keysym - PK_F1);
6076         goto done;
6077     }
6078
6079     if (PK_ISCURSOR(keysym)) {
6080         int xkey;
6081
6082         switch (keysym) {
6083           case PK_UP:    xkey = 'A'; break;
6084           case PK_DOWN:  xkey = 'B'; break;
6085           case PK_RIGHT: xkey = 'C'; break;
6086           case PK_LEFT:  xkey = 'D'; break;
6087           case PK_REST:  xkey = 'G'; break; /* centre key on number pad */
6088           default: xkey = 0; break; /* else gcc warns `enum value not used' */
6089         }
6090         if (term->vt52_mode)
6091             p += sprintf((char *) p, "\x1B%c", xkey);
6092         else {
6093             int app_flg = (term->app_cursor_keys && !term->cfg.no_applic_c);
6094
6095             /* Useful mapping of Ctrl-arrows */
6096             if (modifiers == PKM_CONTROL)
6097                 app_flg = !app_flg;
6098
6099             if (app_flg)
6100                 p += sprintf((char *) p, "\x1BO%c", xkey);
6101             else
6102                 p += sprintf((char *) p, "\x1B[%c", xkey);
6103         }
6104         goto done;
6105     }
6106
6107   done:
6108     if (p > output || tlen > 0) {
6109         /*
6110          * Interrupt an ongoing paste. I'm not sure
6111          * this is sensible, but for the moment it's
6112          * preferable to having to faff about buffering
6113          * things.
6114          */
6115         term_nopaste(term);
6116
6117         /*
6118          * We need not bother about stdin backlogs
6119          * here, because in GUI PuTTY we can't do
6120          * anything about it anyway; there's no means
6121          * of asking Windows to hold off on KEYDOWN
6122          * messages. We _have_ to buffer everything
6123          * we're sent.
6124          */
6125         term_seen_key_event(term);
6126
6127         if (prependesc) {
6128 #if 0
6129             fprintf(stderr, "sending ESC\n");
6130 #endif
6131             ldisc_send(term->ldisc, "\x1b", 1, 1);
6132         }
6133
6134         if (p > output) {
6135 #if 0
6136             fprintf(stderr, "sending %d bytes:", p - output);
6137             for (i = 0; i < p - output; i++)
6138                 fprintf(stderr, " %02x", output[i]);
6139             fprintf(stderr, "\n");
6140 #endif
6141             ldisc_send(term->ldisc, output, p - output, 1);
6142         } else if (tlen > 0) {
6143 #if 0
6144             fprintf(stderr, "sending %d unichars:", tlen);
6145             for (i = 0; i < tlen; i++)
6146                 fprintf(stderr, " %04x", (unsigned) text[i]);
6147             fprintf(stderr, "\n");
6148 #endif
6149             luni_send(term->ldisc, text, tlen, 1);
6150         }
6151     }
6152 }
6153
6154 void term_nopaste(Terminal *term)
6155 {
6156     if (term->paste_len == 0)
6157         return;
6158     sfree(term->paste_buffer);
6159     term->paste_buffer = NULL;
6160     term->paste_len = 0;
6161 }
6162
6163 int term_paste_pending(Terminal *term)
6164 {
6165     return term->paste_len != 0;
6166 }
6167
6168 void term_paste(Terminal *term)
6169 {
6170     long now, paste_diff;
6171
6172     if (term->paste_len == 0)
6173         return;
6174
6175     /* Don't wait forever to paste */
6176     if (term->paste_hold) {
6177         now = GETTICKCOUNT();
6178         paste_diff = now - term->last_paste;
6179         if (paste_diff >= 0 && paste_diff < 450)
6180             return;
6181     }
6182     term->paste_hold = 0;
6183
6184     while (term->paste_pos < term->paste_len) {
6185         int n = 0;
6186         while (n + term->paste_pos < term->paste_len) {
6187             if (term->paste_buffer[term->paste_pos + n++] == '\015')
6188                 break;
6189         }
6190         if (term->ldisc)
6191             luni_send(term->ldisc, term->paste_buffer + term->paste_pos, n, 0);
6192         term->paste_pos += n;
6193
6194         if (term->paste_pos < term->paste_len) {
6195             term->paste_hold = 1;
6196             return;
6197         }
6198     }
6199     sfree(term->paste_buffer);
6200     term->paste_buffer = NULL;
6201     term->paste_len = 0;
6202 }
6203
6204 static void deselect(Terminal *term)
6205 {
6206     term->selstate = NO_SELECTION;
6207     term->selstart.x = term->selstart.y = term->selend.x = term->selend.y = 0;
6208 }
6209
6210 void term_deselect(Terminal *term)
6211 {
6212     deselect(term);
6213     term_update(term);
6214 }
6215
6216 int term_ldisc(Terminal *term, int option)
6217 {
6218     if (option == LD_ECHO)
6219         return term->term_echoing;
6220     if (option == LD_EDIT)
6221         return term->term_editing;
6222     return FALSE;
6223 }
6224
6225 int term_data(Terminal *term, int is_stderr, const char *data, int len)
6226 {
6227     bufchain_add(&term->inbuf, data, len);
6228
6229     if (!term->in_term_out) {
6230         term->in_term_out = TRUE;
6231         term_reset_cblink(term);
6232         /*
6233          * During drag-selects, we do not process terminal input,
6234          * because the user will want the screen to hold still to
6235          * be selected.
6236          */
6237         if (term->selstate != DRAGGING)
6238             term_out(term);
6239         term->in_term_out = FALSE;
6240     }
6241
6242     /*
6243      * term_out() always completely empties inbuf. Therefore,
6244      * there's no reason at all to return anything other than zero
6245      * from this function, because there _can't_ be a question of
6246      * the remote side needing to wait until term_out() has cleared
6247      * a backlog.
6248      *
6249      * This is a slightly suboptimal way to deal with SSH-2 - in
6250      * principle, the window mechanism would allow us to continue
6251      * to accept data on forwarded ports and X connections even
6252      * while the terminal processing was going slowly - but we
6253      * can't do the 100% right thing without moving the terminal
6254      * processing into a separate thread, and that might hurt
6255      * portability. So we manage stdout buffering the old SSH-1 way:
6256      * if the terminal processing goes slowly, the whole SSH
6257      * connection stops accepting data until it's ready.
6258      *
6259      * In practice, I can't imagine this causing serious trouble.
6260      */
6261     return 0;
6262 }
6263
6264 void term_provide_logctx(Terminal *term, void *logctx)
6265 {
6266     term->logctx = logctx;
6267 }
6268
6269 void term_set_focus(Terminal *term, int has_focus)
6270 {
6271     term->has_focus = has_focus;
6272     term_schedule_cblink(term);
6273 }