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