]> asedeno.scripts.mit.edu Git - PuTTY_svn.git/blob - unix/pterm.c
Oops - that fix wasn't _quite_ right, since it killed all
[PuTTY_svn.git] / unix / pterm.c
1 /*
2  * pterm - a fusion of the PuTTY terminal emulator with a Unix pty
3  * back end, all running as a GTK application. Wish me luck.
4  */
5
6 #include <string.h>
7 #include <assert.h>
8 #include <stdlib.h>
9 #include <stdio.h>
10 #include <time.h>
11 #include <errno.h>
12 #include <fcntl.h>
13 #include <unistd.h>
14 #include <X11/Xlib.h>
15 #include <X11/Xutil.h>
16 #include <gtk/gtk.h>
17 #include <gdk/gdkkeysyms.h>
18
19 #define PUTTY_DO_GLOBALS               /* actually _define_ globals */
20 #include "putty.h"
21
22 #define CAT2(x,y) x ## y
23 #define CAT(x,y) CAT2(x,y)
24 #define ASSERT(x) enum {CAT(assertion_,__LINE__) = 1 / (x)}
25
26 #define NCOLOURS (lenof(((Config *)0)->colours))
27
28 struct gui_data {
29     GtkWidget *window, *area, *sbar;
30     GtkBox *hbox;
31     GtkAdjustment *sbar_adjust;
32     GdkPixmap *pixmap;
33     GdkFont *fonts[2];                 /* normal and bold (for now!) */
34     GdkCursor *rawcursor, *textcursor, *blankcursor, *currcursor;
35     GdkColor cols[NCOLOURS];
36     GdkColormap *colmap;
37     wchar_t *pastein_data;
38     int pastein_data_len;
39     char *pasteout_data;
40     int pasteout_data_len;
41     int font_width, font_height;
42     int ignore_sbar;
43     int mouseptr_visible;
44     guint term_paste_idle_id;
45     GdkAtom compound_text_atom;
46     int alt_keycode;
47     char wintitle[sizeof(((Config *)0)->wintitle)];
48     char icontitle[sizeof(((Config *)0)->wintitle)];
49 };
50
51 static struct gui_data the_inst;
52 static struct gui_data *inst = &the_inst;   /* so we always write `inst->' */
53 static int send_raw_mouse;
54
55 void ldisc_update(int echo, int edit)
56 {
57     /*
58      * This is a stub in pterm. If I ever produce a Unix
59      * command-line ssh/telnet/rlogin client (i.e. a port of plink)
60      * then it will require some termios manoeuvring analogous to
61      * that in the Windows plink.c, but here it's meaningless.
62      */
63 }
64
65 int askappend(char *filename)
66 {
67     /*
68      * Logging in an xterm-alike is liable to be something you only
69      * do at serious diagnostic need. Hence, I'm going to take the
70      * easy option for now and assume we always want to overwrite
71      * log files. I can always make it properly configurable later.
72      */
73     return 2;
74 }
75
76 void logevent(char *string)
77 {
78     /*
79      * This is not a very helpful function: events are logged
80      * pretty much exclusively by the back end, and our pty back
81      * end is self-contained. So we need do nothing.
82      */
83 }
84
85 int font_dimension(int which)          /* 0 for width, 1 for height */
86 {
87     if (which)
88         return inst->font_height;
89     else
90         return inst->font_width;
91 }
92
93 /*
94  * Translate a raw mouse button designation (LEFT, MIDDLE, RIGHT)
95  * into a cooked one (SELECT, EXTEND, PASTE).
96  * 
97  * In Unix, this is not configurable; the X button arrangement is
98  * rock-solid across all applications, everyone has a three-button
99  * mouse or a means of faking it, and there is no need to switch
100  * buttons around at all.
101  */
102 Mouse_Button translate_button(Mouse_Button button)
103 {
104     if (button == MBT_LEFT)
105         return MBT_SELECT;
106     if (button == MBT_MIDDLE)
107         return MBT_PASTE;
108     if (button == MBT_RIGHT)
109         return MBT_EXTEND;
110     return 0;                          /* shouldn't happen */
111 }
112
113 /*
114  * Minimise or restore the window in response to a server-side
115  * request.
116  */
117 void set_iconic(int iconic)
118 {
119     /*
120      * GTK 1.2 doesn't know how to do this.
121      */
122 #if GTK_CHECK_VERSION(2,0,0)
123     if (iconic)
124         gtk_window_iconify(GTK_WINDOW(inst->window));
125     else
126         gtk_window_deiconify(GTK_WINDOW(inst->window));
127 #endif
128 }
129
130 /*
131  * Move the window in response to a server-side request.
132  */
133 void move_window(int x, int y)
134 {
135     /*
136      * I assume that when the GTK version of this call is available
137      * we should use it. Not sure how it differs from the GDK one,
138      * though.
139      */
140 #if GTK_CHECK_VERSION(2,0,0)
141     gtk_window_move(GTK_WINDOW(inst->window), x, y);
142 #else
143     gdk_window_move(inst->window->window, x, y);
144 #endif
145 }
146
147 /*
148  * Move the window to the top or bottom of the z-order in response
149  * to a server-side request.
150  */
151 void set_zorder(int top)
152 {
153     if (top)
154         gdk_window_raise(inst->window->window);
155     else
156         gdk_window_lower(inst->window->window);
157 }
158
159 /*
160  * Refresh the window in response to a server-side request.
161  */
162 void refresh_window(void)
163 {
164     term_invalidate();
165 }
166
167 /*
168  * Maximise or restore the window in response to a server-side
169  * request.
170  */
171 void set_zoomed(int zoomed)
172 {
173     /*
174      * GTK 1.2 doesn't know how to do this.
175      */
176 #if GTK_CHECK_VERSION(2,0,0)
177     if (iconic)
178         gtk_window_maximize(GTK_WINDOW(inst->window));
179     else
180         gtk_window_unmaximize(GTK_WINDOW(inst->window));
181 #endif
182 }
183
184 /*
185  * Report whether the window is iconic, for terminal reports.
186  */
187 int is_iconic(void)
188 {
189     return !gdk_window_is_viewable(inst->window->window);
190 }
191
192 /*
193  * Report the window's position, for terminal reports.
194  */
195 void get_window_pos(int *x, int *y)
196 {
197     /*
198      * I assume that when the GTK version of this call is available
199      * we should use it. Not sure how it differs from the GDK one,
200      * though.
201      */
202 #if GTK_CHECK_VERSION(2,0,0)
203     gtk_window_get_position(GTK_WINDOW(inst->window), x, y);
204 #else
205     gdk_window_get_position(inst->window->window, x, y);
206 #endif
207 }
208
209 /*
210  * Report the window's pixel size, for terminal reports.
211  */
212 void get_window_pixels(int *x, int *y)
213 {
214     /*
215      * I assume that when the GTK version of this call is available
216      * we should use it. Not sure how it differs from the GDK one,
217      * though.
218      */
219 #if GTK_CHECK_VERSION(2,0,0)
220     gtk_window_get_size(GTK_WINDOW(inst->window), x, y);
221 #else
222     gdk_window_get_size(inst->window->window, x, y);
223 #endif
224 }
225
226 /*
227  * Return the window or icon title.
228  */
229 char *get_window_title(int icon)
230 {
231     return icon ? inst->wintitle : inst->icontitle;
232 }
233
234 gint delete_window(GtkWidget *widget, GdkEvent *event, gpointer data)
235 {
236     /*
237      * We could implement warn-on-close here if we really wanted
238      * to.
239      */
240     return FALSE;
241 }
242
243 void show_mouseptr(int show)
244 {
245     if (!cfg.hide_mouseptr)
246         show = 1;
247     if (show)
248         gdk_window_set_cursor(inst->area->window, inst->currcursor);
249     else
250         gdk_window_set_cursor(inst->area->window, inst->blankcursor);
251     inst->mouseptr_visible = show;
252 }
253
254 gint configure_area(GtkWidget *widget, GdkEventConfigure *event, gpointer data)
255 {
256     struct gui_data *inst = (struct gui_data *)data;
257     int w, h, need_size = 0;
258
259     w = (event->width - 2*cfg.window_border) / inst->font_width;
260     h = (event->height - 2*cfg.window_border) / inst->font_height;
261
262     if (w != cfg.width || h != cfg.height) {
263         if (inst->pixmap) {
264             gdk_pixmap_unref(inst->pixmap);
265             inst->pixmap = NULL;
266         }
267         cfg.width = w;
268         cfg.height = h;
269         need_size = 1;
270     }
271     if (!inst->pixmap) {
272         GdkGC *gc;
273
274         inst->pixmap = gdk_pixmap_new(widget->window,
275                                       (cfg.width * inst->font_width +
276                                        2*cfg.window_border),
277                                       (cfg.height * inst->font_height +
278                                        2*cfg.window_border), -1);
279
280         gc = gdk_gc_new(inst->area->window);
281         gdk_gc_set_foreground(gc, &inst->cols[18]);   /* default background */
282         gdk_draw_rectangle(inst->pixmap, gc, 1, 0, 0,
283                            cfg.width * inst->font_width + 2*cfg.window_border,
284                            cfg.height * inst->font_height + 2*cfg.window_border);
285         gdk_gc_unref(gc);
286     }
287
288     if (need_size) {
289         term_size(h, w, cfg.savelines);
290     }
291
292     return TRUE;
293 }
294
295 gint expose_area(GtkWidget *widget, GdkEventExpose *event, gpointer data)
296 {
297     /* struct gui_data *inst = (struct gui_data *)data; */
298
299     /*
300      * Pass the exposed rectangle to terminal.c, which will call us
301      * back to do the actual painting.
302      */
303     if (inst->pixmap) {
304         gdk_draw_pixmap(widget->window,
305                         widget->style->fg_gc[GTK_WIDGET_STATE(widget)],
306                         inst->pixmap,
307                         event->area.x, event->area.y,
308                         event->area.x, event->area.y,
309                         event->area.width, event->area.height);
310     }
311     return TRUE;
312 }
313
314 #define KEY_PRESSED(k) \
315     (inst->keystate[(k) / 32] & (1 << ((k) % 32)))
316
317 gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data)
318 {
319     /* struct gui_data *inst = (struct gui_data *)data; */
320     char output[32];
321     int start, end;
322
323     /* By default, nothing is generated. */
324     end = start = 0;
325
326     /*
327      * If Alt is being released after typing an Alt+numberpad
328      * sequence, we should generate the code that was typed.
329      */
330     if (event->type == GDK_KEY_RELEASE &&
331         (event->keyval == GDK_Meta_L || event->keyval == GDK_Alt_L ||
332          event->keyval == GDK_Meta_R || event->keyval == GDK_Alt_R) &&
333         inst->alt_keycode >= 0) {
334 #ifdef KEY_DEBUGGING
335         printf("Alt key up, keycode = %d\n", inst->alt_keycode);
336 #endif
337         output[0] = inst->alt_keycode;
338         end = 1;
339         goto done;
340     }
341
342     if (event->type == GDK_KEY_PRESS) {
343 #ifdef KEY_DEBUGGING
344         {
345             int i;
346             printf("keypress: keyval = %04x, state = %08x; string =",
347                    event->keyval, event->state);
348             for (i = 0; event->string[i]; i++)
349                 printf(" %02x", (unsigned char) event->string[i]);
350             printf("\n");
351         }
352 #endif
353
354         /*
355          * NYI: Compose key (!!! requires Unicode faff before even trying)
356          */
357
358         /*
359          * If Alt has just been pressed, we start potentially
360          * accumulating an Alt+numberpad code. We do this by
361          * setting alt_keycode to -1 (nothing yet but plausible).
362          */
363         if ((event->keyval == GDK_Meta_L || event->keyval == GDK_Alt_L ||
364              event->keyval == GDK_Meta_R || event->keyval == GDK_Alt_R)) {
365             inst->alt_keycode = -1;
366             goto done;                 /* this generates nothing else */
367         }
368
369         /*
370          * If we're seeing a numberpad key press with Mod1 down,
371          * consider adding it to alt_keycode if that's sensible.
372          * Anything _else_ with Mod1 down cancels any possibility
373          * of an ALT keycode: we set alt_keycode to -2.
374          */
375         if ((event->state & GDK_MOD1_MASK) && inst->alt_keycode != -2) {
376             int digit = -1;
377             switch (event->keyval) {
378               case GDK_KP_0: case GDK_KP_Insert: digit = 0; break;
379               case GDK_KP_1: case GDK_KP_End: digit = 1; break;
380               case GDK_KP_2: case GDK_KP_Down: digit = 2; break;
381               case GDK_KP_3: case GDK_KP_Page_Down: digit = 3; break;
382               case GDK_KP_4: case GDK_KP_Left: digit = 4; break;
383               case GDK_KP_5: case GDK_KP_Begin: digit = 5; break;
384               case GDK_KP_6: case GDK_KP_Right: digit = 6; break;
385               case GDK_KP_7: case GDK_KP_Home: digit = 7; break;
386               case GDK_KP_8: case GDK_KP_Up: digit = 8; break;
387               case GDK_KP_9: case GDK_KP_Page_Up: digit = 9; break;
388             }
389             if (digit < 0)
390                 inst->alt_keycode = -2;   /* it's invalid */
391             else {
392 #ifdef KEY_DEBUGGING
393                 printf("Adding digit %d to keycode %d", digit,
394                        inst->alt_keycode);
395 #endif
396                 if (inst->alt_keycode == -1)
397                     inst->alt_keycode = digit;   /* one-digit code */
398                 else
399                     inst->alt_keycode = inst->alt_keycode * 10 + digit;
400 #ifdef KEY_DEBUGGING
401                 printf(" gives new code %d\n", inst->alt_keycode);
402 #endif
403                 /* Having used this digit, we now do nothing more with it. */
404                 goto done;
405             }
406         }
407
408         /*
409          * Shift-PgUp and Shift-PgDn don't even generate keystrokes
410          * at all.
411          */
412         if (event->keyval == GDK_Page_Up && (event->state & GDK_SHIFT_MASK)) {
413             term_scroll(0, -cfg.height/2);
414             return TRUE;
415         }
416         if (event->keyval == GDK_Page_Down && (event->state & GDK_SHIFT_MASK)) {
417             term_scroll(0, +cfg.height/2);
418             return TRUE;
419         }
420
421         /*
422          * Neither does Shift-Ins.
423          */
424         if (event->keyval == GDK_Insert && (event->state & GDK_SHIFT_MASK)) {
425             request_paste();
426             return TRUE;
427         }
428
429         /* ALT+things gives leading Escape. */
430         output[0] = '\033';
431         strncpy(output+1, event->string, 31);
432         output[31] = '\0';
433         end = strlen(output);
434         if (event->state & GDK_MOD1_MASK) {
435             start = 0;
436             if (end == 1) end = 0;
437         } else
438             start = 1;
439
440         /* Control-` is the same as Control-\ (unless gtk has a better idea) */
441         if (!event->string[0] && event->keyval == '`' &&
442             (event->state & GDK_CONTROL_MASK)) {
443             output[1] = '\x1C';
444             end = 2;
445         }
446
447         /* Control-Break is the same as Control-C */
448         if (event->keyval == GDK_Break &&
449             (event->state & GDK_CONTROL_MASK)) {
450             output[1] = '\003';
451             end = 2;
452         }
453
454         /* Control-2, Control-Space and Control-@ are NUL */
455         if (!event->string[0] &&
456             (event->keyval == ' ' || event->keyval == '2' ||
457              event->keyval == '@') &&
458             (event->state & (GDK_SHIFT_MASK |
459                              GDK_CONTROL_MASK)) == GDK_CONTROL_MASK) {
460             output[1] = '\0';
461             end = 2;
462         }
463
464         /* Control-Shift-Space is 160 (ISO8859 nonbreaking space) */
465         if (!event->string[0] && event->keyval == ' ' &&
466             (event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK)) ==
467             (GDK_SHIFT_MASK | GDK_CONTROL_MASK)) {
468             output[1] = '\240';
469             end = 2;
470         }
471
472         /* We don't let GTK tell us what Backspace is! We know better. */
473         if (event->keyval == GDK_BackSpace &&
474             !(event->state & GDK_SHIFT_MASK)) {
475             output[1] = cfg.bksp_is_delete ? '\x7F' : '\x08';
476             end = 2;
477         }
478         /* For Shift Backspace, do opposite of what is configured. */
479         if (event->keyval == GDK_BackSpace &&
480             (event->state & GDK_SHIFT_MASK)) {
481             output[1] = cfg.bksp_is_delete ? '\x08' : '\x7F';
482             end = 2;
483         }
484
485         /* Shift-Tab is ESC [ Z */
486         if (event->keyval == GDK_ISO_Left_Tab ||
487             (event->keyval == GDK_Tab && (event->state & GDK_SHIFT_MASK))) {
488             end = 1 + sprintf(output+1, "\033[Z");
489         }
490
491         /*
492          * NetHack keypad mode.
493          */
494         if (cfg.nethack_keypad) {
495             char *keys = NULL;
496             switch (event->keyval) {
497               case GDK_KP_1: case GDK_KP_End: keys = "bB"; break;
498               case GDK_KP_2: case GDK_KP_Down: keys = "jJ"; break;
499               case GDK_KP_3: case GDK_KP_Page_Down: keys = "nN"; break;
500               case GDK_KP_4: case GDK_KP_Left: keys = "hH"; break;
501               case GDK_KP_5: case GDK_KP_Begin: keys = ".."; break;
502               case GDK_KP_6: case GDK_KP_Right: keys = "lL"; break;
503               case GDK_KP_7: case GDK_KP_Home: keys = "yY"; break;
504               case GDK_KP_8: case GDK_KP_Up: keys = "kK"; break;
505               case GDK_KP_9: case GDK_KP_Page_Up: keys = "uU"; break;
506             }
507             if (keys) {
508                 end = 2;
509                 if (event->state & GDK_SHIFT_MASK)
510                     output[1] = keys[1];
511                 else
512                     output[1] = keys[0];
513                 goto done;
514             }
515         }
516
517         /*
518          * Application keypad mode.
519          */
520         if (app_keypad_keys && !cfg.no_applic_k) {
521             int xkey = 0;
522             switch (event->keyval) {
523               case GDK_Num_Lock: xkey = 'P'; break;
524               case GDK_KP_Divide: xkey = 'Q'; break;
525               case GDK_KP_Multiply: xkey = 'R'; break;
526               case GDK_KP_Subtract: xkey = 'S'; break;
527                 /*
528                  * Keypad + is tricky. It covers a space that would
529                  * be taken up on the VT100 by _two_ keys; so we
530                  * let Shift select between the two. Worse still,
531                  * in xterm function key mode we change which two...
532                  */
533               case GDK_KP_Add:
534                 if (cfg.funky_type == 2) {
535                     if (event->state & GDK_SHIFT_MASK)
536                         xkey = 'l';
537                     else
538                         xkey = 'k';
539                 } else if (event->state & GDK_SHIFT_MASK)
540                         xkey = 'm';
541                 else
542                     xkey = 'l';
543                 break;
544               case GDK_KP_Enter: xkey = 'M'; break;
545               case GDK_KP_0: case GDK_KP_Insert: xkey = 'p'; break;
546               case GDK_KP_1: case GDK_KP_End: xkey = 'q'; break;
547               case GDK_KP_2: case GDK_KP_Down: xkey = 'r'; break;
548               case GDK_KP_3: case GDK_KP_Page_Down: xkey = 's'; break;
549               case GDK_KP_4: case GDK_KP_Left: xkey = 't'; break;
550               case GDK_KP_5: case GDK_KP_Begin: xkey = 'u'; break;
551               case GDK_KP_6: case GDK_KP_Right: xkey = 'v'; break;
552               case GDK_KP_7: case GDK_KP_Home: xkey = 'w'; break;
553               case GDK_KP_8: case GDK_KP_Up: xkey = 'x'; break;
554               case GDK_KP_9: case GDK_KP_Page_Up: xkey = 'y'; break;
555               case GDK_KP_Decimal: case GDK_KP_Delete: xkey = 'n'; break;
556             }
557             if (xkey) {
558                 if (vt52_mode) {
559                     if (xkey >= 'P' && xkey <= 'S')
560                         end = 1 + sprintf(output+1, "\033%c", xkey);
561                     else
562                         end = 1 + sprintf(output+1, "\033?%c", xkey);
563                 } else
564                     end = 1 + sprintf(output+1, "\033O%c", xkey);
565                 goto done;
566             }
567         }
568
569         /*
570          * Next, all the keys that do tilde codes. (ESC '[' nn '~',
571          * for integer decimal nn.)
572          *
573          * We also deal with the weird ones here. Linux VCs replace F1
574          * to F5 by ESC [ [ A to ESC [ [ E. rxvt doesn't do _that_, but
575          * does replace Home and End (1~ and 4~) by ESC [ H and ESC O w
576          * respectively.
577          */
578         {
579             int code = 0;
580             switch (event->keyval) {
581               case GDK_F1:
582                 code = (event->state & GDK_SHIFT_MASK ? 23 : 11);
583                 break;
584               case GDK_F2:
585                 code = (event->state & GDK_SHIFT_MASK ? 24 : 12);
586                 break;
587               case GDK_F3:
588                 code = (event->state & GDK_SHIFT_MASK ? 25 : 13);
589                 break;
590               case GDK_F4:
591                 code = (event->state & GDK_SHIFT_MASK ? 26 : 14);
592                 break;
593               case GDK_F5:
594                 code = (event->state & GDK_SHIFT_MASK ? 28 : 15);
595                 break;
596               case GDK_F6:
597                 code = (event->state & GDK_SHIFT_MASK ? 29 : 17);
598                 break;
599               case GDK_F7:
600                 code = (event->state & GDK_SHIFT_MASK ? 31 : 18);
601                 break;
602               case GDK_F8:
603                 code = (event->state & GDK_SHIFT_MASK ? 32 : 19);
604                 break;
605               case GDK_F9:
606                 code = (event->state & GDK_SHIFT_MASK ? 33 : 20);
607                 break;
608               case GDK_F10:
609                 code = (event->state & GDK_SHIFT_MASK ? 34 : 21);
610                 break;
611               case GDK_F11:
612                 code = 23;
613                 break;
614               case GDK_F12:
615                 code = 24;
616                 break;
617               case GDK_F13:
618                 code = 25;
619                 break;
620               case GDK_F14:
621                 code = 26;
622                 break;
623               case GDK_F15:
624                 code = 28;
625                 break;
626               case GDK_F16:
627                 code = 29;
628                 break;
629               case GDK_F17:
630                 code = 31;
631                 break;
632               case GDK_F18:
633                 code = 32;
634                 break;
635               case GDK_F19:
636                 code = 33;
637                 break;
638               case GDK_F20:
639                 code = 34;
640                 break;
641             }
642             if (!(event->state & GDK_CONTROL_MASK)) switch (event->keyval) {
643               case GDK_Home: case GDK_KP_Home:
644                 code = 1;
645                 break;
646               case GDK_Insert: case GDK_KP_Insert:
647                 code = 2;
648                 break;
649               case GDK_Delete: case GDK_KP_Delete:
650                 code = 3;
651                 break;
652               case GDK_End: case GDK_KP_End:
653                 code = 4;
654                 break;
655               case GDK_Page_Up: case GDK_KP_Page_Up:
656                 code = 5;
657                 break;
658               case GDK_Page_Down: case GDK_KP_Page_Down:
659                 code = 6;
660                 break;
661             }
662             /* Reorder edit keys to physical order */
663             if (cfg.funky_type == 3 && code <= 6)
664                 code = "\0\2\1\4\5\3\6"[code];
665
666             if (vt52_mode && code > 0 && code <= 6) {
667                 end = 1 + sprintf(output+1, "\x1B%c", " HLMEIG"[code]);
668                 goto done;
669             }
670
671             if (cfg.funky_type == 5 &&     /* SCO function keys */
672                 code >= 11 && code <= 34) {
673                 char codes[] = "MNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@[\\]^_`{";
674                 int index = 0;
675                 switch (event->keyval) {
676                   case GDK_F1: index = 0; break;
677                   case GDK_F2: index = 1; break;
678                   case GDK_F3: index = 2; break;
679                   case GDK_F4: index = 3; break;
680                   case GDK_F5: index = 4; break;
681                   case GDK_F6: index = 5; break;
682                   case GDK_F7: index = 6; break;
683                   case GDK_F8: index = 7; break;
684                   case GDK_F9: index = 8; break;
685                   case GDK_F10: index = 9; break;
686                   case GDK_F11: index = 10; break;
687                   case GDK_F12: index = 11; break;
688                 }
689                 if (event->state & GDK_SHIFT_MASK) index += 12;
690                 if (event->state & GDK_CONTROL_MASK) index += 24;
691                 end = 1 + sprintf(output+1, "\x1B[%c", codes[index]);
692                 goto done;
693             }
694             if (cfg.funky_type == 5 &&     /* SCO small keypad */
695                 code >= 1 && code <= 6) {
696                 char codes[] = "HL.FIG";
697                 if (code == 3) {
698                     output[1] = '\x7F';
699                     end = 2;
700                 } else {
701                     end = 1 + sprintf(output+1, "\x1B[%c", codes[code-1]);
702                 }
703                 goto done;
704             }
705             if ((vt52_mode || cfg.funky_type == 4) && code >= 11 && code <= 24) {
706                 int offt = 0;
707                 if (code > 15)
708                     offt++;
709                 if (code > 21)
710                     offt++;
711                 if (vt52_mode)
712                     end = 1 + sprintf(output+1,
713                                       "\x1B%c", code + 'P' - 11 - offt);
714                 else
715                     end = 1 + sprintf(output+1,
716                                       "\x1BO%c", code + 'P' - 11 - offt);
717                 goto done;
718             }
719             if (cfg.funky_type == 1 && code >= 11 && code <= 15) {
720                 end = 1 + sprintf(output+1, "\x1B[[%c", code + 'A' - 11);
721                 goto done;
722             }
723             if (cfg.funky_type == 2 && code >= 11 && code <= 14) {
724                 if (vt52_mode)
725                     end = 1 + sprintf(output+1, "\x1B%c", code + 'P' - 11);
726                 else
727                     end = 1 + sprintf(output+1, "\x1BO%c", code + 'P' - 11);
728                 goto done;
729             }
730             if (cfg.rxvt_homeend && (code == 1 || code == 4)) {
731                 end = 1 + sprintf(output+1, code == 1 ? "\x1B[H" : "\x1BOw");
732                 goto done;
733             }
734             if (code) {
735                 end = 1 + sprintf(output+1, "\x1B[%d~", code);
736                 goto done;
737             }
738         }
739
740         /*
741          * Cursor keys. (This includes the numberpad cursor keys,
742          * if we haven't already done them due to app keypad mode.)
743          * 
744          * Here we also process un-numlocked un-appkeypadded KP5,
745          * which sends ESC [ G.
746          */
747         {
748             int xkey = 0;
749             switch (event->keyval) {
750               case GDK_Up: case GDK_KP_Up: xkey = 'A'; break;
751               case GDK_Down: case GDK_KP_Down: xkey = 'B'; break;
752               case GDK_Right: case GDK_KP_Right: xkey = 'C'; break;
753               case GDK_Left: case GDK_KP_Left: xkey = 'D'; break;
754               case GDK_Begin: case GDK_KP_Begin: xkey = 'G'; break;
755             }
756             if (xkey) {
757                 /*
758                  * The arrow keys normally do ESC [ A and so on. In
759                  * app cursor keys mode they do ESC O A instead.
760                  * Ctrl toggles the two modes.
761                  */
762                 if (vt52_mode) {
763                     end = 1 + sprintf(output+1, "\033%c", xkey);
764                 } else if (!app_cursor_keys ^
765                            !(event->state & GDK_CONTROL_MASK)) {
766                     end = 1 + sprintf(output+1, "\033O%c", xkey);
767                 } else {                    
768                     end = 1 + sprintf(output+1, "\033[%c", xkey);
769                 }
770                 goto done;
771             }
772         }
773         goto done;
774     }
775
776     done:
777
778     if (end-start > 0) {
779 #ifdef KEY_DEBUGGING
780         int i;
781         printf("generating sequence:");
782         for (i = start; i < end; i++)
783             printf(" %02x", (unsigned char) output[i]);
784         printf("\n");
785 #endif
786
787         ldisc_send(output+start, end-start, 1);
788         show_mouseptr(0);
789         term_out();
790     }
791
792     return TRUE;
793 }
794
795 gint button_event(GtkWidget *widget, GdkEventButton *event, gpointer data)
796 {
797     struct gui_data *inst = (struct gui_data *)data;
798     int shift, ctrl, alt, x, y, button, act;
799
800     show_mouseptr(1);
801
802     if (event->button == 4 && event->type == GDK_BUTTON_PRESS) {
803         term_scroll(0, -5);
804         return TRUE;
805     }
806     if (event->button == 5 && event->type == GDK_BUTTON_PRESS) {
807         term_scroll(0, +5);
808         return TRUE;
809     }
810
811     shift = event->state & GDK_SHIFT_MASK;
812     ctrl = event->state & GDK_CONTROL_MASK;
813     alt = event->state & GDK_MOD1_MASK;
814     if (event->button == 1)
815         button = MBT_LEFT;
816     else if (event->button == 2)
817         button = MBT_MIDDLE;
818     else if (event->button == 3)
819         button = MBT_RIGHT;
820     else
821         return FALSE;                  /* don't even know what button! */
822
823     switch (event->type) {
824       case GDK_BUTTON_PRESS: act = MA_CLICK; break;
825       case GDK_BUTTON_RELEASE: act = MA_RELEASE; break;
826       case GDK_2BUTTON_PRESS: act = MA_2CLK; break;
827       case GDK_3BUTTON_PRESS: act = MA_3CLK; break;
828       default: return FALSE;           /* don't know this event type */
829     }
830
831     if (send_raw_mouse && !(cfg.mouse_override && shift) &&
832         act != MA_CLICK && act != MA_RELEASE)
833         return TRUE;                   /* we ignore these in raw mouse mode */
834
835     x = (event->x - cfg.window_border) / inst->font_width;
836     y = (event->y - cfg.window_border) / inst->font_height;
837
838     term_mouse(button, act, x, y, shift, ctrl, alt);
839
840     return TRUE;
841 }
842
843 gint motion_event(GtkWidget *widget, GdkEventMotion *event, gpointer data)
844 {
845     struct gui_data *inst = (struct gui_data *)data;
846     int shift, ctrl, alt, x, y, button;
847
848     show_mouseptr(1);
849
850     shift = event->state & GDK_SHIFT_MASK;
851     ctrl = event->state & GDK_CONTROL_MASK;
852     alt = event->state & GDK_MOD1_MASK;
853     if (event->state & GDK_BUTTON1_MASK)
854         button = MBT_LEFT;
855     else if (event->state & GDK_BUTTON2_MASK)
856         button = MBT_MIDDLE;
857     else if (event->state & GDK_BUTTON3_MASK)
858         button = MBT_RIGHT;
859     else
860         return FALSE;                  /* don't even know what button! */
861
862     x = (event->x - cfg.window_border) / inst->font_width;
863     y = (event->y - cfg.window_border) / inst->font_height;
864
865     term_mouse(button, MA_DRAG, x, y, shift, ctrl, alt);
866
867     return TRUE;
868 }
869
870 gint timer_func(gpointer data)
871 {
872     /* struct gui_data *inst = (struct gui_data *)data; */
873     extern int pty_child_is_dead();  /* declared in pty.c */
874
875     if (pty_child_is_dead()) {
876         /*
877          * The primary child process died. We could keep the
878          * terminal open for remaining subprocesses to output to,
879          * but conventional wisdom seems to feel that that's the
880          * Wrong Thing for an xterm-alike, so we bail out now. This
881          * would be easy enough to change or make configurable if
882          * necessary.
883          */
884         exit(0);
885     }
886
887     term_update();
888     term_blink(0);
889     return TRUE;
890 }
891
892 void pty_input_func(gpointer data, gint sourcefd, GdkInputCondition condition)
893 {
894     /* struct gui_data *inst = (struct gui_data *)data; */
895     char buf[4096];
896     int ret;
897
898     ret = read(sourcefd, buf, sizeof(buf));
899
900     /*
901      * Clean termination condition is that either ret == 0, or ret
902      * < 0 and errno == EIO. Not sure why the latter, but it seems
903      * to happen. Boo.
904      */
905     if (ret == 0 || (ret < 0 && errno == EIO)) {
906         exit(0);
907     }
908
909     if (ret < 0) {
910         perror("read pty master");
911         exit(1);
912     }
913     if (ret > 0)
914         from_backend(0, buf, ret);
915     term_blink(1);
916     term_out();
917 }
918
919 void destroy(GtkWidget *widget, gpointer data)
920 {
921     gtk_main_quit();
922 }
923
924 gint focus_event(GtkWidget *widget, GdkEventFocus *event, gpointer data)
925 {
926     has_focus = event->in;
927     term_out();
928     term_update();
929     show_mouseptr(1);
930     return FALSE;
931 }
932
933 /*
934  * set or clear the "raw mouse message" mode
935  */
936 void set_raw_mouse_mode(int activate)
937 {
938     activate = activate && !cfg.no_mouse_rep;
939     send_raw_mouse = activate;
940     if (send_raw_mouse)
941         inst->currcursor = inst->rawcursor;
942     else
943         inst->currcursor = inst->textcursor;
944     show_mouseptr(inst->mouseptr_visible);
945 }
946
947 void request_resize(int w, int h)
948 {
949     int large_x, large_y;
950     int offset_x, offset_y;
951     int area_x, area_y;
952     GtkRequisition inner, outer;
953
954     /*
955      * This is a heinous hack dreamed up by the gnome-terminal
956      * people to get around a limitation in gtk. The problem is
957      * that in order to set the size correctly we really need to be
958      * calling gtk_window_resize - but that needs to know the size
959      * of the _whole window_, not the drawing area. So what we do
960      * is to set an artificially huge size request on the drawing
961      * area, recompute the resulting size request on the window,
962      * and look at the difference between the two. That gives us
963      * the x and y offsets we need to translate drawing area size
964      * into window size for real, and then we call
965      * gtk_window_resize.
966      */
967
968     /*
969      * We start by retrieving the current size of the whole window.
970      * Adding a bit to _that_ will give us a value we can use as a
971      * bogus size request which guarantees to be bigger than the
972      * current size of the drawing area.
973      */
974     get_window_pixels(&large_x, &large_y);
975     large_x += 32;
976     large_y += 32;
977
978 #if GTK_CHECK_VERSION(2,0,0)
979     gtk_widget_set_size_request(inst->area, large_x, large_y);
980 #else
981     gtk_widget_set_usize(inst->area, large_x, large_y);
982 #endif
983     gtk_widget_size_request(inst->area, &inner);
984     gtk_widget_size_request(inst->window, &outer);
985
986     offset_x = outer.width - inner.width;
987     offset_y = outer.height - inner.height;
988
989     area_x = inst->font_width * w + 2*cfg.window_border;
990     area_y = inst->font_height * h + 2*cfg.window_border;
991
992     /*
993      * Now we must set the size request on the drawing area back to
994      * something sensible before we commit the real resize. Best
995      * way to do this, I think, is to set it to what the size is
996      * really going to end up being.
997      */
998 #if GTK_CHECK_VERSION(2,0,0)
999     gtk_widget_set_size_request(inst->area, area_x, area_y);
1000 #else
1001     gtk_widget_set_usize(inst->area, area_x, area_y);
1002 #endif
1003
1004 #if GTK_CHECK_VERSION(2,0,0)
1005     gtk_window_resize(GTK_WINDOW(inst->window),
1006                       area_x + offset_x, area_y + offset_y);
1007 #else
1008     gdk_window_resize(inst->window->window,
1009                       area_x + offset_x, area_y + offset_y);
1010 #endif
1011 }
1012
1013 void real_palette_set(int n, int r, int g, int b)
1014 {
1015     gboolean success[1];
1016
1017     inst->cols[n].red = r * 0x0101;
1018     inst->cols[n].green = g * 0x0101;
1019     inst->cols[n].blue = b * 0x0101;
1020
1021     gdk_colormap_alloc_colors(inst->colmap, inst->cols + n, 1,
1022                               FALSE, FALSE, success);
1023     if (!success[0])
1024         g_error("pterm: couldn't allocate colour %d (#%02x%02x%02x)\n",
1025                 n, r, g, b);
1026 }
1027
1028 void palette_set(int n, int r, int g, int b)
1029 {
1030     static const int first[21] = {
1031         0, 2, 4, 6, 8, 10, 12, 14,
1032         1, 3, 5, 7, 9, 11, 13, 15,
1033         16, 17, 18, 20, 22
1034     };
1035     real_palette_set(first[n], r, g, b);
1036     if (first[n] >= 18)
1037         real_palette_set(first[n] + 1, r, g, b);
1038 }
1039
1040 void palette_reset(void)
1041 {
1042     /* This maps colour indices in cfg to those used in inst->cols. */
1043     static const int ww[] = {
1044         6, 7, 8, 9, 10, 11, 12, 13,
1045         14, 15, 16, 17, 18, 19, 20, 21,
1046         0, 1, 2, 3, 4, 5
1047     };
1048     gboolean success[NCOLOURS];
1049     int i;
1050
1051     assert(lenof(ww) == NCOLOURS);
1052
1053     if (!inst->colmap) {
1054         inst->colmap = gdk_colormap_get_system();
1055     } else {
1056         gdk_colormap_free_colors(inst->colmap, inst->cols, NCOLOURS);
1057     }
1058
1059     for (i = 0; i < NCOLOURS; i++) {
1060         inst->cols[i].red = cfg.colours[ww[i]][0] * 0x0101;
1061         inst->cols[i].green = cfg.colours[ww[i]][1] * 0x0101;
1062         inst->cols[i].blue = cfg.colours[ww[i]][2] * 0x0101;
1063     }
1064
1065     gdk_colormap_alloc_colors(inst->colmap, inst->cols, NCOLOURS,
1066                               FALSE, FALSE, success);
1067     for (i = 0; i < NCOLOURS; i++) {
1068         if (!success[i])
1069             g_error("pterm: couldn't allocate colour %d (#%02x%02x%02x)\n",
1070                     i, cfg.colours[i][0], cfg.colours[i][1], cfg.colours[i][2]);
1071     }
1072 }
1073
1074 void write_clip(wchar_t * data, int len, int must_deselect)
1075 {
1076     if (inst->pasteout_data)
1077         sfree(inst->pasteout_data);
1078     inst->pasteout_data = smalloc(len);
1079     inst->pasteout_data_len = len;
1080     wc_to_mb(0, 0, data, len, inst->pasteout_data, inst->pasteout_data_len,
1081              NULL, NULL);
1082
1083     if (gtk_selection_owner_set(inst->area, GDK_SELECTION_PRIMARY,
1084                                 GDK_CURRENT_TIME)) {
1085         gtk_selection_add_target(inst->area, GDK_SELECTION_PRIMARY,
1086                                  GDK_SELECTION_TYPE_STRING, 1);
1087         gtk_selection_add_target(inst->area, GDK_SELECTION_PRIMARY,
1088                                  inst->compound_text_atom, 1);
1089     }
1090 }
1091
1092 void selection_get(GtkWidget *widget, GtkSelectionData *seldata,
1093                    guint info, guint time_stamp, gpointer data)
1094 {
1095     gtk_selection_data_set(seldata, GDK_SELECTION_TYPE_STRING, 8,
1096                            inst->pasteout_data, inst->pasteout_data_len);
1097 }
1098
1099 gint selection_clear(GtkWidget *widget, GdkEventSelection *seldata,
1100                      gpointer data)
1101 {
1102     term_deselect();
1103     if (inst->pasteout_data)
1104         sfree(inst->pasteout_data);
1105     inst->pasteout_data = NULL;
1106     inst->pasteout_data_len = 0;
1107     return TRUE;
1108 }
1109
1110 void request_paste(void)
1111 {
1112     /*
1113      * In Unix, pasting is asynchronous: all we can do at the
1114      * moment is to call gtk_selection_convert(), and when the data
1115      * comes back _then_ we can call term_do_paste().
1116      */
1117     gtk_selection_convert(inst->area, GDK_SELECTION_PRIMARY,
1118                           GDK_SELECTION_TYPE_STRING, GDK_CURRENT_TIME);
1119 }
1120
1121 gint idle_paste_func(gpointer data);   /* forward ref */
1122
1123 void selection_received(GtkWidget *widget, GtkSelectionData *seldata,
1124                         gpointer data)
1125 {
1126     if (seldata->length <= 0 ||
1127         seldata->type != GDK_SELECTION_TYPE_STRING)
1128         return;                        /* Nothing happens. */
1129
1130     if (inst->pastein_data)
1131         sfree(inst->pastein_data);
1132
1133     inst->pastein_data = smalloc(seldata->length * sizeof(wchar_t));
1134     inst->pastein_data_len = seldata->length;
1135     mb_to_wc(0, 0, seldata->data, seldata->length,
1136              inst->pastein_data, inst->pastein_data_len);
1137
1138     term_do_paste();
1139
1140     if (term_paste_pending())
1141         inst->term_paste_idle_id = gtk_idle_add(idle_paste_func, inst);
1142 }
1143
1144 gint idle_paste_func(gpointer data)
1145 {
1146     struct gui_data *inst = (struct gui_data *)data;
1147
1148     if (term_paste_pending())
1149         term_paste();
1150     else
1151         gtk_idle_remove(inst->term_paste_idle_id);
1152
1153     return TRUE;
1154 }
1155
1156
1157 void get_clip(wchar_t ** p, int *len)
1158 {
1159     if (p) {
1160         *p = inst->pastein_data;
1161         *len = inst->pastein_data_len;
1162     }
1163 }
1164
1165 void set_title(char *title)
1166 {
1167     strncpy(inst->wintitle, title, lenof(inst->wintitle));
1168     inst->wintitle[lenof(inst->wintitle)-1] = '\0';
1169     gtk_window_set_title(GTK_WINDOW(inst->window), inst->wintitle);
1170 }
1171
1172 void set_icon(char *title)
1173 {
1174     strncpy(inst->icontitle, title, lenof(inst->icontitle));
1175     inst->icontitle[lenof(inst->icontitle)-1] = '\0';
1176     gdk_window_set_icon_name(inst->window->window, inst->icontitle);
1177 }
1178
1179 void set_sbar(int total, int start, int page)
1180 {
1181     if (!cfg.scrollbar)
1182         return;
1183     inst->sbar_adjust->lower = 0;
1184     inst->sbar_adjust->upper = total;
1185     inst->sbar_adjust->value = start;
1186     inst->sbar_adjust->page_size = page;
1187     inst->sbar_adjust->step_increment = 1;
1188     inst->sbar_adjust->page_increment = page/2;
1189     inst->ignore_sbar = TRUE;
1190     gtk_adjustment_changed(inst->sbar_adjust);
1191     inst->ignore_sbar = FALSE;
1192 }
1193
1194 void scrollbar_moved(GtkAdjustment *adj, gpointer data)
1195 {
1196     if (!cfg.scrollbar)
1197         return;
1198     if (!inst->ignore_sbar)
1199         term_scroll(1, (int)adj->value);
1200 }
1201
1202 void sys_cursor(int x, int y)
1203 {
1204     /*
1205      * This is meaningless under X.
1206      */
1207 }
1208
1209 void beep(int mode)
1210 {
1211     gdk_beep();
1212 }
1213
1214 int CharWidth(Context ctx, int uc)
1215 {
1216     /*
1217      * Under X, any fixed-width font really _is_ fixed-width.
1218      * Double-width characters will be dealt with using a separate
1219      * font. For the moment we can simply return 1.
1220      */
1221     return 1;
1222 }
1223
1224 Context get_ctx(void)
1225 {
1226     GdkGC *gc;
1227     if (!inst->area->window)
1228         return NULL;
1229     gc = gdk_gc_new(inst->area->window);
1230     return gc;
1231 }
1232
1233 void free_ctx(Context ctx)
1234 {
1235     GdkGC *gc = (GdkGC *)ctx;
1236     gdk_gc_unref(gc);
1237 }
1238
1239 /*
1240  * Draw a line of text in the window, at given character
1241  * coordinates, in given attributes.
1242  *
1243  * We are allowed to fiddle with the contents of `text'.
1244  */
1245 void do_text_internal(Context ctx, int x, int y, char *text, int len,
1246                       unsigned long attr, int lattr)
1247 {
1248     int nfg, nbg, t, fontid, shadow;
1249     GdkGC *gc = (GdkGC *)ctx;
1250
1251     /*
1252      * NYI:
1253      *  - Unicode, code pages, and ATTR_WIDE for CJK support.
1254      */
1255
1256     nfg = 2 * ((attr & ATTR_FGMASK) >> ATTR_FGSHIFT);
1257     nbg = 2 * ((attr & ATTR_BGMASK) >> ATTR_BGSHIFT);
1258     if (attr & ATTR_REVERSE) {
1259         t = nfg;
1260         nfg = nbg;
1261         nbg = t;
1262     }
1263     if (cfg.bold_colour && (attr & ATTR_BOLD))
1264         nfg++;
1265     if (cfg.bold_colour && (attr & ATTR_BLINK))
1266         nbg++;
1267     if (attr & TATTR_ACTCURS) {
1268         nfg = NCOLOURS-2;
1269         nbg = NCOLOURS-1;
1270     }
1271
1272     fontid = shadow = 0;
1273     if ((attr & ATTR_BOLD) && !cfg.bold_colour) {
1274         if (inst->fonts[1])
1275             fontid = 1;
1276         else
1277             shadow = 1;
1278     }
1279
1280     if (lattr != LATTR_NORM) {
1281         x *= 2;
1282         if (x >= cols)
1283             return;
1284         if (x + len*2 > cols)
1285             len = (cols-x)/2;          /* trim to LH half */
1286     }
1287
1288     gdk_gc_set_foreground(gc, &inst->cols[nbg]);
1289     gdk_draw_rectangle(inst->pixmap, gc, 1,
1290                        x*inst->font_width+cfg.window_border,
1291                        y*inst->font_height+cfg.window_border,
1292                        len*inst->font_width, inst->font_height);
1293
1294     gdk_gc_set_foreground(gc, &inst->cols[nfg]);
1295     gdk_draw_text(inst->pixmap, inst->fonts[fontid], gc,
1296                   x*inst->font_width+cfg.window_border,
1297                   y*inst->font_height+cfg.window_border+inst->fonts[0]->ascent,
1298                   text, len);
1299
1300     if (shadow) {
1301         gdk_draw_text(inst->pixmap, inst->fonts[fontid], gc,
1302                       x*inst->font_width+cfg.window_border + cfg.shadowboldoffset,
1303                       y*inst->font_height+cfg.window_border+inst->fonts[0]->ascent,
1304                       text, len);
1305     }
1306
1307     if (attr & ATTR_UNDER) {
1308         int uheight = inst->fonts[0]->ascent + 1;
1309         if (uheight >= inst->font_height)
1310             uheight = inst->font_height - 1;
1311         gdk_draw_line(inst->pixmap, gc, x*inst->font_width+cfg.window_border,
1312                       y*inst->font_height + uheight + cfg.window_border,
1313                       (x+len)*inst->font_width-1+cfg.window_border,
1314                       y*inst->font_height + uheight + cfg.window_border);
1315     }
1316
1317     if (lattr != LATTR_NORM) {
1318         /*
1319          * I can't find any plausible StretchBlt equivalent in the
1320          * X server, so I'm going to do this the slow and painful
1321          * way. This will involve repeated calls to
1322          * gdk_draw_pixmap() to stretch the text horizontally. It's
1323          * O(N^2) in time and O(N) in network bandwidth, but you
1324          * try thinking of a better way. :-(
1325          */
1326         int i;
1327         for (i = 0; i < len * inst->font_width; i++) {
1328             gdk_draw_pixmap(inst->pixmap, gc, inst->pixmap,
1329                             x*inst->font_width+cfg.window_border + 2*i,
1330                             y*inst->font_height+cfg.window_border,
1331                             x*inst->font_width+cfg.window_border + 2*i+1,
1332                             y*inst->font_height+cfg.window_border,
1333                             len * inst->font_width - i, inst->font_height);
1334         }
1335         len *= 2;
1336         if (lattr != LATTR_WIDE) {
1337             int dt, db;
1338             /* Now stretch vertically, in the same way. */
1339             if (lattr == LATTR_BOT)
1340                 dt = 0, db = 1;
1341             else
1342                 dt = 1, db = 0;
1343             for (i = 0; i < inst->font_height; i+=2) {
1344                 gdk_draw_pixmap(inst->pixmap, gc, inst->pixmap,
1345                                 x*inst->font_width+cfg.window_border,
1346                                 y*inst->font_height+cfg.window_border+dt*i+db,
1347                                 x*inst->font_width+cfg.window_border,
1348                                 y*inst->font_height+cfg.window_border+dt*(i+1),
1349                                 len * inst->font_width, inst->font_height-i-1);
1350             }
1351         }
1352     }
1353 }
1354
1355 void do_text(Context ctx, int x, int y, char *text, int len,
1356              unsigned long attr, int lattr)
1357 {
1358     GdkGC *gc = (GdkGC *)ctx;
1359
1360     do_text_internal(ctx, x, y, text, len, attr, lattr);
1361
1362     if (lattr != LATTR_NORM) {
1363         x *= 2;
1364         if (x >= cols)
1365             return;
1366         if (x + len*2 > cols)
1367             len = (cols-x)/2;          /* trim to LH half */
1368         len *= 2;
1369     }
1370
1371     gdk_draw_pixmap(inst->area->window, gc, inst->pixmap,
1372                     x*inst->font_width+cfg.window_border,
1373                     y*inst->font_height+cfg.window_border,
1374                     x*inst->font_width+cfg.window_border,
1375                     y*inst->font_height+cfg.window_border,
1376                     len*inst->font_width, inst->font_height);
1377 }
1378
1379 void do_cursor(Context ctx, int x, int y, char *text, int len,
1380                unsigned long attr, int lattr)
1381 {
1382     int passive;
1383     GdkGC *gc = (GdkGC *)ctx;
1384
1385     if (attr & TATTR_PASCURS) {
1386         attr &= ~TATTR_PASCURS;
1387         passive = 1;
1388     } else
1389         passive = 0;
1390     if ((attr & TATTR_ACTCURS) && cfg.cursor_type != 0) {
1391         attr &= ~TATTR_ACTCURS;
1392     }
1393     do_text_internal(ctx, x, y, text, len, attr, lattr);
1394
1395     if (lattr != LATTR_NORM) {
1396         x *= 2;
1397         if (x >= cols)
1398             return;
1399         if (x + len*2 > cols)
1400             len = (cols-x)/2;          /* trim to LH half */
1401         len *= 2;
1402     }
1403
1404     if (cfg.cursor_type == 0) {
1405         /*
1406          * An active block cursor will already have been done by
1407          * the above do_text call, so we only need to do anything
1408          * if it's passive.
1409          */
1410         if (passive) {
1411             gdk_gc_set_foreground(gc, &inst->cols[NCOLOURS-1]);
1412             gdk_draw_rectangle(inst->pixmap, gc, 0,
1413                                x*inst->font_width+cfg.window_border,
1414                                y*inst->font_height+cfg.window_border,
1415                                len*inst->font_width-1, inst->font_height-1);
1416         }
1417     } else {
1418         int uheight;
1419         int startx, starty, dx, dy, length, i;
1420
1421         int char_width;
1422
1423         if ((attr & ATTR_WIDE) || lattr != LATTR_NORM)
1424             char_width = 2*inst->font_width;
1425         else
1426             char_width = inst->font_width;
1427
1428         if (cfg.cursor_type == 1) {
1429             uheight = inst->fonts[0]->ascent + 1;
1430             if (uheight >= inst->font_height)
1431                 uheight = inst->font_height - 1;
1432
1433             startx = x * inst->font_width + cfg.window_border;
1434             starty = y * inst->font_height + cfg.window_border + uheight;
1435             dx = 1;
1436             dy = 0;
1437             length = len * char_width;
1438         } else {
1439             int xadjust = 0;
1440             if (attr & TATTR_RIGHTCURS)
1441                 xadjust = char_width - 1;
1442             startx = x * inst->font_width + cfg.window_border + xadjust;
1443             starty = y * inst->font_height + cfg.window_border;
1444             dx = 0;
1445             dy = 1;
1446             length = inst->font_height;
1447         }
1448
1449         gdk_gc_set_foreground(gc, &inst->cols[NCOLOURS-1]);
1450         if (passive) {
1451             for (i = 0; i < length; i++) {
1452                 if (i % 2 == 0) {
1453                     gdk_draw_point(inst->pixmap, gc, startx, starty);
1454                 }
1455                 startx += dx;
1456                 starty += dy;
1457             }
1458         } else {
1459             gdk_draw_line(inst->pixmap, gc, startx, starty,
1460                           startx + (length-1) * dx, starty + (length-1) * dy);
1461         }
1462     }
1463
1464     gdk_draw_pixmap(inst->area->window, gc, inst->pixmap,
1465                     x*inst->font_width+cfg.window_border,
1466                     y*inst->font_height+cfg.window_border,
1467                     x*inst->font_width+cfg.window_border,
1468                     y*inst->font_height+cfg.window_border,
1469                     len*inst->font_width, inst->font_height);
1470 }
1471
1472 GdkCursor *make_mouse_ptr(int cursor_val)
1473 {
1474     /*
1475      * Truly hideous hack: GTK doesn't allow us to set the mouse
1476      * cursor foreground and background colours unless we've _also_
1477      * created our own cursor from bitmaps. Therefore, I need to
1478      * load the `cursor' font and draw glyphs from it on to
1479      * pixmaps, in order to construct my cursors with the fg and bg
1480      * I want. This is a gross hack, but it's more self-contained
1481      * than linking in Xlib to find the X window handle to
1482      * inst->area and calling XRecolorCursor, and it's more
1483      * futureproof than hard-coding the shapes as bitmap arrays.
1484      */
1485     static GdkFont *cursor_font = NULL;
1486     GdkPixmap *source, *mask;
1487     GdkGC *gc;
1488     GdkColor cfg = { 0, 65535, 65535, 65535 };
1489     GdkColor cbg = { 0, 0, 0, 0 };
1490     GdkColor dfg = { 1, 65535, 65535, 65535 };
1491     GdkColor dbg = { 0, 0, 0, 0 };
1492     GdkCursor *ret;
1493     gchar text[2];
1494     gint lb, rb, wid, asc, desc, w, h, x, y;
1495
1496     if (cursor_val == -2) {
1497         gdk_font_unref(cursor_font);
1498         return NULL;
1499     }
1500
1501     if (cursor_val >= 0 && !cursor_font)
1502         cursor_font = gdk_font_load("cursor");
1503
1504     /*
1505      * Get the text extent of the cursor in question. We use the
1506      * mask character for this, because it's typically slightly
1507      * bigger than the main character.
1508      */
1509     if (cursor_val >= 0) {
1510         text[1] = '\0';
1511         text[0] = (char)cursor_val + 1;
1512         gdk_string_extents(cursor_font, text, &lb, &rb, &wid, &asc, &desc);
1513         w = rb-lb; h = asc+desc; x = -lb; y = asc;
1514     } else {
1515         w = h = 1;
1516         x = y = 0;
1517     }
1518
1519     source = gdk_pixmap_new(NULL, w, h, 1);
1520     mask = gdk_pixmap_new(NULL, w, h, 1);
1521
1522     /*
1523      * Draw the mask character on the mask pixmap.
1524      */
1525     gc = gdk_gc_new(mask);
1526     gdk_gc_set_foreground(gc, &dbg);
1527     gdk_draw_rectangle(mask, gc, 1, 0, 0, w, h);
1528     if (cursor_val >= 0) {
1529         text[1] = '\0';
1530         text[0] = (char)cursor_val + 1;
1531         gdk_gc_set_foreground(gc, &dfg);
1532         gdk_draw_text(mask, cursor_font, gc, x, y, text, 1);
1533     }
1534     gdk_gc_unref(gc);
1535
1536     /*
1537      * Draw the main character on the source pixmap.
1538      */
1539     gc = gdk_gc_new(source);
1540     gdk_gc_set_foreground(gc, &dbg);
1541     gdk_draw_rectangle(source, gc, 1, 0, 0, w, h);
1542     if (cursor_val >= 0) {
1543         text[1] = '\0';
1544         text[0] = (char)cursor_val;
1545         gdk_gc_set_foreground(gc, &dfg);
1546         gdk_draw_text(source, cursor_font, gc, x, y, text, 1);
1547     }
1548     gdk_gc_unref(gc);
1549
1550     /*
1551      * Create the cursor.
1552      */
1553     ret = gdk_cursor_new_from_pixmap(source, mask, &cfg, &cbg, x, y);
1554
1555     /*
1556      * Clean up.
1557      */
1558     gdk_pixmap_unref(source);
1559     gdk_pixmap_unref(mask);
1560
1561     return ret;
1562 }
1563
1564 void modalfatalbox(char *p, ...)
1565 {
1566     va_list ap;
1567     fprintf(stderr, "FATAL ERROR: ");
1568     va_start(ap, p);
1569     vfprintf(stderr, p, ap);
1570     va_end(ap);
1571     fputc('\n', stderr);
1572     exit(1);
1573 }
1574
1575 char *get_x_display(void)
1576 {
1577     return gdk_get_display();
1578 }
1579
1580 char *app_name = "pterm";
1581
1582 int do_cmdline(int argc, char **argv, int do_everything)
1583 {
1584     int err = 0;
1585     extern char **pty_argv;            /* declared in pty.c */
1586
1587     /*
1588      * Macros to make argument handling easier.
1589      */
1590 #define EXPECTS_ARG do { \
1591     if (--argc <= 0) { \
1592         err = 1; \
1593         fprintf(stderr, "pterm: %s expects an argument\n", p); \
1594     } else \
1595         val = *++argv; \
1596 } while (0)
1597 #define SECOND_PASS_ONLY do { \
1598     if (!do_everything) continue; \
1599 } while (0)
1600
1601     /*
1602      * TODO:
1603      * 
1604      * finish -geometry
1605      */
1606
1607     char *val;
1608     while (--argc > 0) {
1609         char *p = *++argv;
1610         if (!strcmp(p, "-fn") || !strcmp(p, "-font")) {
1611             EXPECTS_ARG;
1612             SECOND_PASS_ONLY;
1613             strncpy(cfg.font, val, sizeof(cfg.font));
1614             cfg.font[sizeof(cfg.font)-1] = '\0';
1615
1616         } else if (!strcmp(p, "-fb")) {
1617             EXPECTS_ARG;
1618             SECOND_PASS_ONLY;
1619             strncpy(cfg.boldfont, val, sizeof(cfg.boldfont));
1620             cfg.boldfont[sizeof(cfg.boldfont)-1] = '\0';
1621
1622         } else if (!strcmp(p, "-geometry")) {
1623             int flags, x, y, w, h;
1624             EXPECTS_ARG;
1625             SECOND_PASS_ONLY;
1626
1627             flags = XParseGeometry(val, &x, &y, &w, &h);
1628             if (flags & WidthValue)
1629                 cfg.width = w;
1630             if (flags & HeightValue)
1631                 cfg.height = h;
1632
1633             /*
1634              * Apparently setting the initial window position is
1635              * difficult in GTK 1.2. Not entirely sure why this
1636              * should be. 2.0 has gtk_window_parse_geometry(),
1637              * which would help... For the moment, though, I can't
1638              * be bothered with this.
1639              */
1640
1641         } else if (!strcmp(p, "-sl")) {
1642             EXPECTS_ARG;
1643             SECOND_PASS_ONLY;
1644             cfg.savelines = atoi(val);
1645
1646         } else if (!strcmp(p, "-fg") || !strcmp(p, "-bg") ||
1647                    !strcmp(p, "-bfg") || !strcmp(p, "-bbg") ||
1648                    !strcmp(p, "-cfg") || !strcmp(p, "-cbg")) {
1649             GdkColor col;
1650
1651             EXPECTS_ARG;
1652             SECOND_PASS_ONLY;
1653             if (!gdk_color_parse(val, &col)) {
1654                 err = 1;
1655                 fprintf(stderr, "pterm: unable to parse colour \"%s\"\n", val);
1656             } else {
1657                 int index;
1658                 index = (!strcmp(p, "-fg") ? 0 :
1659                          !strcmp(p, "-bg") ? 2 :
1660                          !strcmp(p, "-bfg") ? 1 :
1661                          !strcmp(p, "-bbg") ? 3 :
1662                          !strcmp(p, "-cfg") ? 4 :
1663                          !strcmp(p, "-cbg") ? 5 : -1);
1664                 assert(index != -1);
1665                 cfg.colours[index][0] = col.red / 256;
1666                 cfg.colours[index][1] = col.green / 256;
1667                 cfg.colours[index][2] = col.blue / 256;
1668             }
1669
1670         } else if (!strcmp(p, "-e")) {
1671             /* This option swallows all further arguments. */
1672             if (!do_everything)
1673                 break;
1674
1675             if (--argc > 0) {
1676                 int i;
1677                 pty_argv = smalloc((argc+1) * sizeof(char *));
1678                 ++argv;
1679                 for (i = 0; i < argc; i++)
1680                     pty_argv[i] = argv[i];
1681                 pty_argv[argc] = NULL;
1682                 break;                 /* finished command-line processing */
1683             } else
1684                 err = 1, fprintf(stderr, "pterm: -e expects an argument\n");
1685
1686         } else if (!strcmp(p, "-T")) {
1687             EXPECTS_ARG;
1688             SECOND_PASS_ONLY;
1689             strncpy(cfg.wintitle, val, sizeof(cfg.wintitle));
1690             cfg.wintitle[sizeof(cfg.wintitle)-1] = '\0';
1691
1692         } else if (!strcmp(p, "-log")) {
1693             EXPECTS_ARG;
1694             SECOND_PASS_ONLY;
1695             strncpy(cfg.logfilename, val, sizeof(cfg.logfilename));
1696             cfg.logfilename[sizeof(cfg.logfilename)-1] = '\0';
1697             cfg.logtype = LGTYP_DEBUG;
1698
1699         } else if (!strcmp(p, "-ut-") || !strcmp(p, "+ut")) {
1700             SECOND_PASS_ONLY;
1701             cfg.stamp_utmp = 0;
1702
1703         } else if (!strcmp(p, "-ut")) {
1704             SECOND_PASS_ONLY;
1705             cfg.stamp_utmp = 0;
1706
1707         } else if (!strcmp(p, "-ls-") || !strcmp(p, "+ls")) {
1708             SECOND_PASS_ONLY;
1709             cfg.login_shell = 0;
1710
1711         } else if (!strcmp(p, "-ls")) {
1712             SECOND_PASS_ONLY;
1713             cfg.login_shell = 1;
1714
1715         } else if (!strcmp(p, "-nethack")) {
1716             SECOND_PASS_ONLY;
1717             cfg.nethack_keypad = 1;
1718
1719         } else if (!strcmp(p, "-sb-") || !strcmp(p, "+sb")) {
1720             SECOND_PASS_ONLY;
1721             cfg.scrollbar = 0;
1722
1723         } else if (!strcmp(p, "-sb")) {
1724             SECOND_PASS_ONLY;
1725             cfg.scrollbar = 0;
1726
1727         } else if (!strcmp(p, "-name")) {
1728             EXPECTS_ARG;
1729             app_name = val;
1730
1731         } else if (!strcmp(p, "-xrm")) {
1732             EXPECTS_ARG;
1733             provide_xrm_string(val);
1734
1735         }
1736     }
1737
1738     return err;
1739 }
1740
1741 int main(int argc, char **argv)
1742 {
1743     extern int pty_master_fd;          /* declared in pty.c */
1744     extern void pty_pre_init(void);    /* declared in pty.c */
1745
1746     pty_pre_init();
1747
1748     gtk_init(&argc, &argv);
1749
1750     if (do_cmdline(argc, argv, 0))     /* pre-defaults pass to get -class */
1751         exit(1);
1752     do_defaults(NULL, &cfg);
1753     if (do_cmdline(argc, argv, 1))     /* post-defaults, do everything */
1754         exit(1);
1755
1756     inst->fonts[0] = gdk_font_load(cfg.font);
1757     if (!inst->fonts[0]) {
1758         fprintf(stderr, "pterm: unable to load font \"%s\"\n", cfg.font);
1759         exit(1);
1760     }
1761     if (cfg.boldfont[0]) {
1762         inst->fonts[1] = gdk_font_load(cfg.boldfont);
1763         if (!inst->fonts[1]) {
1764             fprintf(stderr, "pterm: unable to load bold font \"%s\"\n",
1765                     cfg.boldfont);
1766             exit(1);
1767         }
1768     } else
1769         inst->fonts[1] = NULL;
1770
1771     inst->font_width = gdk_char_width(inst->fonts[0], ' ');
1772     inst->font_height = inst->fonts[0]->ascent + inst->fonts[0]->descent;
1773
1774     inst->compound_text_atom = gdk_atom_intern("COMPOUND_TEXT", FALSE);
1775
1776     init_ucs();
1777
1778     inst->window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1779
1780     if (cfg.wintitle[0])
1781         set_title(cfg.wintitle);
1782     else
1783         set_title("pterm");
1784
1785     /*
1786      * Set up the colour map.
1787      */
1788     palette_reset();
1789
1790     inst->area = gtk_drawing_area_new();
1791     gtk_drawing_area_size(GTK_DRAWING_AREA(inst->area),
1792                           inst->font_width * cfg.width + 2*cfg.window_border,
1793                           inst->font_height * cfg.height + 2*cfg.window_border);
1794     if (cfg.scrollbar) {
1795         inst->sbar_adjust = GTK_ADJUSTMENT(gtk_adjustment_new(0,0,0,0,0,0));
1796         inst->sbar = gtk_vscrollbar_new(inst->sbar_adjust);
1797     }
1798     inst->hbox = GTK_BOX(gtk_hbox_new(FALSE, 0));
1799     if (cfg.scrollbar) {
1800         if (cfg.scrollbar_on_left)
1801             gtk_box_pack_start(inst->hbox, inst->sbar, FALSE, FALSE, 0);
1802         else
1803             gtk_box_pack_end(inst->hbox, inst->sbar, FALSE, FALSE, 0);
1804     }
1805     gtk_box_pack_start(inst->hbox, inst->area, TRUE, TRUE, 0);
1806
1807     gtk_container_add(GTK_CONTAINER(inst->window), GTK_WIDGET(inst->hbox));
1808
1809     {
1810         GdkGeometry geom;
1811         geom.min_width = inst->font_width + 2*cfg.window_border;
1812         geom.min_height = inst->font_height + 2*cfg.window_border;
1813         geom.max_width = geom.max_height = -1;
1814         geom.base_width = 2*cfg.window_border;
1815         geom.base_height = 2*cfg.window_border;
1816         geom.width_inc = inst->font_width;
1817         geom.height_inc = inst->font_height;
1818         geom.min_aspect = geom.max_aspect = 0;
1819         gtk_window_set_geometry_hints(GTK_WINDOW(inst->window), inst->area, &geom,
1820                                       GDK_HINT_MIN_SIZE | GDK_HINT_BASE_SIZE |
1821                                       GDK_HINT_RESIZE_INC);
1822     }
1823
1824     gtk_signal_connect(GTK_OBJECT(inst->window), "destroy",
1825                        GTK_SIGNAL_FUNC(destroy), inst);
1826     gtk_signal_connect(GTK_OBJECT(inst->window), "delete_event",
1827                        GTK_SIGNAL_FUNC(delete_window), inst);
1828     gtk_signal_connect(GTK_OBJECT(inst->window), "key_press_event",
1829                        GTK_SIGNAL_FUNC(key_event), inst);
1830     gtk_signal_connect(GTK_OBJECT(inst->window), "key_release_event",
1831                        GTK_SIGNAL_FUNC(key_event), inst);
1832     gtk_signal_connect(GTK_OBJECT(inst->window), "focus_in_event",
1833                        GTK_SIGNAL_FUNC(focus_event), inst);
1834     gtk_signal_connect(GTK_OBJECT(inst->window), "focus_out_event",
1835                        GTK_SIGNAL_FUNC(focus_event), inst);
1836     gtk_signal_connect(GTK_OBJECT(inst->area), "configure_event",
1837                        GTK_SIGNAL_FUNC(configure_area), inst);
1838     gtk_signal_connect(GTK_OBJECT(inst->area), "expose_event",
1839                        GTK_SIGNAL_FUNC(expose_area), inst);
1840     gtk_signal_connect(GTK_OBJECT(inst->area), "button_press_event",
1841                        GTK_SIGNAL_FUNC(button_event), inst);
1842     gtk_signal_connect(GTK_OBJECT(inst->area), "button_release_event",
1843                        GTK_SIGNAL_FUNC(button_event), inst);
1844     gtk_signal_connect(GTK_OBJECT(inst->area), "motion_notify_event",
1845                        GTK_SIGNAL_FUNC(motion_event), inst);
1846     gtk_signal_connect(GTK_OBJECT(inst->area), "selection_received",
1847                        GTK_SIGNAL_FUNC(selection_received), inst);
1848     gtk_signal_connect(GTK_OBJECT(inst->area), "selection_get",
1849                        GTK_SIGNAL_FUNC(selection_get), inst);
1850     gtk_signal_connect(GTK_OBJECT(inst->area), "selection_clear_event",
1851                        GTK_SIGNAL_FUNC(selection_clear), inst);
1852     if (cfg.scrollbar)
1853         gtk_signal_connect(GTK_OBJECT(inst->sbar_adjust), "value_changed",
1854                            GTK_SIGNAL_FUNC(scrollbar_moved), inst);
1855     gtk_timeout_add(20, timer_func, inst);
1856     gtk_widget_add_events(GTK_WIDGET(inst->area),
1857                           GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK |
1858                           GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK |
1859                           GDK_POINTER_MOTION_MASK | GDK_BUTTON_MOTION_MASK);
1860
1861     gtk_widget_show(inst->area);
1862     if (cfg.scrollbar)
1863         gtk_widget_show(inst->sbar);
1864     gtk_widget_show(GTK_WIDGET(inst->hbox));
1865     gtk_widget_show(inst->window);
1866
1867     inst->textcursor = make_mouse_ptr(GDK_XTERM);
1868     inst->rawcursor = make_mouse_ptr(GDK_LEFT_PTR);
1869     inst->blankcursor = make_mouse_ptr(-1);
1870     make_mouse_ptr(-2);                /* clean up cursor font */
1871     inst->currcursor = inst->textcursor;
1872     show_mouseptr(1);
1873
1874     back = &pty_backend;
1875     back->init(NULL, 0, NULL, 0);
1876
1877     gdk_input_add(pty_master_fd, GDK_INPUT_READ, pty_input_func, inst);
1878
1879     term_init();
1880     term_size(cfg.height, cfg.width, cfg.savelines);
1881
1882     gtk_main();
1883
1884     return 0;
1885 }