OSDN Git Service

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