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