]> asedeno.scripts.mit.edu Git - PuTTY_svn.git/blob - unix/gtkwin.c
812e4faf99041f62acb3b6dd003a5872ac116a9b
[PuTTY_svn.git] / unix / gtkwin.c
1 /*
2  * gtkwin.c: the main code that runs a PuTTY terminal emulator and
3  * backend in a GTK window.
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 <signal.h>
13 #include <stdio.h>
14 #include <time.h>
15 #include <errno.h>
16 #include <locale.h>
17 #include <fcntl.h>
18 #include <unistd.h>
19 #include <sys/types.h>
20 #include <sys/wait.h>
21 #include <gtk/gtk.h>
22 #include <gdk/gdkkeysyms.h>
23 #include <gdk/gdkx.h>
24 #include <X11/Xlib.h>
25 #include <X11/Xutil.h>
26 #include <X11/Xatom.h>
27
28 #if GTK_CHECK_VERSION(2,0,0)
29 #include <gtk/gtkimmodule.h>
30 #endif
31
32 #define PUTTY_DO_GLOBALS               /* actually _define_ globals */
33
34 #define MAY_REFER_TO_GTK_IN_HEADERS
35
36 #include "putty.h"
37 #include "terminal.h"
38 #include "gtkfont.h"
39
40 #define CAT2(x,y) x ## y
41 #define CAT(x,y) CAT2(x,y)
42 #define ASSERT(x) enum {CAT(assertion_,__LINE__) = 1 / (x)}
43
44 #if GTK_CHECK_VERSION(2,0,0)
45 ASSERT(sizeof(long) <= sizeof(gsize));
46 #define LONG_TO_GPOINTER(l) GSIZE_TO_POINTER(l)
47 #define GPOINTER_TO_LONG(p) GPOINTER_TO_SIZE(p)
48 #else /* Gtk 1.2 */
49 ASSERT(sizeof(long) <= sizeof(gpointer));
50 #define LONG_TO_GPOINTER(l) ((gpointer)(long)(l))
51 #define GPOINTER_TO_LONG(p) ((long)(p))
52 #endif
53
54 /* Colours come in two flavours: configurable, and xterm-extended. */
55 #define NEXTCOLOURS 240 /* 216 colour-cube plus 24 shades of grey */
56 #define NALLCOLOURS (NCFGCOLOURS + NEXTCOLOURS)
57
58 GdkAtom compound_text_atom, utf8_string_atom;
59
60 extern char **pty_argv;        /* declared in pty.c */
61 extern int use_pty_argv;
62
63 /*
64  * Timers are global across all sessions (even if we were handling
65  * multiple sessions, which we aren't), so the current timer ID is
66  * a global variable.
67  */
68 static guint timer_id = 0;
69
70 struct gui_data {
71     GtkWidget *window, *area, *sbar;
72     GtkBox *hbox;
73     GtkAdjustment *sbar_adjust;
74     GtkWidget *menu, *specialsmenu, *specialsitem1, *specialsitem2,
75         *restartitem;
76     GtkWidget *sessionsmenu;
77     GdkPixmap *pixmap;
78 #if GTK_CHECK_VERSION(2,0,0)
79     GtkIMContext *imc;
80 #endif
81     unifont *fonts[4];                 /* normal, bold, wide, widebold */
82     int xpos, ypos, gotpos, gravity;
83     GdkCursor *rawcursor, *textcursor, *blankcursor, *waitcursor, *currcursor;
84     GdkColor cols[NALLCOLOURS];
85     GdkColormap *colmap;
86     wchar_t *pastein_data;
87     int direct_to_font;
88     int pastein_data_len;
89     char *pasteout_data, *pasteout_data_ctext, *pasteout_data_utf8;
90     int pasteout_data_len, pasteout_data_ctext_len, pasteout_data_utf8_len;
91     int font_width, font_height;
92     int width, height;
93     int ignore_sbar;
94     int mouseptr_visible;
95     int busy_status;
96     guint toplevel_callback_idle_id;
97     int alt_keycode;
98     int alt_digits;
99     char *wintitle;
100     char *icontitle;
101     int master_fd, master_func_id;
102     void *ldisc;
103     Backend *back;
104     void *backhandle;
105     Terminal *term;
106     void *logctx;
107     int exited;
108     struct unicode_data ucsdata;
109     Conf *conf;
110     void *eventlogstuff;
111     char *progname, **gtkargvstart;
112     int ngtkargs;
113     guint32 input_event_time; /* Timestamp of the most recent input event. */
114     int reconfiguring;
115     /* Cached things out of conf that we refer to a lot */
116     int bold_style;
117     int window_border;
118     int cursor_type;
119 };
120
121 static void cache_conf_values(struct gui_data *inst)
122 {
123     inst->bold_style = conf_get_int(inst->conf, CONF_bold_style);
124     inst->window_border = conf_get_int(inst->conf, CONF_window_border);
125     inst->cursor_type = conf_get_int(inst->conf, CONF_cursor_type);
126 }
127
128 struct draw_ctx {
129     GdkGC *gc;
130     struct gui_data *inst;
131 };
132
133 static int send_raw_mouse;
134
135 static char *app_name = "pterm";
136
137 static void start_backend(struct gui_data *inst);
138 static void exit_callback(void *vinst);
139
140 char *x_get_default(const char *key)
141 {
142     return XGetDefault(GDK_DISPLAY(), app_name, key);
143 }
144
145 void connection_fatal(void *frontend, char *p, ...)
146 {
147     struct gui_data *inst = (struct gui_data *)frontend;
148
149     va_list ap;
150     char *msg;
151     va_start(ap, p);
152     msg = dupvprintf(p, ap);
153     va_end(ap);
154     fatal_message_box(inst->window, msg);
155     sfree(msg);
156
157     queue_toplevel_callback(exit_callback, inst);
158 }
159
160 /*
161  * Default settings that are specific to pterm.
162  */
163 FontSpec *platform_default_fontspec(const char *name)
164 {
165     if (!strcmp(name, "Font"))
166         return fontspec_new("server:fixed");
167     else
168         return fontspec_new("");
169 }
170
171 Filename *platform_default_filename(const char *name)
172 {
173     if (!strcmp(name, "LogFileName"))
174         return filename_from_str("putty.log");
175     else
176         return filename_from_str("");
177 }
178
179 char *platform_default_s(const char *name)
180 {
181     if (!strcmp(name, "SerialLine"))
182         return dupstr("/dev/ttyS0");
183     return NULL;
184 }
185
186 int platform_default_i(const char *name, int def)
187 {
188     if (!strcmp(name, "CloseOnExit"))
189         return 2;  /* maps to FORCE_ON after painful rearrangement :-( */
190     if (!strcmp(name, "WinNameAlways"))
191         return 0;  /* X natively supports icon titles, so use 'em by default */
192     return def;
193 }
194
195 /* Dummy routine, only required in plink. */
196 void ldisc_update(void *frontend, int echo, int edit)
197 {
198 }
199
200 char *get_ttymode(void *frontend, const char *mode)
201 {
202     struct gui_data *inst = (struct gui_data *)frontend;
203     return term_get_ttymode(inst->term, mode);
204 }
205
206 int from_backend(void *frontend, int is_stderr, const char *data, int len)
207 {
208     struct gui_data *inst = (struct gui_data *)frontend;
209     return term_data(inst->term, is_stderr, data, len);
210 }
211
212 int from_backend_untrusted(void *frontend, const char *data, int len)
213 {
214     struct gui_data *inst = (struct gui_data *)frontend;
215     return term_data_untrusted(inst->term, data, len);
216 }
217
218 int from_backend_eof(void *frontend)
219 {
220     return TRUE;   /* do respond to incoming EOF with outgoing */
221 }
222
223 int get_userpass_input(prompts_t *p, unsigned char *in, int inlen)
224 {
225     struct gui_data *inst = (struct gui_data *)p->frontend;
226     int ret;
227     ret = cmdline_get_passwd_input(p, in, inlen);
228     if (ret == -1)
229         ret = term_get_userpass_input(inst->term, p, in, inlen);
230     return ret;
231 }
232
233 void logevent(void *frontend, const char *string)
234 {
235     struct gui_data *inst = (struct gui_data *)frontend;
236
237     log_eventlog(inst->logctx, string);
238
239     logevent_dlg(inst->eventlogstuff, string);
240 }
241
242 int font_dimension(void *frontend, int which)/* 0 for width, 1 for height */
243 {
244     struct gui_data *inst = (struct gui_data *)frontend;
245
246     if (which)
247         return inst->font_height;
248     else
249         return inst->font_width;
250 }
251
252 /*
253  * Translate a raw mouse button designation (LEFT, MIDDLE, RIGHT)
254  * into a cooked one (SELECT, EXTEND, PASTE).
255  * 
256  * In Unix, this is not configurable; the X button arrangement is
257  * rock-solid across all applications, everyone has a three-button
258  * mouse or a means of faking it, and there is no need to switch
259  * buttons around at all.
260  */
261 static Mouse_Button translate_button(Mouse_Button button)
262 {
263     /* struct gui_data *inst = (struct gui_data *)frontend; */
264
265     if (button == MBT_LEFT)
266         return MBT_SELECT;
267     if (button == MBT_MIDDLE)
268         return MBT_PASTE;
269     if (button == MBT_RIGHT)
270         return MBT_EXTEND;
271     return 0;                          /* shouldn't happen */
272 }
273
274 /*
275  * Return the top-level GtkWindow associated with a particular
276  * front end instance.
277  */
278 void *get_window(void *frontend)
279 {
280     struct gui_data *inst = (struct gui_data *)frontend;
281     return inst->window;
282 }
283
284 /*
285  * Minimise or restore the window in response to a server-side
286  * request.
287  */
288 void set_iconic(void *frontend, int iconic)
289 {
290     /*
291      * GTK 1.2 doesn't know how to do this.
292      */
293 #if GTK_CHECK_VERSION(2,0,0)
294     struct gui_data *inst = (struct gui_data *)frontend;
295     if (iconic)
296         gtk_window_iconify(GTK_WINDOW(inst->window));
297     else
298         gtk_window_deiconify(GTK_WINDOW(inst->window));
299 #endif
300 }
301
302 /*
303  * Move the window in response to a server-side request.
304  */
305 void move_window(void *frontend, int x, int y)
306 {
307     struct gui_data *inst = (struct gui_data *)frontend;
308     /*
309      * I assume that when the GTK version of this call is available
310      * we should use it. Not sure how it differs from the GDK one,
311      * though.
312      */
313 #if GTK_CHECK_VERSION(2,0,0)
314     gtk_window_move(GTK_WINDOW(inst->window), x, y);
315 #else
316     gdk_window_move(inst->window->window, x, y);
317 #endif
318 }
319
320 /*
321  * Move the window to the top or bottom of the z-order in response
322  * to a server-side request.
323  */
324 void set_zorder(void *frontend, int top)
325 {
326     struct gui_data *inst = (struct gui_data *)frontend;
327     if (top)
328         gdk_window_raise(inst->window->window);
329     else
330         gdk_window_lower(inst->window->window);
331 }
332
333 /*
334  * Refresh the window in response to a server-side request.
335  */
336 void refresh_window(void *frontend)
337 {
338     struct gui_data *inst = (struct gui_data *)frontend;
339     term_invalidate(inst->term);
340 }
341
342 /*
343  * Maximise or restore the window in response to a server-side
344  * request.
345  */
346 void set_zoomed(void *frontend, int zoomed)
347 {
348     /*
349      * GTK 1.2 doesn't know how to do this.
350      */
351 #if GTK_CHECK_VERSION(2,0,0)
352     struct gui_data *inst = (struct gui_data *)frontend;
353     if (zoomed)
354         gtk_window_maximize(GTK_WINDOW(inst->window));
355     else
356         gtk_window_unmaximize(GTK_WINDOW(inst->window));
357 #endif
358 }
359
360 /*
361  * Report whether the window is iconic, for terminal reports.
362  */
363 int is_iconic(void *frontend)
364 {
365     struct gui_data *inst = (struct gui_data *)frontend;
366     return !gdk_window_is_viewable(inst->window->window);
367 }
368
369 /*
370  * Report the window's position, for terminal reports.
371  */
372 void get_window_pos(void *frontend, int *x, int *y)
373 {
374     struct gui_data *inst = (struct gui_data *)frontend;
375     /*
376      * I assume that when the GTK version of this call is available
377      * we should use it. Not sure how it differs from the GDK one,
378      * though.
379      */
380 #if GTK_CHECK_VERSION(2,0,0)
381     gtk_window_get_position(GTK_WINDOW(inst->window), x, y);
382 #else
383     gdk_window_get_position(inst->window->window, x, y);
384 #endif
385 }
386
387 /*
388  * Report the window's pixel size, for terminal reports.
389  */
390 void get_window_pixels(void *frontend, int *x, int *y)
391 {
392     struct gui_data *inst = (struct gui_data *)frontend;
393     /*
394      * I assume that when the GTK version of this call is available
395      * we should use it. Not sure how it differs from the GDK one,
396      * though.
397      */
398 #if GTK_CHECK_VERSION(2,0,0)
399     gtk_window_get_size(GTK_WINDOW(inst->window), x, y);
400 #else
401     gdk_window_get_size(inst->window->window, x, y);
402 #endif
403 }
404
405 /*
406  * Return the window or icon title.
407  */
408 char *get_window_title(void *frontend, int icon)
409 {
410     struct gui_data *inst = (struct gui_data *)frontend;
411     return icon ? inst->icontitle : inst->wintitle;
412 }
413
414 gint delete_window(GtkWidget *widget, GdkEvent *event, gpointer data)
415 {
416     struct gui_data *inst = (struct gui_data *)data;
417     if (!inst->exited && conf_get_int(inst->conf, CONF_warn_on_close)) {
418         if (!reallyclose(inst))
419             return TRUE;
420     }
421     return FALSE;
422 }
423
424 static void update_mouseptr(struct gui_data *inst)
425 {
426     switch (inst->busy_status) {
427       case BUSY_NOT:
428         if (!inst->mouseptr_visible) {
429             gdk_window_set_cursor(inst->area->window, inst->blankcursor);
430         } else if (send_raw_mouse) {
431             gdk_window_set_cursor(inst->area->window, inst->rawcursor);
432         } else {
433             gdk_window_set_cursor(inst->area->window, inst->textcursor);
434         }
435         break;
436       case BUSY_WAITING:    /* XXX can we do better? */
437       case BUSY_CPU:
438         /* We always display these cursors. */
439         gdk_window_set_cursor(inst->area->window, inst->waitcursor);
440         break;
441       default:
442         assert(0);
443     }
444 }
445
446 static void show_mouseptr(struct gui_data *inst, int show)
447 {
448     if (!conf_get_int(inst->conf, CONF_hide_mouseptr))
449         show = 1;
450     inst->mouseptr_visible = show;
451     update_mouseptr(inst);
452 }
453
454 void draw_backing_rect(struct gui_data *inst)
455 {
456     GdkGC *gc = gdk_gc_new(inst->area->window);
457     gdk_gc_set_foreground(gc, &inst->cols[258]);    /* default background */
458     gdk_draw_rectangle(inst->pixmap, gc, 1, 0, 0,
459                        inst->width * inst->font_width + 2*inst->window_border,
460                        inst->height * inst->font_height + 2*inst->window_border);
461     gdk_gc_unref(gc);
462 }
463
464 gint configure_area(GtkWidget *widget, GdkEventConfigure *event, gpointer data)
465 {
466     struct gui_data *inst = (struct gui_data *)data;
467     int w, h, need_size = 0;
468
469     /*
470      * See if the terminal size has changed, in which case we must
471      * let the terminal know.
472      */
473     w = (event->width - 2*inst->window_border) / inst->font_width;
474     h = (event->height - 2*inst->window_border) / inst->font_height;
475     if (w != inst->width || h != inst->height) {
476         inst->width = w;
477         inst->height = h;
478         conf_set_int(inst->conf, CONF_width, inst->width);
479         conf_set_int(inst->conf, CONF_height, inst->height);
480         need_size = 1;
481     }
482
483     if (inst->pixmap) {
484         gdk_pixmap_unref(inst->pixmap);
485         inst->pixmap = NULL;
486     }
487
488     inst->pixmap = gdk_pixmap_new(widget->window,
489                                   (w * inst->font_width + 2*inst->window_border),
490                                   (h * inst->font_height + 2*inst->window_border), -1);
491
492     draw_backing_rect(inst);
493
494     if (need_size && inst->term) {
495         term_size(inst->term, h, w, conf_get_int(inst->conf, CONF_savelines));
496     }
497
498     if (inst->term)
499         term_invalidate(inst->term);
500
501 #if GTK_CHECK_VERSION(2,0,0)
502     gtk_im_context_set_client_window(inst->imc, widget->window);
503 #endif
504
505     return TRUE;
506 }
507
508 gint expose_area(GtkWidget *widget, GdkEventExpose *event, gpointer data)
509 {
510     struct gui_data *inst = (struct gui_data *)data;
511
512     /*
513      * Pass the exposed rectangle to terminal.c, which will call us
514      * back to do the actual painting.
515      */
516     if (inst->pixmap) {
517         gdk_draw_pixmap(widget->window,
518                         widget->style->fg_gc[GTK_WIDGET_STATE(widget)],
519                         inst->pixmap,
520                         event->area.x, event->area.y,
521                         event->area.x, event->area.y,
522                         event->area.width, event->area.height);
523     }
524     return TRUE;
525 }
526
527 #define KEY_PRESSED(k) \
528     (inst->keystate[(k) / 32] & (1 << ((k) % 32)))
529
530 gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data)
531 {
532     struct gui_data *inst = (struct gui_data *)data;
533     char output[256];
534     wchar_t ucsoutput[2];
535     int ucsval, start, end, special, output_charset, use_ucsoutput;
536     int nethack_mode, app_keypad_mode;
537
538     /* Remember the timestamp. */
539     inst->input_event_time = event->time;
540
541     /* By default, nothing is generated. */
542     end = start = 0;
543     special = use_ucsoutput = FALSE;
544     output_charset = CS_ISO8859_1;
545
546     /*
547      * If Alt is being released after typing an Alt+numberpad
548      * sequence, we should generate the code that was typed.
549      * 
550      * Note that we only do this if more than one key was actually
551      * pressed - I don't think Alt+NumPad4 should be ^D or that
552      * Alt+NumPad3 should be ^C, for example. There's no serious
553      * inconvenience in having to type a zero before a single-digit
554      * character code.
555      */
556     if (event->type == GDK_KEY_RELEASE) {
557         if ((event->keyval == GDK_Meta_L || event->keyval == GDK_Alt_L ||
558              event->keyval == GDK_Meta_R || event->keyval == GDK_Alt_R) &&
559             inst->alt_keycode >= 0 && inst->alt_digits > 1) {
560 #ifdef KEY_DEBUGGING
561             printf("Alt key up, keycode = %d\n", inst->alt_keycode);
562 #endif
563             /*
564              * FIXME: we might usefully try to do something clever here
565              * about interpreting the generated key code in a way that's
566              * appropriate to the line code page.
567              */
568             output[0] = inst->alt_keycode;
569             end = 1;
570             goto done;
571         }
572 #if GTK_CHECK_VERSION(2,0,0)
573         if (gtk_im_context_filter_keypress(inst->imc, event))
574             return TRUE;
575 #endif
576     }
577
578     if (event->type == GDK_KEY_PRESS) {
579 #ifdef KEY_DEBUGGING
580         {
581             int i;
582             printf("keypress: keyval = %04x, state = %08x; string =",
583                    event->keyval, event->state);
584             for (i = 0; event->string[i]; i++)
585                 printf(" %02x", (unsigned char) event->string[i]);
586             printf("\n");
587         }
588 #endif
589
590         /*
591          * NYI: Compose key (!!! requires Unicode faff before even trying)
592          */
593
594         /*
595          * If Alt has just been pressed, we start potentially
596          * accumulating an Alt+numberpad code. We do this by
597          * setting alt_keycode to -1 (nothing yet but plausible).
598          */
599         if ((event->keyval == GDK_Meta_L || event->keyval == GDK_Alt_L ||
600              event->keyval == GDK_Meta_R || event->keyval == GDK_Alt_R)) {
601             inst->alt_keycode = -1;
602             inst->alt_digits = 0;
603             goto done;                 /* this generates nothing else */
604         }
605
606         /*
607          * If we're seeing a numberpad key press with Mod1 down,
608          * consider adding it to alt_keycode if that's sensible.
609          * Anything _else_ with Mod1 down cancels any possibility
610          * of an ALT keycode: we set alt_keycode to -2.
611          */
612         if ((event->state & GDK_MOD1_MASK) && inst->alt_keycode != -2) {
613             int digit = -1;
614             switch (event->keyval) {
615               case GDK_KP_0: case GDK_KP_Insert: digit = 0; break;
616               case GDK_KP_1: case GDK_KP_End: digit = 1; break;
617               case GDK_KP_2: case GDK_KP_Down: digit = 2; break;
618               case GDK_KP_3: case GDK_KP_Page_Down: digit = 3; break;
619               case GDK_KP_4: case GDK_KP_Left: digit = 4; break;
620               case GDK_KP_5: case GDK_KP_Begin: digit = 5; break;
621               case GDK_KP_6: case GDK_KP_Right: digit = 6; break;
622               case GDK_KP_7: case GDK_KP_Home: digit = 7; break;
623               case GDK_KP_8: case GDK_KP_Up: digit = 8; break;
624               case GDK_KP_9: case GDK_KP_Page_Up: digit = 9; break;
625             }
626             if (digit < 0)
627                 inst->alt_keycode = -2;   /* it's invalid */
628             else {
629 #ifdef KEY_DEBUGGING
630                 printf("Adding digit %d to keycode %d", digit,
631                        inst->alt_keycode);
632 #endif
633                 if (inst->alt_keycode == -1)
634                     inst->alt_keycode = digit;   /* one-digit code */
635                 else
636                     inst->alt_keycode = inst->alt_keycode * 10 + digit;
637                 inst->alt_digits++;
638 #ifdef KEY_DEBUGGING
639                 printf(" gives new code %d\n", inst->alt_keycode);
640 #endif
641                 /* Having used this digit, we now do nothing more with it. */
642                 goto done;
643             }
644         }
645
646         /*
647          * Shift-PgUp and Shift-PgDn don't even generate keystrokes
648          * at all.
649          */
650         if (event->keyval == GDK_Page_Up && (event->state & GDK_SHIFT_MASK)) {
651             term_scroll(inst->term, 0, -inst->height/2);
652             return TRUE;
653         }
654         if (event->keyval == GDK_Page_Up && (event->state & GDK_CONTROL_MASK)) {
655             term_scroll(inst->term, 0, -1);
656             return TRUE;
657         }
658         if (event->keyval == GDK_Page_Down && (event->state & GDK_SHIFT_MASK)) {
659             term_scroll(inst->term, 0, +inst->height/2);
660             return TRUE;
661         }
662         if (event->keyval == GDK_Page_Down && (event->state & GDK_CONTROL_MASK)) {
663             term_scroll(inst->term, 0, +1);
664             return TRUE;
665         }
666
667         /*
668          * Neither does Shift-Ins.
669          */
670         if (event->keyval == GDK_Insert && (event->state & GDK_SHIFT_MASK)) {
671             request_paste(inst);
672             return TRUE;
673         }
674
675         special = FALSE;
676         use_ucsoutput = FALSE;
677
678         nethack_mode = conf_get_int(inst->conf, CONF_nethack_keypad);
679         app_keypad_mode = (inst->term->app_keypad_keys &&
680                            !conf_get_int(inst->conf, CONF_no_applic_k));
681
682         /* ALT+things gives leading Escape. */
683         output[0] = '\033';
684 #if !GTK_CHECK_VERSION(2,0,0)
685         /*
686          * In vanilla X, and hence also GDK 1.2, the string received
687          * as part of a keyboard event is assumed to be in
688          * ISO-8859-1. (Seems woefully shortsighted in i18n terms,
689          * but it's true: see the man page for XLookupString(3) for
690          * confirmation.)
691          */
692         output_charset = CS_ISO8859_1;
693         strncpy(output+1, event->string, lenof(output)-1);
694 #else
695         /*
696          * Most things can now be passed to
697          * gtk_im_context_filter_keypress without breaking anything
698          * below this point. An exception is the numeric keypad if
699          * we're in Nethack or application mode: the IM will eat
700          * numeric keypad presses if Num Lock is on, but we don't want
701          * it to.
702          */
703         if (app_keypad_mode &&
704             (event->keyval == GDK_Num_Lock ||
705              event->keyval == GDK_KP_Divide ||
706              event->keyval == GDK_KP_Multiply ||
707              event->keyval == GDK_KP_Subtract ||
708              event->keyval == GDK_KP_Add ||
709              event->keyval == GDK_KP_Enter ||
710              event->keyval == GDK_KP_0 ||
711              event->keyval == GDK_KP_Insert ||
712              event->keyval == GDK_KP_1 ||
713              event->keyval == GDK_KP_End ||
714              event->keyval == GDK_KP_2 ||
715              event->keyval == GDK_KP_Down ||
716              event->keyval == GDK_KP_3 ||
717              event->keyval == GDK_KP_Page_Down ||
718              event->keyval == GDK_KP_4 ||
719              event->keyval == GDK_KP_Left ||
720              event->keyval == GDK_KP_5 ||
721              event->keyval == GDK_KP_Begin ||
722              event->keyval == GDK_KP_6 ||
723              event->keyval == GDK_KP_Right ||
724              event->keyval == GDK_KP_7 ||
725              event->keyval == GDK_KP_Home ||
726              event->keyval == GDK_KP_8 ||
727              event->keyval == GDK_KP_Up ||
728              event->keyval == GDK_KP_9 ||
729              event->keyval == GDK_KP_Page_Up ||
730              event->keyval == GDK_KP_Decimal ||
731              event->keyval == GDK_KP_Delete)) {
732             /* app keypad; do nothing */
733         } else if (nethack_mode &&
734                    (event->keyval == GDK_KP_1 ||
735                     event->keyval == GDK_KP_End ||
736                     event->keyval == GDK_KP_2 ||
737                     event->keyval == GDK_KP_Down ||
738                     event->keyval == GDK_KP_3 ||
739                     event->keyval == GDK_KP_Page_Down ||
740                     event->keyval == GDK_KP_4 ||
741                     event->keyval == GDK_KP_Left ||
742                     event->keyval == GDK_KP_5 ||
743                     event->keyval == GDK_KP_Begin ||
744                     event->keyval == GDK_KP_6 ||
745                     event->keyval == GDK_KP_Right ||
746                     event->keyval == GDK_KP_7 ||
747                     event->keyval == GDK_KP_Home ||
748                     event->keyval == GDK_KP_8 ||
749                     event->keyval == GDK_KP_Up ||
750                     event->keyval == GDK_KP_9 ||
751                     event->keyval == GDK_KP_Page_Up)) {
752             /* nethack mode; do nothing */
753         } else {
754             if (gtk_im_context_filter_keypress(inst->imc, event))
755                 return TRUE;
756         }
757
758         /*
759          * GDK 2.0 arranges to have done some translation for us: in
760          * GDK 2.0, event->string is encoded in the current locale.
761          *
762          * So we use the standard C library function mbstowcs() to
763          * convert from the current locale into Unicode; from there
764          * we can convert to whatever PuTTY is currently working in.
765          * (In fact I convert straight back to UTF-8 from
766          * wide-character Unicode, for the sake of simplicity: that
767          * way we can still use exactly the same code to manipulate
768          * the string, such as prefixing ESC.)
769          */
770         output_charset = CS_UTF8;
771         {
772             wchar_t widedata[32];
773             const wchar_t *wp;
774             int wlen;
775             int ulen;
776
777             wlen = mb_to_wc(DEFAULT_CODEPAGE, 0,
778                             event->string, strlen(event->string),
779                             widedata, lenof(widedata)-1);
780
781             wp = widedata;
782             ulen = charset_from_unicode(&wp, &wlen, output+1, lenof(output)-2,
783                                         CS_UTF8, NULL, NULL, 0);
784             output[1+ulen] = '\0';
785         }
786 #endif
787
788         if (!output[1] &&
789             (ucsval = keysym_to_unicode(event->keyval)) >= 0) {
790             ucsoutput[0] = '\033';
791             ucsoutput[1] = ucsval;
792             use_ucsoutput = TRUE;
793             end = 2;
794         } else {
795             output[lenof(output)-1] = '\0';
796             end = strlen(output);
797         }
798         if (event->state & GDK_MOD1_MASK) {
799             start = 0;
800             if (end == 1) end = 0;
801         } else
802             start = 1;
803
804         /* Control-` is the same as Control-\ (unless gtk has a better idea) */
805         if (!output[1] && event->keyval == '`' &&
806             (event->state & GDK_CONTROL_MASK)) {
807             output[1] = '\x1C';
808             use_ucsoutput = FALSE;
809             end = 2;
810         }
811
812         /* Control-Break sends a Break special to the backend */
813         if (event->keyval == GDK_Break &&
814             (event->state & GDK_CONTROL_MASK)) {
815             if (inst->back)
816                 inst->back->special(inst->backhandle, TS_BRK);
817             return TRUE;
818         }
819
820         /* We handle Return ourselves, because it needs to be flagged as
821          * special to ldisc. */
822         if (event->keyval == GDK_Return) {
823             output[1] = '\015';
824             use_ucsoutput = FALSE;
825             end = 2;
826             special = TRUE;
827         }
828
829         /* Control-2, Control-Space and Control-@ are NUL */
830         if (!output[1] &&
831             (event->keyval == ' ' || event->keyval == '2' ||
832              event->keyval == '@') &&
833             (event->state & (GDK_SHIFT_MASK |
834                              GDK_CONTROL_MASK)) == GDK_CONTROL_MASK) {
835             output[1] = '\0';
836             use_ucsoutput = FALSE;
837             end = 2;
838         }
839
840         /* Control-Shift-Space is 160 (ISO8859 nonbreaking space) */
841         if (!output[1] && event->keyval == ' ' &&
842             (event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK)) ==
843             (GDK_SHIFT_MASK | GDK_CONTROL_MASK)) {
844             output[1] = '\240';
845             output_charset = CS_ISO8859_1;
846             use_ucsoutput = FALSE;
847             end = 2;
848         }
849
850         /* We don't let GTK tell us what Backspace is! We know better. */
851         if (event->keyval == GDK_BackSpace &&
852             !(event->state & GDK_SHIFT_MASK)) {
853             output[1] = conf_get_int(inst->conf, CONF_bksp_is_delete) ?
854                 '\x7F' : '\x08';
855             use_ucsoutput = FALSE;
856             end = 2;
857             special = TRUE;
858         }
859         /* For Shift Backspace, do opposite of what is configured. */
860         if (event->keyval == GDK_BackSpace &&
861             (event->state & GDK_SHIFT_MASK)) {
862             output[1] = conf_get_int(inst->conf, CONF_bksp_is_delete) ?
863                 '\x08' : '\x7F';
864             use_ucsoutput = FALSE;
865             end = 2;
866             special = TRUE;
867         }
868
869         /* Shift-Tab is ESC [ Z */
870         if (event->keyval == GDK_ISO_Left_Tab ||
871             (event->keyval == GDK_Tab && (event->state & GDK_SHIFT_MASK))) {
872             end = 1 + sprintf(output+1, "\033[Z");
873             use_ucsoutput = FALSE;
874         }
875         /* And normal Tab is Tab, if the keymap hasn't already told us.
876          * (Curiously, at least one version of the MacOS 10.5 X server
877          * doesn't translate Tab for us. */
878         if (event->keyval == GDK_Tab && end <= 1) {
879             output[1] = '\t';
880             end = 2;
881         }
882
883         /*
884          * NetHack keypad mode.
885          */
886         if (nethack_mode) {
887             char *keys = NULL;
888             switch (event->keyval) {
889               case GDK_KP_1: case GDK_KP_End: keys = "bB\002"; break;
890               case GDK_KP_2: case GDK_KP_Down: keys = "jJ\012"; break;
891               case GDK_KP_3: case GDK_KP_Page_Down: keys = "nN\016"; break;
892               case GDK_KP_4: case GDK_KP_Left: keys = "hH\010"; break;
893               case GDK_KP_5: case GDK_KP_Begin: keys = "..."; break;
894               case GDK_KP_6: case GDK_KP_Right: keys = "lL\014"; break;
895               case GDK_KP_7: case GDK_KP_Home: keys = "yY\031"; break;
896               case GDK_KP_8: case GDK_KP_Up: keys = "kK\013"; break;
897               case GDK_KP_9: case GDK_KP_Page_Up: keys = "uU\025"; break;
898             }
899             if (keys) {
900                 end = 2;
901                 if (event->state & GDK_CONTROL_MASK)
902                     output[1] = keys[2];
903                 else if (event->state & GDK_SHIFT_MASK)
904                     output[1] = keys[1];
905                 else
906                     output[1] = keys[0];
907                 use_ucsoutput = FALSE;
908                 goto done;
909             }
910         }
911
912         /*
913          * Application keypad mode.
914          */
915         if (app_keypad_mode) {
916             int xkey = 0;
917             switch (event->keyval) {
918               case GDK_Num_Lock: xkey = 'P'; break;
919               case GDK_KP_Divide: xkey = 'Q'; break;
920               case GDK_KP_Multiply: xkey = 'R'; break;
921               case GDK_KP_Subtract: xkey = 'S'; break;
922                 /*
923                  * Keypad + is tricky. It covers a space that would
924                  * be taken up on the VT100 by _two_ keys; so we
925                  * let Shift select between the two. Worse still,
926                  * in xterm function key mode we change which two...
927                  */
928               case GDK_KP_Add:
929                 if (conf_get_int(inst->conf, CONF_funky_type) == FUNKY_XTERM) {
930                     if (event->state & GDK_SHIFT_MASK)
931                         xkey = 'l';
932                     else
933                         xkey = 'k';
934                 } else if (event->state & GDK_SHIFT_MASK)
935                         xkey = 'm';
936                 else
937                     xkey = 'l';
938                 break;
939               case GDK_KP_Enter: xkey = 'M'; break;
940               case GDK_KP_0: case GDK_KP_Insert: xkey = 'p'; break;
941               case GDK_KP_1: case GDK_KP_End: xkey = 'q'; break;
942               case GDK_KP_2: case GDK_KP_Down: xkey = 'r'; break;
943               case GDK_KP_3: case GDK_KP_Page_Down: xkey = 's'; break;
944               case GDK_KP_4: case GDK_KP_Left: xkey = 't'; break;
945               case GDK_KP_5: case GDK_KP_Begin: xkey = 'u'; break;
946               case GDK_KP_6: case GDK_KP_Right: xkey = 'v'; break;
947               case GDK_KP_7: case GDK_KP_Home: xkey = 'w'; break;
948               case GDK_KP_8: case GDK_KP_Up: xkey = 'x'; break;
949               case GDK_KP_9: case GDK_KP_Page_Up: xkey = 'y'; break;
950               case GDK_KP_Decimal: case GDK_KP_Delete: xkey = 'n'; break;
951             }
952             if (xkey) {
953                 if (inst->term->vt52_mode) {
954                     if (xkey >= 'P' && xkey <= 'S')
955                         end = 1 + sprintf(output+1, "\033%c", xkey);
956                     else
957                         end = 1 + sprintf(output+1, "\033?%c", xkey);
958                 } else
959                     end = 1 + sprintf(output+1, "\033O%c", xkey);
960                 use_ucsoutput = FALSE;
961                 goto done;
962             }
963         }
964
965         /*
966          * Next, all the keys that do tilde codes. (ESC '[' nn '~',
967          * for integer decimal nn.)
968          *
969          * We also deal with the weird ones here. Linux VCs replace F1
970          * to F5 by ESC [ [ A to ESC [ [ E. rxvt doesn't do _that_, but
971          * does replace Home and End (1~ and 4~) by ESC [ H and ESC O w
972          * respectively.
973          */
974         {
975             int code = 0;
976             int funky_type = conf_get_int(inst->conf, CONF_funky_type);
977             switch (event->keyval) {
978               case GDK_F1:
979                 code = (event->state & GDK_SHIFT_MASK ? 23 : 11);
980                 break;
981               case GDK_F2:
982                 code = (event->state & GDK_SHIFT_MASK ? 24 : 12);
983                 break;
984               case GDK_F3:
985                 code = (event->state & GDK_SHIFT_MASK ? 25 : 13);
986                 break;
987               case GDK_F4:
988                 code = (event->state & GDK_SHIFT_MASK ? 26 : 14);
989                 break;
990               case GDK_F5:
991                 code = (event->state & GDK_SHIFT_MASK ? 28 : 15);
992                 break;
993               case GDK_F6:
994                 code = (event->state & GDK_SHIFT_MASK ? 29 : 17);
995                 break;
996               case GDK_F7:
997                 code = (event->state & GDK_SHIFT_MASK ? 31 : 18);
998                 break;
999               case GDK_F8:
1000                 code = (event->state & GDK_SHIFT_MASK ? 32 : 19);
1001                 break;
1002               case GDK_F9:
1003                 code = (event->state & GDK_SHIFT_MASK ? 33 : 20);
1004                 break;
1005               case GDK_F10:
1006                 code = (event->state & GDK_SHIFT_MASK ? 34 : 21);
1007                 break;
1008               case GDK_F11:
1009                 code = 23;
1010                 break;
1011               case GDK_F12:
1012                 code = 24;
1013                 break;
1014               case GDK_F13:
1015                 code = 25;
1016                 break;
1017               case GDK_F14:
1018                 code = 26;
1019                 break;
1020               case GDK_F15:
1021                 code = 28;
1022                 break;
1023               case GDK_F16:
1024                 code = 29;
1025                 break;
1026               case GDK_F17:
1027                 code = 31;
1028                 break;
1029               case GDK_F18:
1030                 code = 32;
1031                 break;
1032               case GDK_F19:
1033                 code = 33;
1034                 break;
1035               case GDK_F20:
1036                 code = 34;
1037                 break;
1038             }
1039             if (!(event->state & GDK_CONTROL_MASK)) switch (event->keyval) {
1040               case GDK_Home: case GDK_KP_Home:
1041                 code = 1;
1042                 break;
1043               case GDK_Insert: case GDK_KP_Insert:
1044                 code = 2;
1045                 break;
1046               case GDK_Delete: case GDK_KP_Delete:
1047                 code = 3;
1048                 break;
1049               case GDK_End: case GDK_KP_End:
1050                 code = 4;
1051                 break;
1052               case GDK_Page_Up: case GDK_KP_Page_Up:
1053                 code = 5;
1054                 break;
1055               case GDK_Page_Down: case GDK_KP_Page_Down:
1056                 code = 6;
1057                 break;
1058             }
1059             /* Reorder edit keys to physical order */
1060             if (funky_type == FUNKY_VT400 && code <= 6)
1061                 code = "\0\2\1\4\5\3\6"[code];
1062
1063             if (inst->term->vt52_mode && code > 0 && code <= 6) {
1064                 end = 1 + sprintf(output+1, "\x1B%c", " HLMEIG"[code]);
1065                 use_ucsoutput = FALSE;
1066                 goto done;
1067             }
1068
1069             if (funky_type == FUNKY_SCO &&     /* SCO function keys */
1070                 code >= 11 && code <= 34) {
1071                 char codes[] = "MNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@[\\]^_`{";
1072                 int index = 0;
1073                 switch (event->keyval) {
1074                   case GDK_F1: index = 0; break;
1075                   case GDK_F2: index = 1; break;
1076                   case GDK_F3: index = 2; break;
1077                   case GDK_F4: index = 3; break;
1078                   case GDK_F5: index = 4; break;
1079                   case GDK_F6: index = 5; break;
1080                   case GDK_F7: index = 6; break;
1081                   case GDK_F8: index = 7; break;
1082                   case GDK_F9: index = 8; break;
1083                   case GDK_F10: index = 9; break;
1084                   case GDK_F11: index = 10; break;
1085                   case GDK_F12: index = 11; break;
1086                 }
1087                 if (event->state & GDK_SHIFT_MASK) index += 12;
1088                 if (event->state & GDK_CONTROL_MASK) index += 24;
1089                 end = 1 + sprintf(output+1, "\x1B[%c", codes[index]);
1090                 use_ucsoutput = FALSE;
1091                 goto done;
1092             }
1093             if (funky_type == FUNKY_SCO &&     /* SCO small keypad */
1094                 code >= 1 && code <= 6) {
1095                 char codes[] = "HL.FIG";
1096                 if (code == 3) {
1097                     output[1] = '\x7F';
1098                     end = 2;
1099                 } else {
1100                     end = 1 + sprintf(output+1, "\x1B[%c", codes[code-1]);
1101                 }
1102                 use_ucsoutput = FALSE;
1103                 goto done;
1104             }
1105             if ((inst->term->vt52_mode || funky_type == FUNKY_VT100P) &&
1106                 code >= 11 && code <= 24) {
1107                 int offt = 0;
1108                 if (code > 15)
1109                     offt++;
1110                 if (code > 21)
1111                     offt++;
1112                 if (inst->term->vt52_mode)
1113                     end = 1 + sprintf(output+1,
1114                                       "\x1B%c", code + 'P' - 11 - offt);
1115                 else
1116                     end = 1 + sprintf(output+1,
1117                                       "\x1BO%c", code + 'P' - 11 - offt);
1118                 use_ucsoutput = FALSE;
1119                 goto done;
1120             }
1121             if (funky_type == FUNKY_LINUX && code >= 11 && code <= 15) {
1122                 end = 1 + sprintf(output+1, "\x1B[[%c", code + 'A' - 11);
1123                 use_ucsoutput = FALSE;
1124                 goto done;
1125             }
1126             if (funky_type == FUNKY_XTERM && code >= 11 && code <= 14) {
1127                 if (inst->term->vt52_mode)
1128                     end = 1 + sprintf(output+1, "\x1B%c", code + 'P' - 11);
1129                 else
1130                     end = 1 + sprintf(output+1, "\x1BO%c", code + 'P' - 11);
1131                 use_ucsoutput = FALSE;
1132                 goto done;
1133             }
1134             if ((code == 1 || code == 4) &&
1135                 conf_get_int(inst->conf, CONF_rxvt_homeend)) {
1136                 end = 1 + sprintf(output+1, code == 1 ? "\x1B[H" : "\x1BOw");
1137                 use_ucsoutput = FALSE;
1138                 goto done;
1139             }
1140             if (code) {
1141                 end = 1 + sprintf(output+1, "\x1B[%d~", code);
1142                 use_ucsoutput = FALSE;
1143                 goto done;
1144             }
1145         }
1146
1147         /*
1148          * Cursor keys. (This includes the numberpad cursor keys,
1149          * if we haven't already done them due to app keypad mode.)
1150          * 
1151          * Here we also process un-numlocked un-appkeypadded KP5,
1152          * which sends ESC [ G.
1153          */
1154         {
1155             int xkey = 0;
1156             switch (event->keyval) {
1157               case GDK_Up: case GDK_KP_Up: xkey = 'A'; break;
1158               case GDK_Down: case GDK_KP_Down: xkey = 'B'; break;
1159               case GDK_Right: case GDK_KP_Right: xkey = 'C'; break;
1160               case GDK_Left: case GDK_KP_Left: xkey = 'D'; break;
1161               case GDK_Begin: case GDK_KP_Begin: xkey = 'G'; break;
1162             }
1163             if (xkey) {
1164                 end = 1 + format_arrow_key(output+1, inst->term, xkey,
1165                                            event->state & GDK_CONTROL_MASK);
1166                 use_ucsoutput = FALSE;
1167                 goto done;
1168             }
1169         }
1170         goto done;
1171     }
1172
1173     done:
1174
1175     if (end-start > 0) {
1176 #ifdef KEY_DEBUGGING
1177         int i;
1178         printf("generating sequence:");
1179         for (i = start; i < end; i++)
1180             printf(" %02x", (unsigned char) output[i]);
1181         printf("\n");
1182 #endif
1183
1184         if (special) {
1185             /*
1186              * For special control characters, the character set
1187              * should never matter.
1188              */
1189             output[end] = '\0';        /* NUL-terminate */
1190             if (inst->ldisc)
1191                 ldisc_send(inst->ldisc, output+start, -2, 1);
1192         } else if (!inst->direct_to_font) {
1193             if (!use_ucsoutput) {
1194                 if (inst->ldisc)
1195                     lpage_send(inst->ldisc, output_charset, output+start,
1196                                end-start, 1);
1197             } else {
1198                 /*
1199                  * We generated our own Unicode key data from the
1200                  * keysym, so use that instead.
1201                  */
1202                 if (inst->ldisc)
1203                     luni_send(inst->ldisc, ucsoutput+start, end-start, 1);
1204             }
1205         } else {
1206             /*
1207              * In direct-to-font mode, we just send the string
1208              * exactly as we received it.
1209              */
1210             if (inst->ldisc)
1211                 ldisc_send(inst->ldisc, output+start, end-start, 1);
1212         }
1213
1214         show_mouseptr(inst, 0);
1215         term_seen_key_event(inst->term);
1216     }
1217
1218     return TRUE;
1219 }
1220
1221 #if GTK_CHECK_VERSION(2,0,0)
1222 void input_method_commit_event(GtkIMContext *imc, gchar *str, gpointer data)
1223 {
1224     struct gui_data *inst = (struct gui_data *)data;
1225     if (inst->ldisc)
1226         lpage_send(inst->ldisc, CS_UTF8, str, strlen(str), 1);
1227     show_mouseptr(inst, 0);
1228     term_seen_key_event(inst->term);
1229 }
1230 #endif
1231
1232 gboolean button_internal(struct gui_data *inst, guint32 timestamp,
1233                          GdkEventType type, guint ebutton, guint state,
1234                          gdouble ex, gdouble ey)
1235 {
1236     int shift, ctrl, alt, x, y, button, act;
1237
1238     /* Remember the timestamp. */
1239     inst->input_event_time = timestamp;
1240
1241     show_mouseptr(inst, 1);
1242
1243     if (ebutton == 4 && type == GDK_BUTTON_PRESS) {
1244         term_scroll(inst->term, 0, -5);
1245         return TRUE;
1246     }
1247     if (ebutton == 5 && type == GDK_BUTTON_PRESS) {
1248         term_scroll(inst->term, 0, +5);
1249         return TRUE;
1250     }
1251
1252     shift = state & GDK_SHIFT_MASK;
1253     ctrl = state & GDK_CONTROL_MASK;
1254     alt = state & GDK_MOD1_MASK;
1255
1256     if (ebutton == 3 && ctrl) {
1257         gtk_menu_popup(GTK_MENU(inst->menu), NULL, NULL, NULL, NULL,
1258                        ebutton, timestamp);
1259         return TRUE;
1260     }
1261
1262     if (ebutton == 1)
1263         button = MBT_LEFT;
1264     else if (ebutton == 2)
1265         button = MBT_MIDDLE;
1266     else if (ebutton == 3)
1267         button = MBT_RIGHT;
1268     else
1269         return FALSE;                  /* don't even know what button! */
1270
1271     switch (type) {
1272       case GDK_BUTTON_PRESS: act = MA_CLICK; break;
1273       case GDK_BUTTON_RELEASE: act = MA_RELEASE; break;
1274       case GDK_2BUTTON_PRESS: act = MA_2CLK; break;
1275       case GDK_3BUTTON_PRESS: act = MA_3CLK; break;
1276       default: return FALSE;           /* don't know this event type */
1277     }
1278
1279     if (send_raw_mouse && !(shift && conf_get_int(inst->conf,
1280                                                   CONF_mouse_override)) &&
1281         act != MA_CLICK && act != MA_RELEASE)
1282         return TRUE;                   /* we ignore these in raw mouse mode */
1283
1284     x = (ex - inst->window_border) / inst->font_width;
1285     y = (ey - inst->window_border) / inst->font_height;
1286
1287     term_mouse(inst->term, button, translate_button(button), act,
1288                x, y, shift, ctrl, alt);
1289
1290     return TRUE;
1291 }
1292
1293 gboolean button_event(GtkWidget *widget, GdkEventButton *event, gpointer data)
1294 {
1295     struct gui_data *inst = (struct gui_data *)data;
1296     return button_internal(inst, event->time, event->type, event->button,
1297                            event->state, event->x, event->y);
1298 }
1299
1300 #if GTK_CHECK_VERSION(2,0,0)
1301 /*
1302  * In GTK 2, mouse wheel events have become a new type of event.
1303  * This handler translates them back into button-4 and button-5
1304  * presses so that I don't have to change my old code too much :-)
1305  */
1306 gboolean scroll_event(GtkWidget *widget, GdkEventScroll *event, gpointer data)
1307 {
1308     struct gui_data *inst = (struct gui_data *)data;
1309     guint button;
1310
1311     if (event->direction == GDK_SCROLL_UP)
1312         button = 4;
1313     else if (event->direction == GDK_SCROLL_DOWN)
1314         button = 5;
1315     else
1316         return FALSE;
1317
1318     return button_internal(inst, event->time, GDK_BUTTON_PRESS,
1319                            button, event->state, event->x, event->y);
1320 }
1321 #endif
1322
1323 gint motion_event(GtkWidget *widget, GdkEventMotion *event, gpointer data)
1324 {
1325     struct gui_data *inst = (struct gui_data *)data;
1326     int shift, ctrl, alt, x, y, button;
1327
1328     /* Remember the timestamp. */
1329     inst->input_event_time = event->time;
1330
1331     show_mouseptr(inst, 1);
1332
1333     shift = event->state & GDK_SHIFT_MASK;
1334     ctrl = event->state & GDK_CONTROL_MASK;
1335     alt = event->state & GDK_MOD1_MASK;
1336     if (event->state & GDK_BUTTON1_MASK)
1337         button = MBT_LEFT;
1338     else if (event->state & GDK_BUTTON2_MASK)
1339         button = MBT_MIDDLE;
1340     else if (event->state & GDK_BUTTON3_MASK)
1341         button = MBT_RIGHT;
1342     else
1343         return FALSE;                  /* don't even know what button! */
1344
1345     x = (event->x - inst->window_border) / inst->font_width;
1346     y = (event->y - inst->window_border) / inst->font_height;
1347
1348     term_mouse(inst->term, button, translate_button(button), MA_DRAG,
1349                x, y, shift, ctrl, alt);
1350
1351     return TRUE;
1352 }
1353
1354 void frontend_keypress(void *handle)
1355 {
1356     struct gui_data *inst = (struct gui_data *)handle;
1357
1358     /*
1359      * If our child process has exited but not closed, terminate on
1360      * any keypress.
1361      */
1362     if (inst->exited)
1363         cleanup_exit(0);
1364 }
1365
1366 static void exit_callback(void *vinst)
1367 {
1368     struct gui_data *inst = (struct gui_data *)vinst;
1369     int exitcode, close_on_exit;
1370
1371     if (!inst->exited &&
1372         (exitcode = inst->back->exitcode(inst->backhandle)) >= 0) {
1373         inst->exited = TRUE;
1374         close_on_exit = conf_get_int(inst->conf, CONF_close_on_exit);
1375         if (close_on_exit == FORCE_ON ||
1376             (close_on_exit == AUTO && exitcode == 0))
1377             gtk_main_quit();           /* just go */
1378         if (inst->ldisc) {
1379             ldisc_free(inst->ldisc);
1380             inst->ldisc = NULL;
1381         }
1382         inst->back->free(inst->backhandle);
1383         inst->backhandle = NULL;
1384         inst->back = NULL;
1385         term_provide_resize_fn(inst->term, NULL, NULL);
1386         update_specials_menu(inst);
1387         gtk_widget_set_sensitive(inst->restartitem, TRUE);
1388     }
1389 }
1390
1391 void notify_remote_exit(void *frontend)
1392 {
1393     struct gui_data *inst = (struct gui_data *)frontend;
1394
1395     queue_toplevel_callback(exit_callback, inst);
1396 }
1397
1398 static void notify_toplevel_callback(void *frontend);
1399
1400 static gint quit_toplevel_callback_func(gpointer data)
1401 {
1402     struct gui_data *inst = (struct gui_data *)data;
1403
1404     notify_toplevel_callback(inst);
1405
1406     return 0;
1407 }
1408
1409 static gint idle_toplevel_callback_func(gpointer data)
1410 {
1411     struct gui_data *inst = (struct gui_data *)data;
1412
1413     if (gtk_main_level() > 1) {
1414         /*
1415          * We don't run the callbacks if we're in the middle of a
1416          * subsidiary gtk_main. Instead, ask for a callback when we
1417          * get back out of the subsidiary main loop, so we can
1418          * reschedule ourself then.
1419          */
1420         gtk_quit_add(2, quit_toplevel_callback_func, inst);
1421     } else {
1422         run_toplevel_callbacks();
1423     }
1424
1425     if (!toplevel_callback_pending())
1426         gtk_idle_remove(inst->toplevel_callback_idle_id);
1427
1428     return TRUE;
1429 }
1430
1431 static void notify_toplevel_callback(void *frontend)
1432 {
1433     struct gui_data *inst = (struct gui_data *)frontend;
1434
1435     inst->toplevel_callback_idle_id =
1436         gtk_idle_add(idle_toplevel_callback_func, inst);
1437 }
1438
1439 static gint timer_trigger(gpointer data)
1440 {
1441     unsigned long now = GPOINTER_TO_LONG(data);
1442     unsigned long next, then;
1443     long ticks;
1444
1445     if (run_timers(now, &next)) {
1446         then = now;
1447         now = GETTICKCOUNT();
1448         if (now - then > next - then)
1449             ticks = 0;
1450         else
1451             ticks = next - now;
1452         timer_id = gtk_timeout_add(ticks, timer_trigger,
1453                                    LONG_TO_GPOINTER(next));
1454     }
1455
1456     /*
1457      * Never let a timer resume. If we need another one, we've
1458      * asked for it explicitly above.
1459      */
1460     return FALSE;
1461 }
1462
1463 void timer_change_notify(unsigned long next)
1464 {
1465     long ticks;
1466
1467     if (timer_id)
1468         gtk_timeout_remove(timer_id);
1469
1470     ticks = next - GETTICKCOUNT();
1471     if (ticks <= 0)
1472         ticks = 1;                     /* just in case */
1473
1474     timer_id = gtk_timeout_add(ticks, timer_trigger,
1475                                LONG_TO_GPOINTER(next));
1476 }
1477
1478 void fd_input_func(gpointer data, gint sourcefd, GdkInputCondition condition)
1479 {
1480     /*
1481      * We must process exceptional notifications before ordinary
1482      * readability ones, or we may go straight past the urgent
1483      * marker.
1484      */
1485     if (condition & GDK_INPUT_EXCEPTION)
1486         select_result(sourcefd, 4);
1487     if (condition & GDK_INPUT_READ)
1488         select_result(sourcefd, 1);
1489     if (condition & GDK_INPUT_WRITE)
1490         select_result(sourcefd, 2);
1491 }
1492
1493 void destroy(GtkWidget *widget, gpointer data)
1494 {
1495     gtk_main_quit();
1496 }
1497
1498 gint focus_event(GtkWidget *widget, GdkEventFocus *event, gpointer data)
1499 {
1500     struct gui_data *inst = (struct gui_data *)data;
1501     term_set_focus(inst->term, event->in);
1502     term_update(inst->term);
1503     show_mouseptr(inst, 1);
1504     return FALSE;
1505 }
1506
1507 void set_busy_status(void *frontend, int status)
1508 {
1509     struct gui_data *inst = (struct gui_data *)frontend;
1510     inst->busy_status = status;
1511     update_mouseptr(inst);
1512 }
1513
1514 /*
1515  * set or clear the "raw mouse message" mode
1516  */
1517 void set_raw_mouse_mode(void *frontend, int activate)
1518 {
1519     struct gui_data *inst = (struct gui_data *)frontend;
1520     activate = activate && !conf_get_int(inst->conf, CONF_no_mouse_rep);
1521     send_raw_mouse = activate;
1522     update_mouseptr(inst);
1523 }
1524
1525 void request_resize(void *frontend, int w, int h)
1526 {
1527     struct gui_data *inst = (struct gui_data *)frontend;
1528     int large_x, large_y;
1529     int offset_x, offset_y;
1530     int area_x, area_y;
1531     GtkRequisition inner, outer;
1532
1533     /*
1534      * This is a heinous hack dreamed up by the gnome-terminal
1535      * people to get around a limitation in gtk. The problem is
1536      * that in order to set the size correctly we really need to be
1537      * calling gtk_window_resize - but that needs to know the size
1538      * of the _whole window_, not the drawing area. So what we do
1539      * is to set an artificially huge size request on the drawing
1540      * area, recompute the resulting size request on the window,
1541      * and look at the difference between the two. That gives us
1542      * the x and y offsets we need to translate drawing area size
1543      * into window size for real, and then we call
1544      * gtk_window_resize.
1545      */
1546
1547     /*
1548      * We start by retrieving the current size of the whole window.
1549      * Adding a bit to _that_ will give us a value we can use as a
1550      * bogus size request which guarantees to be bigger than the
1551      * current size of the drawing area.
1552      */
1553     get_window_pixels(inst, &large_x, &large_y);
1554     large_x += 32;
1555     large_y += 32;
1556
1557 #if GTK_CHECK_VERSION(2,0,0)
1558     gtk_widget_set_size_request(inst->area, large_x, large_y);
1559 #else
1560     gtk_widget_set_usize(inst->area, large_x, large_y);
1561 #endif
1562     gtk_widget_size_request(inst->area, &inner);
1563     gtk_widget_size_request(inst->window, &outer);
1564
1565     offset_x = outer.width - inner.width;
1566     offset_y = outer.height - inner.height;
1567
1568     area_x = inst->font_width * w + 2*inst->window_border;
1569     area_y = inst->font_height * h + 2*inst->window_border;
1570
1571     /*
1572      * Now we must set the size request on the drawing area back to
1573      * something sensible before we commit the real resize. Best
1574      * way to do this, I think, is to set it to what the size is
1575      * really going to end up being.
1576      */
1577 #if GTK_CHECK_VERSION(2,0,0)
1578     gtk_widget_set_size_request(inst->area, area_x, area_y);
1579     gtk_window_resize(GTK_WINDOW(inst->window),
1580                       area_x + offset_x, area_y + offset_y);
1581 #else
1582     gtk_widget_set_usize(inst->area, area_x, area_y);
1583     gtk_drawing_area_size(GTK_DRAWING_AREA(inst->area), area_x, area_y);
1584     /*
1585      * I can no longer remember what this call to
1586      * gtk_container_dequeue_resize_handler is for. It was
1587      * introduced in r3092 with no comment, and the commit log
1588      * message was uninformative. I'm _guessing_ its purpose is to
1589      * prevent gratuitous resize processing on the window given
1590      * that we're about to resize it anyway, but I have no idea
1591      * why that's so incredibly vital.
1592      * 
1593      * I've tried removing the call, and nothing seems to go
1594      * wrong. I've backtracked to r3092 and tried removing the
1595      * call there, and still nothing goes wrong. So I'm going to
1596      * adopt the working hypothesis that it's superfluous; I won't
1597      * actually remove it from the GTK 1.2 code, but I won't
1598      * attempt to replicate its functionality in the GTK 2 code
1599      * above.
1600      */
1601     gtk_container_dequeue_resize_handler(GTK_CONTAINER(inst->window));
1602     gdk_window_resize(inst->window->window,
1603                       area_x + offset_x, area_y + offset_y);
1604 #endif
1605 }
1606
1607 static void real_palette_set(struct gui_data *inst, int n, int r, int g, int b)
1608 {
1609     gboolean success[1];
1610
1611     inst->cols[n].red = r * 0x0101;
1612     inst->cols[n].green = g * 0x0101;
1613     inst->cols[n].blue = b * 0x0101;
1614
1615     gdk_colormap_free_colors(inst->colmap, inst->cols + n, 1);
1616     gdk_colormap_alloc_colors(inst->colmap, inst->cols + n, 1,
1617                               FALSE, TRUE, success);
1618     if (!success[0])
1619         g_error("%s: couldn't allocate colour %d (#%02x%02x%02x)\n", appname,
1620                 n, r, g, b);
1621 }
1622
1623 void set_window_background(struct gui_data *inst)
1624 {
1625     if (inst->area && inst->area->window)
1626         gdk_window_set_background(inst->area->window, &inst->cols[258]);
1627     if (inst->window && inst->window->window)
1628         gdk_window_set_background(inst->window->window, &inst->cols[258]);
1629 }
1630
1631 void palette_set(void *frontend, int n, int r, int g, int b)
1632 {
1633     struct gui_data *inst = (struct gui_data *)frontend;
1634     if (n >= 16)
1635         n += 256 - 16;
1636     if (n >= NALLCOLOURS)
1637         return;
1638     real_palette_set(inst, n, r, g, b);
1639     if (n == 258) {
1640         /* Default Background changed. Ensure space between text area and
1641          * window border is redrawn */
1642         set_window_background(inst);
1643         draw_backing_rect(inst);
1644         gtk_widget_queue_draw(inst->area);
1645     }
1646 }
1647
1648 void palette_reset(void *frontend)
1649 {
1650     struct gui_data *inst = (struct gui_data *)frontend;
1651     /* This maps colour indices in inst->conf to those used in inst->cols. */
1652     static const int ww[] = {
1653         256, 257, 258, 259, 260, 261,
1654         0, 8, 1, 9, 2, 10, 3, 11,
1655         4, 12, 5, 13, 6, 14, 7, 15
1656     };
1657     gboolean success[NALLCOLOURS];
1658     int i;
1659
1660     assert(lenof(ww) == NCFGCOLOURS);
1661
1662     if (!inst->colmap) {
1663         inst->colmap = gdk_colormap_get_system();
1664     } else {
1665         gdk_colormap_free_colors(inst->colmap, inst->cols, NALLCOLOURS);
1666     }
1667
1668     for (i = 0; i < NCFGCOLOURS; i++) {
1669         inst->cols[ww[i]].red =
1670             conf_get_int_int(inst->conf, CONF_colours, i*3+0) * 0x0101;
1671         inst->cols[ww[i]].green =
1672             conf_get_int_int(inst->conf, CONF_colours, i*3+1) * 0x0101;
1673         inst->cols[ww[i]].blue = 
1674             conf_get_int_int(inst->conf, CONF_colours, i*3+2) * 0x0101;
1675     }
1676
1677     for (i = 0; i < NEXTCOLOURS; i++) {
1678         if (i < 216) {
1679             int r = i / 36, g = (i / 6) % 6, b = i % 6;
1680             inst->cols[i+16].red = r ? r * 0x2828 + 0x3737 : 0;
1681             inst->cols[i+16].green = g ? g * 0x2828 + 0x3737 : 0;
1682             inst->cols[i+16].blue = b ? b * 0x2828 + 0x3737 : 0;
1683         } else {
1684             int shade = i - 216;
1685             shade = shade * 0x0a0a + 0x0808;
1686             inst->cols[i+16].red = inst->cols[i+16].green =
1687                 inst->cols[i+16].blue = shade;
1688         }
1689     }
1690
1691     gdk_colormap_alloc_colors(inst->colmap, inst->cols, NALLCOLOURS,
1692                               FALSE, TRUE, success);
1693     for (i = 0; i < NALLCOLOURS; i++) {
1694         if (!success[i])
1695             g_error("%s: couldn't allocate colour %d (#%02x%02x%02x)\n",
1696                     appname, i,
1697                     conf_get_int_int(inst->conf, CONF_colours, i*3+0),
1698                     conf_get_int_int(inst->conf, CONF_colours, i*3+1),
1699                     conf_get_int_int(inst->conf, CONF_colours, i*3+2));
1700     }
1701
1702     /* Since Default Background may have changed, ensure that space
1703      * between text area and window border is refreshed. */
1704     set_window_background(inst);
1705     if (inst->area && inst->area->window) {
1706         draw_backing_rect(inst);
1707         gtk_widget_queue_draw(inst->area);
1708     }
1709 }
1710
1711 /* Ensure that all the cut buffers exist - according to the ICCCM, we must
1712  * do this before we start using cut buffers.
1713  */
1714 void init_cutbuffers()
1715 {
1716     unsigned char empty[] = "";
1717     XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1718                     XA_CUT_BUFFER0, XA_STRING, 8, PropModeAppend, empty, 0);
1719     XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1720                     XA_CUT_BUFFER1, XA_STRING, 8, PropModeAppend, empty, 0);
1721     XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1722                     XA_CUT_BUFFER2, XA_STRING, 8, PropModeAppend, empty, 0);
1723     XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1724                     XA_CUT_BUFFER3, XA_STRING, 8, PropModeAppend, empty, 0);
1725     XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1726                     XA_CUT_BUFFER4, XA_STRING, 8, PropModeAppend, empty, 0);
1727     XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1728                     XA_CUT_BUFFER5, XA_STRING, 8, PropModeAppend, empty, 0);
1729     XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1730                     XA_CUT_BUFFER6, XA_STRING, 8, PropModeAppend, empty, 0);
1731     XChangeProperty(GDK_DISPLAY(), GDK_ROOT_WINDOW(),
1732                     XA_CUT_BUFFER7, XA_STRING, 8, PropModeAppend, empty, 0);
1733 }
1734
1735 /* Store the data in a cut-buffer. */
1736 void store_cutbuffer(char * ptr, int len)
1737 {
1738     /* ICCCM says we must rotate the buffers before storing to buffer 0. */
1739     XRotateBuffers(GDK_DISPLAY(), 1);
1740     XStoreBytes(GDK_DISPLAY(), ptr, len);
1741 }
1742
1743 /* Retrieve data from a cut-buffer.
1744  * Returned data needs to be freed with XFree().
1745  */
1746 char * retrieve_cutbuffer(int * nbytes)
1747 {
1748     char * ptr;
1749     ptr = XFetchBytes(GDK_DISPLAY(), nbytes);
1750     if (*nbytes <= 0 && ptr != 0) {
1751         XFree(ptr);
1752         ptr = 0;
1753     }
1754     return ptr;
1755 }
1756
1757 void write_clip(void *frontend, wchar_t * data, int *attr, int len, int must_deselect)
1758 {
1759     struct gui_data *inst = (struct gui_data *)frontend;
1760     if (inst->pasteout_data)
1761         sfree(inst->pasteout_data);
1762     if (inst->pasteout_data_ctext)
1763         sfree(inst->pasteout_data_ctext);
1764     if (inst->pasteout_data_utf8)
1765         sfree(inst->pasteout_data_utf8);
1766
1767     /*
1768      * Set up UTF-8 and compound text paste data. This only happens
1769      * if we aren't in direct-to-font mode using the D800 hack.
1770      */
1771     if (!inst->direct_to_font) {
1772         const wchar_t *tmp = data;
1773         int tmplen = len;
1774         XTextProperty tp;
1775         char *list[1];
1776
1777         inst->pasteout_data_utf8 = snewn(len*6, char);
1778         inst->pasteout_data_utf8_len = len*6;
1779         inst->pasteout_data_utf8_len =
1780             charset_from_unicode(&tmp, &tmplen, inst->pasteout_data_utf8,
1781                                  inst->pasteout_data_utf8_len,
1782                                  CS_UTF8, NULL, NULL, 0);
1783         if (inst->pasteout_data_utf8_len == 0) {
1784             sfree(inst->pasteout_data_utf8);
1785             inst->pasteout_data_utf8 = NULL;
1786         } else {
1787             inst->pasteout_data_utf8 =
1788                 sresize(inst->pasteout_data_utf8,
1789                         inst->pasteout_data_utf8_len + 1, char);
1790             inst->pasteout_data_utf8[inst->pasteout_data_utf8_len] = '\0';
1791         }
1792
1793         /*
1794          * Now let Xlib convert our UTF-8 data into compound text.
1795          */
1796         list[0] = inst->pasteout_data_utf8;
1797         if (Xutf8TextListToTextProperty(GDK_DISPLAY(), list, 1,
1798                                         XCompoundTextStyle, &tp) == 0) {
1799             inst->pasteout_data_ctext = snewn(tp.nitems+1, char);
1800             memcpy(inst->pasteout_data_ctext, tp.value, tp.nitems);
1801             inst->pasteout_data_ctext_len = tp.nitems;
1802             XFree(tp.value);
1803         } else {
1804             inst->pasteout_data_ctext = NULL;
1805             inst->pasteout_data_ctext_len = 0;
1806         }
1807     } else {
1808         inst->pasteout_data_utf8 = NULL;
1809         inst->pasteout_data_utf8_len = 0;
1810         inst->pasteout_data_ctext = NULL;
1811         inst->pasteout_data_ctext_len = 0;
1812     }
1813
1814     inst->pasteout_data = snewn(len*6, char);
1815     inst->pasteout_data_len = len*6;
1816     inst->pasteout_data_len = wc_to_mb(inst->ucsdata.line_codepage, 0,
1817                                        data, len, inst->pasteout_data,
1818                                        inst->pasteout_data_len,
1819                                        NULL, NULL, NULL);
1820     if (inst->pasteout_data_len == 0) {
1821         sfree(inst->pasteout_data);
1822         inst->pasteout_data = NULL;
1823     } else {
1824         inst->pasteout_data =
1825             sresize(inst->pasteout_data, inst->pasteout_data_len, char);
1826     }
1827
1828     store_cutbuffer(inst->pasteout_data, inst->pasteout_data_len);
1829
1830     if (gtk_selection_owner_set(inst->area, GDK_SELECTION_PRIMARY,
1831                                 inst->input_event_time)) {
1832 #if GTK_CHECK_VERSION(2,0,0)
1833         gtk_selection_clear_targets(inst->area, GDK_SELECTION_PRIMARY);
1834 #endif
1835         gtk_selection_add_target(inst->area, GDK_SELECTION_PRIMARY,
1836                                  GDK_SELECTION_TYPE_STRING, 1);
1837         if (inst->pasteout_data_ctext)
1838             gtk_selection_add_target(inst->area, GDK_SELECTION_PRIMARY,
1839                                      compound_text_atom, 1);
1840         if (inst->pasteout_data_utf8)
1841             gtk_selection_add_target(inst->area, GDK_SELECTION_PRIMARY,
1842                                      utf8_string_atom, 1);
1843     }
1844
1845     if (must_deselect)
1846         term_deselect(inst->term);
1847 }
1848
1849 void selection_get(GtkWidget *widget, GtkSelectionData *seldata,
1850                    guint info, guint time_stamp, gpointer data)
1851 {
1852     struct gui_data *inst = (struct gui_data *)data;
1853     if (seldata->target == utf8_string_atom)
1854         gtk_selection_data_set(seldata, seldata->target, 8,
1855                                (unsigned char *)inst->pasteout_data_utf8,
1856                                inst->pasteout_data_utf8_len);
1857     else if (seldata->target == compound_text_atom)
1858         gtk_selection_data_set(seldata, seldata->target, 8,
1859                                (unsigned char *)inst->pasteout_data_ctext,
1860                                inst->pasteout_data_ctext_len);
1861     else
1862         gtk_selection_data_set(seldata, seldata->target, 8,
1863                                (unsigned char *)inst->pasteout_data,
1864                                inst->pasteout_data_len);
1865 }
1866
1867 gint selection_clear(GtkWidget *widget, GdkEventSelection *seldata,
1868                      gpointer data)
1869 {
1870     struct gui_data *inst = (struct gui_data *)data;
1871
1872     term_deselect(inst->term);
1873     if (inst->pasteout_data)
1874         sfree(inst->pasteout_data);
1875     if (inst->pasteout_data_ctext)
1876         sfree(inst->pasteout_data_ctext);
1877     if (inst->pasteout_data_utf8)
1878         sfree(inst->pasteout_data_utf8);
1879     inst->pasteout_data = NULL;
1880     inst->pasteout_data_len = 0;
1881     inst->pasteout_data_ctext = NULL;
1882     inst->pasteout_data_ctext_len = 0;
1883     inst->pasteout_data_utf8 = NULL;
1884     inst->pasteout_data_utf8_len = 0;
1885     return TRUE;
1886 }
1887
1888 void request_paste(void *frontend)
1889 {
1890     struct gui_data *inst = (struct gui_data *)frontend;
1891     /*
1892      * In Unix, pasting is asynchronous: all we can do at the
1893      * moment is to call gtk_selection_convert(), and when the data
1894      * comes back _then_ we can call term_do_paste().
1895      */
1896
1897     if (!inst->direct_to_font) {
1898         /*
1899          * First we attempt to retrieve the selection as a UTF-8
1900          * string (which we will convert to the correct code page
1901          * before sending to the session, of course). If that
1902          * fails, selection_received() will be informed and will
1903          * fall back to an ordinary string.
1904          */
1905         gtk_selection_convert(inst->area, GDK_SELECTION_PRIMARY,
1906                               utf8_string_atom,
1907                               inst->input_event_time);
1908     } else {
1909         /*
1910          * If we're in direct-to-font mode, we disable UTF-8
1911          * pasting, and go straight to ordinary string data.
1912          */
1913         gtk_selection_convert(inst->area, GDK_SELECTION_PRIMARY,
1914                               GDK_SELECTION_TYPE_STRING,
1915                               inst->input_event_time);
1916     }
1917 }
1918
1919 gint idle_paste_func(gpointer data);   /* forward ref */
1920
1921 void selection_received(GtkWidget *widget, GtkSelectionData *seldata,
1922                         guint time, gpointer data)
1923 {
1924     struct gui_data *inst = (struct gui_data *)data;
1925     XTextProperty tp;
1926     char **list;
1927     char *text;
1928     int length, count, ret;
1929     int free_list_required = 0;
1930     int free_required = 0;
1931     int charset;
1932
1933     if (seldata->target == utf8_string_atom && seldata->length <= 0) {
1934         /*
1935          * Failed to get a UTF-8 selection string. Try compound
1936          * text next.
1937          */
1938         gtk_selection_convert(inst->area, GDK_SELECTION_PRIMARY,
1939                               compound_text_atom,
1940                               inst->input_event_time);
1941         return;
1942     }
1943
1944     if (seldata->target == compound_text_atom && seldata->length <= 0) {
1945         /*
1946          * Failed to get UTF-8 or compound text. Try an ordinary
1947          * string.
1948          */
1949         gtk_selection_convert(inst->area, GDK_SELECTION_PRIMARY,
1950                               GDK_SELECTION_TYPE_STRING,
1951                               inst->input_event_time);
1952         return;
1953     }
1954
1955     /*
1956      * If we have data, but it's not of a type we can deal with,
1957      * we have to ignore the data.
1958      */
1959     if (seldata->length > 0 &&
1960         seldata->type != GDK_SELECTION_TYPE_STRING &&
1961         seldata->type != compound_text_atom &&
1962         seldata->type != utf8_string_atom)
1963         return;
1964
1965     /*
1966      * If we have no data, try looking in a cut buffer.
1967      */
1968     if (seldata->length <= 0) {
1969         text = retrieve_cutbuffer(&length);
1970         if (length == 0)
1971             return;
1972         /* Xterm is rumoured to expect Latin-1, though I havn't checked the
1973          * source, so use that as a de-facto standard. */
1974         charset = CS_ISO8859_1;
1975         free_required = 1;
1976     } else {
1977         /*
1978          * Convert COMPOUND_TEXT into UTF-8.
1979          */
1980         if (seldata->type == compound_text_atom) {
1981             tp.value = seldata->data;
1982             tp.encoding = (Atom) seldata->type;
1983             tp.format = seldata->format;
1984             tp.nitems = seldata->length;
1985             ret = Xutf8TextPropertyToTextList(GDK_DISPLAY(), &tp,
1986                                               &list, &count);
1987             if (ret != 0 || count != 1) {
1988                 /*
1989                  * Compound text failed; fall back to STRING.
1990                  */
1991                 gtk_selection_convert(inst->area, GDK_SELECTION_PRIMARY,
1992                                       GDK_SELECTION_TYPE_STRING,
1993                                       inst->input_event_time);
1994                 return;
1995             }
1996             text = list[0];
1997             length = strlen(list[0]);
1998             charset = CS_UTF8;
1999             free_list_required = 1;
2000         } else {
2001             text = (char *)seldata->data;
2002             length = seldata->length;
2003             charset = (seldata->type == utf8_string_atom ?
2004                        CS_UTF8 : inst->ucsdata.line_codepage);
2005         }
2006     }
2007
2008     if (inst->pastein_data)
2009         sfree(inst->pastein_data);
2010
2011     inst->pastein_data = snewn(length, wchar_t);
2012     inst->pastein_data_len = length;
2013     inst->pastein_data_len =
2014         mb_to_wc(charset, 0, text, length,
2015                  inst->pastein_data, inst->pastein_data_len);
2016
2017     term_do_paste(inst->term);
2018
2019     if (free_list_required)
2020         XFreeStringList(list);
2021     if (free_required)
2022         XFree(text);
2023 }
2024
2025 void get_clip(void *frontend, wchar_t ** p, int *len)
2026 {
2027     struct gui_data *inst = (struct gui_data *)frontend;
2028
2029     if (p) {
2030         *p = inst->pastein_data;
2031         *len = inst->pastein_data_len;
2032     }
2033 }
2034
2035 static void set_window_titles(struct gui_data *inst)
2036 {
2037     /*
2038      * We must always call set_icon_name after calling set_title,
2039      * since set_title will write both names. Irritating, but such
2040      * is life.
2041      */
2042     gtk_window_set_title(GTK_WINDOW(inst->window), inst->wintitle);
2043     if (!conf_get_int(inst->conf, CONF_win_name_always))
2044         gdk_window_set_icon_name(inst->window->window, inst->icontitle);
2045 }
2046
2047 void set_title(void *frontend, char *title)
2048 {
2049     struct gui_data *inst = (struct gui_data *)frontend;
2050     sfree(inst->wintitle);
2051     inst->wintitle = dupstr(title);
2052     set_window_titles(inst);
2053 }
2054
2055 void set_icon(void *frontend, char *title)
2056 {
2057     struct gui_data *inst = (struct gui_data *)frontend;
2058     sfree(inst->icontitle);
2059     inst->icontitle = dupstr(title);
2060     set_window_titles(inst);
2061 }
2062
2063 void set_title_and_icon(void *frontend, char *title, char *icon)
2064 {
2065     struct gui_data *inst = (struct gui_data *)frontend;
2066     sfree(inst->wintitle);
2067     inst->wintitle = dupstr(title);
2068     sfree(inst->icontitle);
2069     inst->icontitle = dupstr(icon);
2070     set_window_titles(inst);
2071 }
2072
2073 void set_sbar(void *frontend, int total, int start, int page)
2074 {
2075     struct gui_data *inst = (struct gui_data *)frontend;
2076     if (!conf_get_int(inst->conf, CONF_scrollbar))
2077         return;
2078     inst->sbar_adjust->lower = 0;
2079     inst->sbar_adjust->upper = total;
2080     inst->sbar_adjust->value = start;
2081     inst->sbar_adjust->page_size = page;
2082     inst->sbar_adjust->step_increment = 1;
2083     inst->sbar_adjust->page_increment = page/2;
2084     inst->ignore_sbar = TRUE;
2085     gtk_adjustment_changed(inst->sbar_adjust);
2086     inst->ignore_sbar = FALSE;
2087 }
2088
2089 void scrollbar_moved(GtkAdjustment *adj, gpointer data)
2090 {
2091     struct gui_data *inst = (struct gui_data *)data;
2092
2093     if (!conf_get_int(inst->conf, CONF_scrollbar))
2094         return;
2095     if (!inst->ignore_sbar)
2096         term_scroll(inst->term, 1, (int)adj->value);
2097 }
2098
2099 void sys_cursor(void *frontend, int x, int y)
2100 {
2101     /*
2102      * This is meaningless under X.
2103      */
2104 }
2105
2106 /*
2107  * This is still called when mode==BELL_VISUAL, even though the
2108  * visual bell is handled entirely within terminal.c, because we
2109  * may want to perform additional actions on any kind of bell (for
2110  * example, taskbar flashing in Windows).
2111  */
2112 void do_beep(void *frontend, int mode)
2113 {
2114     if (mode == BELL_DEFAULT)
2115         gdk_beep();
2116 }
2117
2118 int char_width(Context ctx, int uc)
2119 {
2120     /*
2121      * Under X, any fixed-width font really _is_ fixed-width.
2122      * Double-width characters will be dealt with using a separate
2123      * font. For the moment we can simply return 1.
2124      * 
2125      * FIXME: but is that also true of Pango?
2126      */
2127     return 1;
2128 }
2129
2130 Context get_ctx(void *frontend)
2131 {
2132     struct gui_data *inst = (struct gui_data *)frontend;
2133     struct draw_ctx *dctx;
2134
2135     if (!inst->area->window)
2136         return NULL;
2137
2138     dctx = snew(struct draw_ctx);
2139     dctx->inst = inst;
2140     dctx->gc = gdk_gc_new(inst->area->window);
2141     return dctx;
2142 }
2143
2144 void free_ctx(Context ctx)
2145 {
2146     struct draw_ctx *dctx = (struct draw_ctx *)ctx;
2147     /* struct gui_data *inst = dctx->inst; */
2148     GdkGC *gc = dctx->gc;
2149     gdk_gc_unref(gc);
2150     sfree(dctx);
2151 }
2152
2153 /*
2154  * Draw a line of text in the window, at given character
2155  * coordinates, in given attributes.
2156  *
2157  * We are allowed to fiddle with the contents of `text'.
2158  */
2159 void do_text_internal(Context ctx, int x, int y, wchar_t *text, int len,
2160                       unsigned long attr, int lattr)
2161 {
2162     struct draw_ctx *dctx = (struct draw_ctx *)ctx;
2163     struct gui_data *inst = dctx->inst;
2164     GdkGC *gc = dctx->gc;
2165     int ncombining, combining;
2166     int nfg, nbg, t, fontid, shadow, rlen, widefactor, bold;
2167     int monochrome = gtk_widget_get_visual(inst->area)->depth == 1;
2168
2169     if (attr & TATTR_COMBINING) {
2170         ncombining = len;
2171         len = 1;
2172     } else
2173         ncombining = 1;
2174
2175     nfg = ((monochrome ? ATTR_DEFFG : (attr & ATTR_FGMASK)) >> ATTR_FGSHIFT);
2176     nbg = ((monochrome ? ATTR_DEFBG : (attr & ATTR_BGMASK)) >> ATTR_BGSHIFT);
2177     if (!!(attr & ATTR_REVERSE) ^ (monochrome && (attr & TATTR_ACTCURS))) {
2178         t = nfg;
2179         nfg = nbg;
2180         nbg = t;
2181     }
2182     if ((inst->bold_style & 2) && (attr & ATTR_BOLD)) {
2183         if (nfg < 16) nfg |= 8;
2184         else if (nfg >= 256) nfg |= 1;
2185     }
2186     if ((inst->bold_style & 2) && (attr & ATTR_BLINK)) {
2187         if (nbg < 16) nbg |= 8;
2188         else if (nbg >= 256) nbg |= 1;
2189     }
2190     if ((attr & TATTR_ACTCURS) && !monochrome) {
2191         nfg = 260;
2192         nbg = 261;
2193     }
2194
2195     fontid = shadow = 0;
2196
2197     if (attr & ATTR_WIDE) {
2198         widefactor = 2;
2199         fontid |= 2;
2200     } else {
2201         widefactor = 1;
2202     }
2203
2204     if ((attr & ATTR_BOLD) && (inst->bold_style & 1)) {
2205         bold = 1;
2206         fontid |= 1;
2207     } else {
2208         bold = 0;
2209     }
2210
2211     if (!inst->fonts[fontid]) {
2212         int i;
2213         /*
2214          * Fall back through font ids with subsets of this one's
2215          * set bits, in order.
2216          */
2217         for (i = fontid; i-- > 0 ;) {
2218             if (i & ~fontid)
2219                 continue;              /* some other bit is set */
2220             if (inst->fonts[i]) {
2221                 fontid = i;
2222                 break;
2223             }
2224         }
2225         assert(inst->fonts[fontid]);   /* we should at least have hit zero */
2226     }
2227
2228     if ((lattr & LATTR_MODE) != LATTR_NORM) {
2229         x *= 2;
2230         if (x >= inst->term->cols)
2231             return;
2232         if (x + len*2*widefactor > inst->term->cols)
2233             len = (inst->term->cols-x)/2/widefactor;/* trim to LH half */
2234         rlen = len * 2;
2235     } else
2236         rlen = len;
2237
2238     {
2239         GdkRectangle r;
2240
2241         r.x = x*inst->font_width+inst->window_border;
2242         r.y = y*inst->font_height+inst->window_border;
2243         r.width = rlen*widefactor*inst->font_width;
2244         r.height = inst->font_height;
2245         gdk_gc_set_clip_rectangle(gc, &r);
2246     }
2247
2248     gdk_gc_set_foreground(gc, &inst->cols[nbg]);
2249     gdk_draw_rectangle(inst->pixmap, gc, 1,
2250                        x*inst->font_width+inst->window_border,
2251                        y*inst->font_height+inst->window_border,
2252                        rlen*widefactor*inst->font_width, inst->font_height);
2253
2254     gdk_gc_set_foreground(gc, &inst->cols[nfg]);
2255     for (combining = 0; combining < ncombining; combining++) {
2256         unifont_draw_text(inst->pixmap, gc, inst->fonts[fontid],
2257                           x*inst->font_width+inst->window_border,
2258                           y*inst->font_height+inst->window_border+inst->fonts[0]->ascent,
2259                           text + combining, len, widefactor > 1,
2260                           bold, inst->font_width);
2261     }
2262
2263     if (attr & ATTR_UNDER) {
2264         int uheight = inst->fonts[0]->ascent + 1;
2265         if (uheight >= inst->font_height)
2266             uheight = inst->font_height - 1;
2267         gdk_draw_line(inst->pixmap, gc, x*inst->font_width+inst->window_border,
2268                       y*inst->font_height + uheight + inst->window_border,
2269                       (x+len)*widefactor*inst->font_width-1+inst->window_border,
2270                       y*inst->font_height + uheight + inst->window_border);
2271     }
2272
2273     if ((lattr & LATTR_MODE) != LATTR_NORM) {
2274         /*
2275          * I can't find any plausible StretchBlt equivalent in the
2276          * X server, so I'm going to do this the slow and painful
2277          * way. This will involve repeated calls to
2278          * gdk_draw_pixmap() to stretch the text horizontally. It's
2279          * O(N^2) in time and O(N) in network bandwidth, but you
2280          * try thinking of a better way. :-(
2281          */
2282         int i;
2283         for (i = 0; i < len * widefactor * inst->font_width; i++) {
2284             gdk_draw_pixmap(inst->pixmap, gc, inst->pixmap,
2285                             x*inst->font_width+inst->window_border + 2*i,
2286                             y*inst->font_height+inst->window_border,
2287                             x*inst->font_width+inst->window_border + 2*i+1,
2288                             y*inst->font_height+inst->window_border,
2289                             len * widefactor * inst->font_width - i, inst->font_height);
2290         }
2291         len *= 2;
2292         if ((lattr & LATTR_MODE) != LATTR_WIDE) {
2293             int dt, db;
2294             /* Now stretch vertically, in the same way. */
2295             if ((lattr & LATTR_MODE) == LATTR_BOT)
2296                 dt = 0, db = 1;
2297             else
2298                 dt = 1, db = 0;
2299             for (i = 0; i < inst->font_height; i+=2) {
2300                 gdk_draw_pixmap(inst->pixmap, gc, inst->pixmap,
2301                                 x*inst->font_width+inst->window_border,
2302                                 y*inst->font_height+inst->window_border+dt*i+db,
2303                                 x*inst->font_width+inst->window_border,
2304                                 y*inst->font_height+inst->window_border+dt*(i+1),
2305                                 len * widefactor * inst->font_width, inst->font_height-i-1);
2306             }
2307         }
2308     }
2309 }
2310
2311 void do_text(Context ctx, int x, int y, wchar_t *text, int len,
2312              unsigned long attr, int lattr)
2313 {
2314     struct draw_ctx *dctx = (struct draw_ctx *)ctx;
2315     struct gui_data *inst = dctx->inst;
2316     GdkGC *gc = dctx->gc;
2317     int widefactor;
2318
2319     do_text_internal(ctx, x, y, text, len, attr, lattr);
2320
2321     if (attr & ATTR_WIDE) {
2322         widefactor = 2;
2323     } else {
2324         widefactor = 1;
2325     }
2326
2327     if ((lattr & LATTR_MODE) != LATTR_NORM) {
2328         x *= 2;
2329         if (x >= inst->term->cols)
2330             return;
2331         if (x + len*2*widefactor > inst->term->cols)
2332             len = (inst->term->cols-x)/2/widefactor;/* trim to LH half */
2333         len *= 2;
2334     }
2335
2336     gdk_draw_pixmap(inst->area->window, gc, inst->pixmap,
2337                     x*inst->font_width+inst->window_border,
2338                     y*inst->font_height+inst->window_border,
2339                     x*inst->font_width+inst->window_border,
2340                     y*inst->font_height+inst->window_border,
2341                     len*widefactor*inst->font_width, inst->font_height);
2342 }
2343
2344 void do_cursor(Context ctx, int x, int y, wchar_t *text, int len,
2345                unsigned long attr, int lattr)
2346 {
2347     struct draw_ctx *dctx = (struct draw_ctx *)ctx;
2348     struct gui_data *inst = dctx->inst;
2349     GdkGC *gc = dctx->gc;
2350
2351     int active, passive, widefactor;
2352
2353     if (attr & TATTR_PASCURS) {
2354         attr &= ~TATTR_PASCURS;
2355         passive = 1;
2356     } else
2357         passive = 0;
2358     if ((attr & TATTR_ACTCURS) && inst->cursor_type != 0) {
2359         attr &= ~TATTR_ACTCURS;
2360         active = 1;
2361     } else
2362         active = 0;
2363     do_text_internal(ctx, x, y, text, len, attr, lattr);
2364
2365     if (attr & TATTR_COMBINING)
2366         len = 1;
2367
2368     if (attr & ATTR_WIDE) {
2369         widefactor = 2;
2370     } else {
2371         widefactor = 1;
2372     }
2373
2374     if ((lattr & LATTR_MODE) != LATTR_NORM) {
2375         x *= 2;
2376         if (x >= inst->term->cols)
2377             return;
2378         if (x + len*2*widefactor > inst->term->cols)
2379             len = (inst->term->cols-x)/2/widefactor;/* trim to LH half */
2380         len *= 2;
2381     }
2382
2383     if (inst->cursor_type == 0) {
2384         /*
2385          * An active block cursor will already have been done by
2386          * the above do_text call, so we only need to do anything
2387          * if it's passive.
2388          */
2389         if (passive) {
2390             gdk_gc_set_foreground(gc, &inst->cols[261]);
2391             gdk_draw_rectangle(inst->pixmap, gc, 0,
2392                                x*inst->font_width+inst->window_border,
2393                                y*inst->font_height+inst->window_border,
2394                                len*widefactor*inst->font_width-1, inst->font_height-1);
2395         }
2396     } else {
2397         int uheight;
2398         int startx, starty, dx, dy, length, i;
2399
2400         int char_width;
2401
2402         if ((attr & ATTR_WIDE) || (lattr & LATTR_MODE) != LATTR_NORM)
2403             char_width = 2*inst->font_width;
2404         else
2405             char_width = inst->font_width;
2406
2407         if (inst->cursor_type == 1) {
2408             uheight = inst->fonts[0]->ascent + 1;
2409             if (uheight >= inst->font_height)
2410                 uheight = inst->font_height - 1;
2411
2412             startx = x * inst->font_width + inst->window_border;
2413             starty = y * inst->font_height + inst->window_border + uheight;
2414             dx = 1;
2415             dy = 0;
2416             length = len * widefactor * char_width;
2417         } else {
2418             int xadjust = 0;
2419             if (attr & TATTR_RIGHTCURS)
2420                 xadjust = char_width - 1;
2421             startx = x * inst->font_width + inst->window_border + xadjust;
2422             starty = y * inst->font_height + inst->window_border;
2423             dx = 0;
2424             dy = 1;
2425             length = inst->font_height;
2426         }
2427
2428         gdk_gc_set_foreground(gc, &inst->cols[261]);
2429         if (passive) {
2430             for (i = 0; i < length; i++) {
2431                 if (i % 2 == 0) {
2432                     gdk_draw_point(inst->pixmap, gc, startx, starty);
2433                 }
2434                 startx += dx;
2435                 starty += dy;
2436             }
2437         } else if (active) {
2438             gdk_draw_line(inst->pixmap, gc, startx, starty,
2439                           startx + (length-1) * dx, starty + (length-1) * dy);
2440         } /* else no cursor (e.g., blinked off) */
2441     }
2442
2443     gdk_draw_pixmap(inst->area->window, gc, inst->pixmap,
2444                     x*inst->font_width+inst->window_border,
2445                     y*inst->font_height+inst->window_border,
2446                     x*inst->font_width+inst->window_border,
2447                     y*inst->font_height+inst->window_border,
2448                     len*widefactor*inst->font_width, inst->font_height);
2449
2450 #if GTK_CHECK_VERSION(2,0,0)
2451     {
2452         GdkRectangle cursorrect;
2453         cursorrect.x = x*inst->font_width+inst->window_border;
2454         cursorrect.y = y*inst->font_height+inst->window_border;
2455         cursorrect.width = len*widefactor*inst->font_width;
2456         cursorrect.height = inst->font_height;
2457         gtk_im_context_set_cursor_location(inst->imc, &cursorrect);
2458     }
2459 #endif
2460 }
2461
2462 GdkCursor *make_mouse_ptr(struct gui_data *inst, int cursor_val)
2463 {
2464     /*
2465      * Truly hideous hack: GTK doesn't allow us to set the mouse
2466      * cursor foreground and background colours unless we've _also_
2467      * created our own cursor from bitmaps. Therefore, I need to
2468      * load the `cursor' font and draw glyphs from it on to
2469      * pixmaps, in order to construct my cursors with the fg and bg
2470      * I want. This is a gross hack, but it's more self-contained
2471      * than linking in Xlib to find the X window handle to
2472      * inst->area and calling XRecolorCursor, and it's more
2473      * futureproof than hard-coding the shapes as bitmap arrays.
2474      */
2475     static GdkFont *cursor_font = NULL;
2476     GdkPixmap *source, *mask;
2477     GdkGC *gc;
2478     GdkColor cfg = { 0, 65535, 65535, 65535 };
2479     GdkColor cbg = { 0, 0, 0, 0 };
2480     GdkColor dfg = { 1, 65535, 65535, 65535 };
2481     GdkColor dbg = { 0, 0, 0, 0 };
2482     GdkCursor *ret;
2483     gchar text[2];
2484     gint lb, rb, wid, asc, desc, w, h, x, y;
2485
2486     if (cursor_val == -2) {
2487         gdk_font_unref(cursor_font);
2488         return NULL;
2489     }
2490
2491     if (cursor_val >= 0 && !cursor_font) {
2492         cursor_font = gdk_font_load("cursor");
2493         if (cursor_font)
2494             gdk_font_ref(cursor_font);
2495     }
2496
2497     /*
2498      * Get the text extent of the cursor in question. We use the
2499      * mask character for this, because it's typically slightly
2500      * bigger than the main character.
2501      */
2502     if (cursor_val >= 0) {
2503         text[1] = '\0';
2504         text[0] = (char)cursor_val + 1;
2505         gdk_string_extents(cursor_font, text, &lb, &rb, &wid, &asc, &desc);
2506         w = rb-lb; h = asc+desc; x = -lb; y = asc;
2507     } else {
2508         w = h = 1;
2509         x = y = 0;
2510     }
2511
2512     source = gdk_pixmap_new(NULL, w, h, 1);
2513     mask = gdk_pixmap_new(NULL, w, h, 1);
2514
2515     /*
2516      * Draw the mask character on the mask pixmap.
2517      */
2518     gc = gdk_gc_new(mask);
2519     gdk_gc_set_foreground(gc, &dbg);
2520     gdk_draw_rectangle(mask, gc, 1, 0, 0, w, h);
2521     if (cursor_val >= 0) {
2522         text[1] = '\0';
2523         text[0] = (char)cursor_val + 1;
2524         gdk_gc_set_foreground(gc, &dfg);
2525         gdk_draw_text(mask, cursor_font, gc, x, y, text, 1);
2526     }
2527     gdk_gc_unref(gc);
2528
2529     /*
2530      * Draw the main character on the source pixmap.
2531      */
2532     gc = gdk_gc_new(source);
2533     gdk_gc_set_foreground(gc, &dbg);
2534     gdk_draw_rectangle(source, gc, 1, 0, 0, w, h);
2535     if (cursor_val >= 0) {
2536         text[1] = '\0';
2537         text[0] = (char)cursor_val;
2538         gdk_gc_set_foreground(gc, &dfg);
2539         gdk_draw_text(source, cursor_font, gc, x, y, text, 1);
2540     }
2541     gdk_gc_unref(gc);
2542
2543     /*
2544      * Create the cursor.
2545      */
2546     ret = gdk_cursor_new_from_pixmap(source, mask, &cfg, &cbg, x, y);
2547
2548     /*
2549      * Clean up.
2550      */
2551     gdk_pixmap_unref(source);
2552     gdk_pixmap_unref(mask);
2553
2554     return ret;
2555 }
2556
2557 void modalfatalbox(char *p, ...)
2558 {
2559     va_list ap;
2560     fprintf(stderr, "FATAL ERROR: ");
2561     va_start(ap, p);
2562     vfprintf(stderr, p, ap);
2563     va_end(ap);
2564     fputc('\n', stderr);
2565     exit(1);
2566 }
2567
2568 void cmdline_error(char *p, ...)
2569 {
2570     va_list ap;
2571     fprintf(stderr, "%s: ", appname);
2572     va_start(ap, p);
2573     vfprintf(stderr, p, ap);
2574     va_end(ap);
2575     fputc('\n', stderr);
2576     exit(1);
2577 }
2578
2579 char *get_x_display(void *frontend)
2580 {
2581     return gdk_get_display();
2582 }
2583
2584 long get_windowid(void *frontend)
2585 {
2586     struct gui_data *inst = (struct gui_data *)frontend;
2587     return (long)GDK_WINDOW_XWINDOW(inst->area->window);
2588 }
2589
2590 static void help(FILE *fp) {
2591     if(fprintf(fp,
2592 "pterm option summary:\n"
2593 "\n"
2594 "  --display DISPLAY         Specify X display to use (note '--')\n"
2595 "  -name PREFIX              Prefix when looking up resources (default: pterm)\n"
2596 "  -fn FONT                  Normal text font\n"
2597 "  -fb FONT                  Bold text font\n"
2598 "  -geometry GEOMETRY        Position and size of window (size in characters)\n"
2599 "  -sl LINES                 Number of lines of scrollback\n"
2600 "  -fg COLOUR, -bg COLOUR    Foreground/background colour\n"
2601 "  -bfg COLOUR, -bbg COLOUR  Foreground/background bold colour\n"
2602 "  -cfg COLOUR, -bfg COLOUR  Foreground/background cursor colour\n"
2603 "  -T TITLE                  Window title\n"
2604 "  -ut, +ut                  Do(default) or do not update utmp\n"
2605 "  -ls, +ls                  Do(default) or do not make shell a login shell\n"
2606 "  -sb, +sb                  Do(default) or do not display a scrollbar\n"
2607 "  -log PATH                 Log all output to a file\n"
2608 "  -nethack                  Map numeric keypad to hjklyubn direction keys\n"
2609 "  -xrm RESOURCE-STRING      Set an X resource\n"
2610 "  -e COMMAND [ARGS...]      Execute command (consumes all remaining args)\n"
2611          ) < 0 || fflush(fp) < 0) {
2612         perror("output error");
2613         exit(1);
2614     }
2615 }
2616
2617 static void version(FILE *fp) {
2618     if(fprintf(fp, "%s: %s\n", appname, ver) < 0 || fflush(fp) < 0) {
2619         perror("output error");
2620         exit(1);
2621     }
2622 }
2623
2624 int do_cmdline(int argc, char **argv, int do_everything, int *allow_launch,
2625                struct gui_data *inst, Conf *conf)
2626 {
2627     int err = 0;
2628     char *val;
2629
2630     /*
2631      * Macros to make argument handling easier. Note that because
2632      * they need to call `continue', they cannot be contained in
2633      * the usual do {...} while (0) wrapper to make them
2634      * syntactically single statements; hence it is not legal to
2635      * use one of these macros as an unbraced statement between
2636      * `if' and `else'.
2637      */
2638 #define EXPECTS_ARG { \
2639     if (--argc <= 0) { \
2640         err = 1; \
2641         fprintf(stderr, "%s: %s expects an argument\n", appname, p); \
2642         continue; \
2643     } else \
2644         val = *++argv; \
2645 }
2646 #define SECOND_PASS_ONLY { if (!do_everything) continue; }
2647
2648     while (--argc > 0) {
2649         char *p = *++argv;
2650         int ret;
2651
2652         /*
2653          * Shameless cheating. Debian requires all X terminal
2654          * emulators to support `-T title'; but
2655          * cmdline_process_param will eat -T (it means no-pty) and
2656          * complain that pterm doesn't support it. So, in pterm
2657          * only, we convert -T into -title.
2658          */
2659         if ((cmdline_tooltype & TOOLTYPE_NONNETWORK) &&
2660             !strcmp(p, "-T"))
2661             p = "-title";
2662
2663         ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
2664                                     do_everything ? 1 : -1, conf);
2665
2666         if (ret == -2) {
2667             cmdline_error("option \"%s\" requires an argument", p);
2668         } else if (ret == 2) {
2669             --argc, ++argv;            /* skip next argument */
2670             continue;
2671         } else if (ret == 1) {
2672             continue;
2673         }
2674
2675         if (!strcmp(p, "-fn") || !strcmp(p, "-font")) {
2676             FontSpec *fs;
2677             EXPECTS_ARG;
2678             SECOND_PASS_ONLY;
2679             fs = fontspec_new(val);
2680             conf_set_fontspec(conf, CONF_font, fs);
2681             fontspec_free(fs);
2682
2683         } else if (!strcmp(p, "-fb")) {
2684             FontSpec *fs;
2685             EXPECTS_ARG;
2686             SECOND_PASS_ONLY;
2687             fs = fontspec_new(val);
2688             conf_set_fontspec(conf, CONF_boldfont, fs);
2689             fontspec_free(fs);
2690
2691         } else if (!strcmp(p, "-fw")) {
2692             FontSpec *fs;
2693             EXPECTS_ARG;
2694             SECOND_PASS_ONLY;
2695             fs = fontspec_new(val);
2696             conf_set_fontspec(conf, CONF_widefont, fs);
2697             fontspec_free(fs);
2698
2699         } else if (!strcmp(p, "-fwb")) {
2700             FontSpec *fs;
2701             EXPECTS_ARG;
2702             SECOND_PASS_ONLY;
2703             fs = fontspec_new(val);
2704             conf_set_fontspec(conf, CONF_wideboldfont, fs);
2705             fontspec_free(fs);
2706
2707         } else if (!strcmp(p, "-cs")) {
2708             EXPECTS_ARG;
2709             SECOND_PASS_ONLY;
2710             conf_set_str(conf, CONF_line_codepage, val);
2711
2712         } else if (!strcmp(p, "-geometry")) {
2713             int flags, x, y;
2714             unsigned int w, h;
2715             EXPECTS_ARG;
2716             SECOND_PASS_ONLY;
2717
2718             flags = XParseGeometry(val, &x, &y, &w, &h);
2719             if (flags & WidthValue)
2720                 conf_set_int(conf, CONF_width, w);
2721             if (flags & HeightValue)
2722                 conf_set_int(conf, CONF_height, h);
2723
2724             if (flags & (XValue | YValue)) {
2725                 inst->xpos = x;
2726                 inst->ypos = y;
2727                 inst->gotpos = TRUE;
2728                 inst->gravity = ((flags & XNegative ? 1 : 0) |
2729                                  (flags & YNegative ? 2 : 0));
2730             }
2731
2732         } else if (!strcmp(p, "-sl")) {
2733             EXPECTS_ARG;
2734             SECOND_PASS_ONLY;
2735             conf_set_int(conf, CONF_savelines, atoi(val));
2736
2737         } else if (!strcmp(p, "-fg") || !strcmp(p, "-bg") ||
2738                    !strcmp(p, "-bfg") || !strcmp(p, "-bbg") ||
2739                    !strcmp(p, "-cfg") || !strcmp(p, "-cbg")) {
2740             GdkColor col;
2741
2742             EXPECTS_ARG;
2743             SECOND_PASS_ONLY;
2744             if (!gdk_color_parse(val, &col)) {
2745                 err = 1;
2746                 fprintf(stderr, "%s: unable to parse colour \"%s\"\n",
2747                         appname, val);
2748             } else {
2749                 int index;
2750                 index = (!strcmp(p, "-fg") ? 0 :
2751                          !strcmp(p, "-bg") ? 2 :
2752                          !strcmp(p, "-bfg") ? 1 :
2753                          !strcmp(p, "-bbg") ? 3 :
2754                          !strcmp(p, "-cfg") ? 4 :
2755                          !strcmp(p, "-cbg") ? 5 : -1);
2756                 assert(index != -1);
2757                 conf_set_int_int(conf, CONF_colours, index*3+0, col.red / 256);
2758                 conf_set_int_int(conf, CONF_colours, index*3+1,col.green/ 256);
2759                 conf_set_int_int(conf, CONF_colours, index*3+2, col.blue/ 256);
2760             }
2761
2762         } else if (use_pty_argv && !strcmp(p, "-e")) {
2763             /* This option swallows all further arguments. */
2764             if (!do_everything)
2765                 break;
2766
2767             if (--argc > 0) {
2768                 int i;
2769                 pty_argv = snewn(argc+1, char *);
2770                 ++argv;
2771                 for (i = 0; i < argc; i++)
2772                     pty_argv[i] = argv[i];
2773                 pty_argv[argc] = NULL;
2774                 break;                 /* finished command-line processing */
2775             } else
2776                 err = 1, fprintf(stderr, "%s: -e expects an argument\n",
2777                                  appname);
2778
2779         } else if (!strcmp(p, "-title")) {
2780             EXPECTS_ARG;
2781             SECOND_PASS_ONLY;
2782             conf_set_str(conf, CONF_wintitle, val);
2783
2784         } else if (!strcmp(p, "-log")) {
2785             Filename *fn;
2786             EXPECTS_ARG;
2787             SECOND_PASS_ONLY;
2788             fn = filename_from_str(val);
2789             conf_set_filename(conf, CONF_logfilename, fn);
2790             conf_set_int(conf, CONF_logtype, LGTYP_DEBUG);
2791             filename_free(fn);
2792
2793         } else if (!strcmp(p, "-ut-") || !strcmp(p, "+ut")) {
2794             SECOND_PASS_ONLY;
2795             conf_set_int(conf, CONF_stamp_utmp, 0);
2796
2797         } else if (!strcmp(p, "-ut")) {
2798             SECOND_PASS_ONLY;
2799             conf_set_int(conf, CONF_stamp_utmp, 1);
2800
2801         } else if (!strcmp(p, "-ls-") || !strcmp(p, "+ls")) {
2802             SECOND_PASS_ONLY;
2803             conf_set_int(conf, CONF_login_shell, 0);
2804
2805         } else if (!strcmp(p, "-ls")) {
2806             SECOND_PASS_ONLY;
2807             conf_set_int(conf, CONF_login_shell, 1);
2808
2809         } else if (!strcmp(p, "-nethack")) {
2810             SECOND_PASS_ONLY;
2811             conf_set_int(conf, CONF_nethack_keypad, 1);
2812
2813         } else if (!strcmp(p, "-sb-") || !strcmp(p, "+sb")) {
2814             SECOND_PASS_ONLY;
2815             conf_set_int(conf, CONF_scrollbar, 0);
2816
2817         } else if (!strcmp(p, "-sb")) {
2818             SECOND_PASS_ONLY;
2819             conf_set_int(conf, CONF_scrollbar, 1);
2820
2821         } else if (!strcmp(p, "-name")) {
2822             EXPECTS_ARG;
2823             app_name = val;
2824
2825         } else if (!strcmp(p, "-xrm")) {
2826             EXPECTS_ARG;
2827             provide_xrm_string(val);
2828
2829         } else if(!strcmp(p, "-help") || !strcmp(p, "--help")) {
2830             help(stdout);
2831             exit(0);
2832
2833         } else if(!strcmp(p, "-version") || !strcmp(p, "--version")) {
2834             version(stdout);
2835             exit(0);
2836
2837         } else if (!strcmp(p, "-pgpfp")) {
2838             pgp_fingerprints();
2839             exit(1);
2840
2841         } else if(p[0] != '-' && (!do_everything ||
2842                                   process_nonoption_arg(p, conf,
2843                                                         allow_launch))) {
2844             /* do nothing */
2845
2846         } else {
2847             err = 1;
2848             fprintf(stderr, "%s: unrecognized option '%s'\n", appname, p);
2849         }
2850     }
2851
2852     return err;
2853 }
2854
2855 int uxsel_input_add(int fd, int rwx) {
2856     int flags = 0;
2857     if (rwx & 1) flags |= GDK_INPUT_READ;
2858     if (rwx & 2) flags |= GDK_INPUT_WRITE;
2859     if (rwx & 4) flags |= GDK_INPUT_EXCEPTION;
2860     assert(flags);
2861     return gdk_input_add(fd, flags, fd_input_func, NULL);
2862 }
2863
2864 void uxsel_input_remove(int id) {
2865     gdk_input_remove(id);
2866 }
2867
2868 char *setup_fonts_ucs(struct gui_data *inst)
2869 {
2870     int shadowbold = conf_get_int(inst->conf, CONF_shadowbold);
2871     int shadowboldoffset = conf_get_int(inst->conf, CONF_shadowboldoffset);
2872     FontSpec *fs;
2873     unifont *fonts[4];
2874     int i;
2875
2876     fs = conf_get_fontspec(inst->conf, CONF_font);
2877     fonts[0] = multifont_create(inst->area, fs->name, FALSE, FALSE,
2878                                 shadowboldoffset, shadowbold);
2879     if (!fonts[0]) {
2880         return dupprintf("unable to load font \"%s\"", fs->name);
2881     }
2882
2883     fs = conf_get_fontspec(inst->conf, CONF_boldfont);
2884     if (shadowbold || !fs->name[0]) {
2885         fonts[1] = NULL;
2886     } else {
2887         fonts[1] = multifont_create(inst->area, fs->name, FALSE, TRUE,
2888                                     shadowboldoffset, shadowbold);
2889         if (!fonts[1]) {
2890             if (fonts[0])
2891                 unifont_destroy(fonts[0]);
2892             return dupprintf("unable to load bold font \"%s\"", fs->name);
2893         }
2894     }
2895
2896     fs = conf_get_fontspec(inst->conf, CONF_widefont);
2897     if (fs->name[0]) {
2898         fonts[2] = multifont_create(inst->area, fs->name, TRUE, FALSE,
2899                                     shadowboldoffset, shadowbold);
2900         if (!fonts[2]) {
2901             for (i = 0; i < 2; i++)
2902                 if (fonts[i])
2903                     unifont_destroy(fonts[i]);
2904             return dupprintf("unable to load wide font \"%s\"", fs->name);
2905         }
2906     } else {
2907         fonts[2] = NULL;
2908     }
2909
2910     fs = conf_get_fontspec(inst->conf, CONF_wideboldfont);
2911     if (shadowbold || !fs->name[0]) {
2912         fonts[3] = NULL;
2913     } else {
2914         fonts[3] = multifont_create(inst->area, fs->name, TRUE, TRUE,
2915                                     shadowboldoffset, shadowbold);
2916         if (!fonts[3]) {
2917             for (i = 0; i < 3; i++)
2918                 if (fonts[i])
2919                     unifont_destroy(fonts[i]);
2920             return dupprintf("unable to load wide bold font \"%s\"", fs->name);
2921         }
2922     }
2923
2924     /*
2925      * Now we've got past all the possible error conditions, we can
2926      * actually update our state.
2927      */
2928
2929     for (i = 0; i < 4; i++) {
2930         if (inst->fonts[i])
2931             unifont_destroy(inst->fonts[i]);
2932         inst->fonts[i] = fonts[i];
2933     }
2934
2935     inst->font_width = inst->fonts[0]->width;
2936     inst->font_height = inst->fonts[0]->height;
2937
2938     inst->direct_to_font = init_ucs(&inst->ucsdata,
2939                                     conf_get_str(inst->conf, CONF_line_codepage),
2940                                     conf_get_int(inst->conf, CONF_utf8_override),
2941                                     inst->fonts[0]->public_charset,
2942                                     conf_get_int(inst->conf, CONF_vtmode));
2943
2944     return NULL;
2945 }
2946
2947 void set_geom_hints(struct gui_data *inst)
2948 {
2949     GdkGeometry geom;
2950     geom.min_width = inst->font_width + 2*inst->window_border;
2951     geom.min_height = inst->font_height + 2*inst->window_border;
2952     geom.max_width = geom.max_height = -1;
2953     geom.base_width = 2*inst->window_border;
2954     geom.base_height = 2*inst->window_border;
2955     geom.width_inc = inst->font_width;
2956     geom.height_inc = inst->font_height;
2957     geom.min_aspect = geom.max_aspect = 0;
2958     gtk_window_set_geometry_hints(GTK_WINDOW(inst->window), inst->area, &geom,
2959                                   GDK_HINT_MIN_SIZE | GDK_HINT_BASE_SIZE |
2960                                   GDK_HINT_RESIZE_INC);
2961 }
2962
2963 void clear_scrollback_menuitem(GtkMenuItem *item, gpointer data)
2964 {
2965     struct gui_data *inst = (struct gui_data *)data;
2966     term_clrsb(inst->term);
2967 }
2968
2969 void reset_terminal_menuitem(GtkMenuItem *item, gpointer data)
2970 {
2971     struct gui_data *inst = (struct gui_data *)data;
2972     term_pwron(inst->term, TRUE);
2973     if (inst->ldisc)
2974         ldisc_send(inst->ldisc, NULL, 0, 0);
2975 }
2976
2977 void copy_all_menuitem(GtkMenuItem *item, gpointer data)
2978 {
2979     struct gui_data *inst = (struct gui_data *)data;
2980     term_copyall(inst->term);
2981 }
2982
2983 void special_menuitem(GtkMenuItem *item, gpointer data)
2984 {
2985     struct gui_data *inst = (struct gui_data *)data;
2986     int code = GPOINTER_TO_INT(gtk_object_get_data(GTK_OBJECT(item),
2987                                                    "user-data"));
2988
2989     if (inst->back)
2990         inst->back->special(inst->backhandle, code);
2991 }
2992
2993 void about_menuitem(GtkMenuItem *item, gpointer data)
2994 {
2995     struct gui_data *inst = (struct gui_data *)data;
2996     about_box(inst->window);
2997 }
2998
2999 void event_log_menuitem(GtkMenuItem *item, gpointer data)
3000 {
3001     struct gui_data *inst = (struct gui_data *)data;
3002     showeventlog(inst->eventlogstuff, inst->window);
3003 }
3004
3005 void change_settings_menuitem(GtkMenuItem *item, gpointer data)
3006 {
3007     /* This maps colour indices in inst->conf to those used in inst->cols. */
3008     static const int ww[] = {
3009         256, 257, 258, 259, 260, 261,
3010         0, 8, 1, 9, 2, 10, 3, 11,
3011         4, 12, 5, 13, 6, 14, 7, 15
3012     };
3013     struct gui_data *inst = (struct gui_data *)data;
3014     char *title;
3015     Conf *oldconf, *newconf;
3016     int i, j, need_size;
3017
3018     assert(lenof(ww) == NCFGCOLOURS);
3019
3020     if (inst->reconfiguring)
3021       return;
3022     else
3023       inst->reconfiguring = TRUE;
3024
3025     title = dupcat(appname, " Reconfiguration", NULL);
3026
3027     oldconf = inst->conf;
3028     newconf = conf_copy(inst->conf);
3029
3030     if (do_config_box(title, newconf, 1,
3031                       inst->back?inst->back->cfg_info(inst->backhandle):0)) {
3032         inst->conf = newconf;
3033
3034         /* Pass new config data to the logging module */
3035         log_reconfig(inst->logctx, inst->conf);
3036         /*
3037          * Flush the line discipline's edit buffer in the case
3038          * where local editing has just been disabled.
3039          */
3040         if (inst->ldisc) {
3041             ldisc_configure(inst->ldisc, inst->conf);
3042             ldisc_send(inst->ldisc, NULL, 0, 0);
3043         }
3044         /* Pass new config data to the terminal */
3045         term_reconfig(inst->term, inst->conf);
3046         /* Pass new config data to the back end */
3047         if (inst->back)
3048             inst->back->reconfig(inst->backhandle, inst->conf);
3049
3050         cache_conf_values(inst);
3051
3052         /*
3053          * Just setting inst->conf is sufficient to cause colour
3054          * setting changes to appear on the next ESC]R palette
3055          * reset. But we should also check whether any colour
3056          * settings have been changed, and revert the ones that have
3057          * to the new default, on the assumption that the user is
3058          * most likely to want an immediate update.
3059          */
3060         for (i = 0; i < NCFGCOLOURS; i++) {
3061             for (j = 0; j < 3; j++)
3062                 if (conf_get_int_int(oldconf, CONF_colours, i*3+j) !=
3063                     conf_get_int_int(newconf, CONF_colours, i*3+j))
3064                     break;
3065             if (j < 3) {
3066                 real_palette_set(inst, ww[i],
3067                                  conf_get_int_int(newconf,CONF_colours,i*3+0),
3068                                  conf_get_int_int(newconf,CONF_colours,i*3+1),
3069                                  conf_get_int_int(newconf,CONF_colours,i*3+2));
3070
3071                 /*
3072                  * If the default background has changed, we must
3073                  * repaint the space in between the window border
3074                  * and the text area.
3075                  */
3076                 if (ww[i] == 258) {
3077                     set_window_background(inst);
3078                     draw_backing_rect(inst);
3079                 }
3080             }
3081         }
3082
3083         /*
3084          * If the scrollbar needs to be shown, hidden, or moved
3085          * from one end to the other of the window, do so now.
3086          */
3087         if (conf_get_int(oldconf, CONF_scrollbar) !=
3088             conf_get_int(newconf, CONF_scrollbar)) {
3089             if (conf_get_int(newconf, CONF_scrollbar))
3090                 gtk_widget_show(inst->sbar);
3091             else
3092                 gtk_widget_hide(inst->sbar);
3093         }
3094         if (conf_get_int(oldconf, CONF_scrollbar_on_left) !=
3095             conf_get_int(newconf, CONF_scrollbar_on_left)) {
3096             gtk_box_reorder_child(inst->hbox, inst->sbar,
3097                                   conf_get_int(newconf, CONF_scrollbar_on_left)
3098                                   ? 0 : 1);
3099         }
3100
3101         /*
3102          * Change the window title, if required.
3103          */
3104         if (strcmp(conf_get_str(oldconf, CONF_wintitle),
3105                    conf_get_str(newconf, CONF_wintitle)))
3106             set_title(inst, conf_get_str(newconf, CONF_wintitle));
3107         set_window_titles(inst);
3108
3109         /*
3110          * Redo the whole tangled fonts and Unicode mess if
3111          * necessary.
3112          */
3113         need_size = FALSE;
3114         if (strcmp(conf_get_fontspec(oldconf, CONF_font)->name,
3115                    conf_get_fontspec(newconf, CONF_font)->name) ||
3116             strcmp(conf_get_fontspec(oldconf, CONF_boldfont)->name,
3117                    conf_get_fontspec(newconf, CONF_boldfont)->name) ||
3118             strcmp(conf_get_fontspec(oldconf, CONF_widefont)->name,
3119                    conf_get_fontspec(newconf, CONF_widefont)->name) ||
3120             strcmp(conf_get_fontspec(oldconf, CONF_wideboldfont)->name,
3121                    conf_get_fontspec(newconf, CONF_wideboldfont)->name) ||
3122             strcmp(conf_get_str(oldconf, CONF_line_codepage),
3123                    conf_get_str(newconf, CONF_line_codepage)) ||
3124             conf_get_int(oldconf, CONF_utf8_override) !=
3125             conf_get_int(newconf, CONF_utf8_override) ||
3126             conf_get_int(oldconf, CONF_vtmode) !=
3127             conf_get_int(newconf, CONF_vtmode) ||
3128             conf_get_int(oldconf, CONF_shadowbold) !=
3129             conf_get_int(newconf, CONF_shadowbold) ||
3130             conf_get_int(oldconf, CONF_shadowboldoffset) !=
3131             conf_get_int(newconf, CONF_shadowboldoffset)) {
3132             char *errmsg = setup_fonts_ucs(inst);
3133             if (errmsg) {
3134                 char *msgboxtext =
3135                     dupprintf("Could not change fonts in terminal window: %s\n",
3136                               errmsg);
3137                 messagebox(inst->window, "Font setup error", msgboxtext,
3138                            string_width("Could not change fonts in terminal window:"),
3139                            "OK", 'o', +1, 1,
3140                            NULL);
3141                 sfree(msgboxtext);
3142                 sfree(errmsg);
3143             } else {
3144                 need_size = TRUE;
3145             }
3146         }
3147
3148         /*
3149          * Resize the window.
3150          */
3151         if (conf_get_int(oldconf, CONF_width) !=
3152             conf_get_int(newconf, CONF_width) ||
3153             conf_get_int(oldconf, CONF_height) !=
3154             conf_get_int(newconf, CONF_height) ||
3155             conf_get_int(oldconf, CONF_window_border) !=
3156             conf_get_int(newconf, CONF_window_border) ||
3157             need_size) {
3158             set_geom_hints(inst);
3159             request_resize(inst, conf_get_int(newconf, CONF_width),
3160                            conf_get_int(newconf, CONF_height));
3161         } else {
3162             /*
3163              * The above will have caused a call to term_size() for
3164              * us if it happened. If the user has fiddled with only
3165              * the scrollback size, the above will not have
3166              * happened and we will need an explicit term_size()
3167              * here.
3168              */
3169             if (conf_get_int(oldconf, CONF_savelines) !=
3170                 conf_get_int(newconf, CONF_savelines))
3171                 term_size(inst->term, inst->term->rows, inst->term->cols,
3172                           conf_get_int(newconf, CONF_savelines));
3173         }
3174
3175         term_invalidate(inst->term);
3176
3177         /*
3178          * We do an explicit full redraw here to ensure the window
3179          * border has been redrawn as well as the text area.
3180          */
3181         gtk_widget_queue_draw(inst->area);
3182
3183         conf_free(oldconf);
3184     } else {
3185         conf_free(newconf);
3186     }
3187     sfree(title);
3188     inst->reconfiguring = FALSE;
3189 }
3190
3191 void fork_and_exec_self(struct gui_data *inst, int fd_to_close, ...)
3192 {
3193     /*
3194      * Re-execing ourself is not an exact science under Unix. I do
3195      * the best I can by using /proc/self/exe if available and by
3196      * assuming argv[0] can be found on $PATH if not.
3197      * 
3198      * Note that we also have to reconstruct the elements of the
3199      * original argv which gtk swallowed, since the user wants the
3200      * new session to appear on the same X display as the old one.
3201      */
3202     char **args;
3203     va_list ap;
3204     int i, n;
3205     int pid;
3206
3207     /*
3208      * Collect the arguments with which to re-exec ourself.
3209      */
3210     va_start(ap, fd_to_close);
3211     n = 2;                             /* progname and terminating NULL */
3212     n += inst->ngtkargs;
3213     while (va_arg(ap, char *) != NULL)
3214         n++;
3215     va_end(ap);
3216
3217     args = snewn(n, char *);
3218     args[0] = inst->progname;
3219     args[n-1] = NULL;
3220     for (i = 0; i < inst->ngtkargs; i++)
3221         args[i+1] = inst->gtkargvstart[i];
3222
3223     i++;
3224     va_start(ap, fd_to_close);
3225     while ((args[i++] = va_arg(ap, char *)) != NULL);
3226     va_end(ap);
3227
3228     assert(i == n);
3229
3230     /*
3231      * Do the double fork.
3232      */
3233     pid = fork();
3234     if (pid < 0) {
3235         perror("fork");
3236         sfree(args);
3237         return;
3238     }
3239
3240     if (pid == 0) {
3241         int pid2 = fork();
3242         if (pid2 < 0) {
3243             perror("fork");
3244             _exit(1);
3245         } else if (pid2 > 0) {
3246             /*
3247              * First child has successfully forked second child. My
3248              * Work Here Is Done. Note the use of _exit rather than
3249              * exit: the latter appears to cause destroy messages
3250              * to be sent to the X server. I suspect gtk uses
3251              * atexit.
3252              */
3253             _exit(0);
3254         }
3255
3256         /*
3257          * If we reach here, we are the second child, so we now
3258          * actually perform the exec.
3259          */
3260         if (fd_to_close >= 0)
3261             close(fd_to_close);
3262
3263         execv("/proc/self/exe", args);
3264         execvp(inst->progname, args);
3265         perror("exec");
3266         _exit(127);
3267
3268     } else {
3269         int status;
3270         sfree(args);
3271         waitpid(pid, &status, 0);
3272     }
3273
3274 }
3275
3276 void dup_session_menuitem(GtkMenuItem *item, gpointer gdata)
3277 {
3278     struct gui_data *inst = (struct gui_data *)gdata;
3279     /*
3280      * For this feature we must marshal conf and (possibly) pty_argv
3281      * into a byte stream, create a pipe, and send this byte stream
3282      * to the child through the pipe.
3283      */
3284     int i, ret, sersize, size;
3285     char *data;
3286     char option[80];
3287     int pipefd[2];
3288
3289     if (pipe(pipefd) < 0) {
3290         perror("pipe");
3291         return;
3292     }
3293
3294     size = sersize = conf_serialised_size(inst->conf);
3295     if (use_pty_argv && pty_argv) {
3296         for (i = 0; pty_argv[i]; i++)
3297             size += strlen(pty_argv[i]) + 1;
3298     }
3299
3300     data = snewn(size, char);
3301     conf_serialise(inst->conf, data);
3302     if (use_pty_argv && pty_argv) {
3303         int p = sersize;
3304         for (i = 0; pty_argv[i]; i++) {
3305             strcpy(data + p, pty_argv[i]);
3306             p += strlen(pty_argv[i]) + 1;
3307         }
3308         assert(p == size);
3309     }
3310
3311     sprintf(option, "---[%d,%d]", pipefd[0], size);
3312     noncloexec(pipefd[0]);
3313     fork_and_exec_self(inst, pipefd[1], option, NULL);
3314     close(pipefd[0]);
3315
3316     i = ret = 0;
3317     while (i < size && (ret = write(pipefd[1], data + i, size - i)) > 0)
3318         i += ret;
3319     if (ret < 0)
3320         perror("write to pipe");
3321     close(pipefd[1]);
3322     sfree(data);
3323 }
3324
3325 int read_dupsession_data(struct gui_data *inst, Conf *conf, char *arg)
3326 {
3327     int fd, i, ret, size, size_used;
3328     char *data;
3329
3330     if (sscanf(arg, "---[%d,%d]", &fd, &size) != 2) {
3331         fprintf(stderr, "%s: malformed magic argument `%s'\n", appname, arg);
3332         exit(1);
3333     }
3334
3335     data = snewn(size, char);
3336     i = ret = 0;
3337     while (i < size && (ret = read(fd, data + i, size - i)) > 0)
3338         i += ret;
3339     if (ret < 0) {
3340         perror("read from pipe");
3341         exit(1);
3342     } else if (i < size) {
3343         fprintf(stderr, "%s: unexpected EOF in Duplicate Session data\n",
3344                 appname);
3345         exit(1);
3346     }
3347
3348     size_used = conf_deserialise(conf, data, size);
3349     if (use_pty_argv && size > size_used) {
3350         int n = 0;
3351         i = size_used;
3352         while (i < size) {
3353             while (i < size && data[i]) i++;
3354             if (i >= size) {
3355                 fprintf(stderr, "%s: malformed Duplicate Session data\n",
3356                         appname);
3357                 exit(1);
3358             }
3359             i++;
3360             n++;
3361         }
3362         pty_argv = snewn(n+1, char *);
3363         pty_argv[n] = NULL;
3364         n = 0;
3365         i = size_used;
3366         while (i < size) {
3367             char *p = data + i;
3368             while (i < size && data[i]) i++;
3369             assert(i < size);
3370             i++;
3371             pty_argv[n++] = dupstr(p);
3372         }
3373     }
3374
3375     sfree(data);
3376
3377     return 0;
3378 }
3379
3380 void new_session_menuitem(GtkMenuItem *item, gpointer data)
3381 {
3382     struct gui_data *inst = (struct gui_data *)data;
3383
3384     fork_and_exec_self(inst, -1, NULL);
3385 }
3386
3387 void restart_session_menuitem(GtkMenuItem *item, gpointer data)
3388 {
3389     struct gui_data *inst = (struct gui_data *)data;
3390
3391     if (!inst->back) {
3392         logevent(inst, "----- Session restarted -----");
3393         term_pwron(inst->term, FALSE);
3394         start_backend(inst);
3395         inst->exited = FALSE;
3396     }
3397 }
3398
3399 void saved_session_menuitem(GtkMenuItem *item, gpointer data)
3400 {
3401     struct gui_data *inst = (struct gui_data *)data;
3402     char *str = (char *)gtk_object_get_data(GTK_OBJECT(item), "user-data");
3403
3404     fork_and_exec_self(inst, -1, "-load", str, NULL);
3405 }
3406
3407 void saved_session_freedata(GtkMenuItem *item, gpointer data)
3408 {
3409     char *str = (char *)gtk_object_get_data(GTK_OBJECT(item), "user-data");
3410
3411     sfree(str);
3412 }
3413
3414 static void update_savedsess_menu(GtkMenuItem *menuitem, gpointer data)
3415 {
3416     struct gui_data *inst = (struct gui_data *)data;
3417     struct sesslist sesslist;
3418     int i;
3419
3420     gtk_container_foreach(GTK_CONTAINER(inst->sessionsmenu),
3421                           (GtkCallback)gtk_widget_destroy, NULL);
3422
3423     get_sesslist(&sesslist, TRUE);
3424     /* skip sesslist.sessions[0] == Default Settings */
3425     for (i = 1; i < sesslist.nsessions; i++) {
3426         GtkWidget *menuitem =
3427             gtk_menu_item_new_with_label(sesslist.sessions[i]);
3428         gtk_container_add(GTK_CONTAINER(inst->sessionsmenu), menuitem);
3429         gtk_widget_show(menuitem);
3430         gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
3431                             dupstr(sesslist.sessions[i]));
3432         gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
3433                            GTK_SIGNAL_FUNC(saved_session_menuitem),
3434                            inst);
3435         gtk_signal_connect(GTK_OBJECT(menuitem), "destroy",
3436                            GTK_SIGNAL_FUNC(saved_session_freedata),
3437                            inst);
3438     }
3439     if (sesslist.nsessions <= 1) {
3440         GtkWidget *menuitem =
3441             gtk_menu_item_new_with_label("(No sessions)");
3442         gtk_widget_set_sensitive(menuitem, FALSE);
3443         gtk_container_add(GTK_CONTAINER(inst->sessionsmenu), menuitem);
3444         gtk_widget_show(menuitem);
3445     }
3446     get_sesslist(&sesslist, FALSE); /* free up */
3447 }
3448
3449 void set_window_icon(GtkWidget *window, const char *const *const *icon,
3450                      int n_icon)
3451 {
3452     GdkPixmap *iconpm;
3453     GdkBitmap *iconmask;
3454 #if GTK_CHECK_VERSION(2,0,0)
3455     GList *iconlist;
3456     int n;
3457 #endif
3458
3459     if (!n_icon)
3460         return;
3461
3462     gtk_widget_realize(window);
3463     iconpm = gdk_pixmap_create_from_xpm_d(window->window, &iconmask,
3464                                           NULL, (gchar **)icon[0]);
3465     gdk_window_set_icon(window->window, NULL, iconpm, iconmask);
3466
3467 #if GTK_CHECK_VERSION(2,0,0)
3468     iconlist = NULL;
3469     for (n = 0; n < n_icon; n++) {
3470         iconlist =
3471             g_list_append(iconlist,
3472                           gdk_pixbuf_new_from_xpm_data((const gchar **)
3473                                                        icon[n]));
3474     }
3475     gdk_window_set_icon_list(window->window, iconlist);
3476 #endif
3477 }
3478
3479 void update_specials_menu(void *frontend)
3480 {
3481     struct gui_data *inst = (struct gui_data *)frontend;
3482
3483     const struct telnet_special *specials;
3484
3485     if (inst->back)
3486         specials = inst->back->get_specials(inst->backhandle);
3487     else
3488         specials = NULL;
3489
3490     /* I believe this disposes of submenus too. */
3491     gtk_container_foreach(GTK_CONTAINER(inst->specialsmenu),
3492                           (GtkCallback)gtk_widget_destroy, NULL);
3493     if (specials) {
3494         int i;
3495         GtkWidget *menu = inst->specialsmenu;
3496         /* A lame "stack" for submenus that will do for now. */
3497         GtkWidget *saved_menu = NULL;
3498         int nesting = 1;
3499         for (i = 0; nesting > 0; i++) {
3500             GtkWidget *menuitem = NULL;
3501             switch (specials[i].code) {
3502               case TS_SUBMENU:
3503                 assert (nesting < 2);
3504                 saved_menu = menu; /* XXX lame stacking */
3505                 menu = gtk_menu_new();
3506                 menuitem = gtk_menu_item_new_with_label(specials[i].name);
3507                 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), menu);
3508                 gtk_container_add(GTK_CONTAINER(saved_menu), menuitem);
3509                 gtk_widget_show(menuitem);
3510                 menuitem = NULL;
3511                 nesting++;
3512                 break;
3513               case TS_EXITMENU:
3514                 nesting--;
3515                 if (nesting) {
3516                     menu = saved_menu; /* XXX lame stacking */
3517                     saved_menu = NULL;
3518                 }
3519                 break;
3520               case TS_SEP:
3521                 menuitem = gtk_menu_item_new();
3522                 break;
3523               default:
3524                 menuitem = gtk_menu_item_new_with_label(specials[i].name);
3525                 gtk_object_set_data(GTK_OBJECT(menuitem), "user-data",
3526                                     GINT_TO_POINTER(specials[i].code));
3527                 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
3528                                    GTK_SIGNAL_FUNC(special_menuitem), inst);
3529                 break;
3530             }
3531             if (menuitem) {
3532                 gtk_container_add(GTK_CONTAINER(menu), menuitem);
3533                 gtk_widget_show(menuitem);
3534             }
3535         }
3536         gtk_widget_show(inst->specialsitem1);
3537         gtk_widget_show(inst->specialsitem2);
3538     } else {
3539         gtk_widget_hide(inst->specialsitem1);
3540         gtk_widget_hide(inst->specialsitem2);
3541     }
3542 }
3543
3544 static void start_backend(struct gui_data *inst)
3545 {
3546     extern Backend *select_backend(Conf *conf);
3547     char *realhost;
3548     const char *error;
3549     char *s;
3550
3551     inst->back = select_backend(inst->conf);
3552
3553     error = inst->back->init((void *)inst, &inst->backhandle,
3554                              inst->conf,
3555                              conf_get_str(inst->conf, CONF_host),
3556                              conf_get_int(inst->conf, CONF_port),
3557                              &realhost,
3558                              conf_get_int(inst->conf, CONF_tcp_nodelay),
3559                              conf_get_int(inst->conf, CONF_tcp_keepalives));
3560
3561     if (error) {
3562         char *msg = dupprintf("Unable to open connection to %s:\n%s",
3563                               conf_get_str(inst->conf, CONF_host), error);
3564         inst->exited = TRUE;
3565         fatal_message_box(inst->window, msg);
3566         sfree(msg);
3567         exit(0);
3568     }
3569
3570     s = conf_get_str(inst->conf, CONF_wintitle);
3571     if (s[0]) {
3572         set_title_and_icon(inst, s, s);
3573     } else {
3574         char *title = make_default_wintitle(realhost);
3575         set_title_and_icon(inst, title, title);
3576         sfree(title);
3577     }
3578     sfree(realhost);
3579
3580     inst->back->provide_logctx(inst->backhandle, inst->logctx);
3581
3582     term_provide_resize_fn(inst->term, inst->back->size, inst->backhandle);
3583
3584     inst->ldisc =
3585         ldisc_create(inst->conf, inst->term, inst->back, inst->backhandle,
3586                      inst);
3587
3588     gtk_widget_set_sensitive(inst->restartitem, FALSE);
3589 }
3590
3591 int pt_main(int argc, char **argv)
3592 {
3593     extern int cfgbox(Conf *conf);
3594     struct gui_data *inst;
3595
3596     setlocale(LC_CTYPE, "");
3597
3598     /*
3599      * Create an instance structure and initialise to zeroes
3600      */
3601     inst = snew(struct gui_data);
3602     memset(inst, 0, sizeof(*inst));
3603     inst->alt_keycode = -1;            /* this one needs _not_ to be zero */
3604     inst->busy_status = BUSY_NOT;
3605     inst->conf = conf_new();
3606     inst->wintitle = inst->icontitle = NULL;
3607
3608     /* defer any child exit handling until we're ready to deal with
3609      * it */
3610     block_signal(SIGCHLD, 1);
3611
3612     inst->progname = argv[0];
3613     /*
3614      * Copy the original argv before letting gtk_init fiddle with
3615      * it. It will be required later.
3616      */
3617     {
3618         int i, oldargc;
3619         inst->gtkargvstart = snewn(argc-1, char *);
3620         for (i = 1; i < argc; i++)
3621             inst->gtkargvstart[i-1] = dupstr(argv[i]);
3622         oldargc = argc;
3623         gtk_init(&argc, &argv);
3624         inst->ngtkargs = oldargc - argc;
3625     }
3626
3627     if (argc > 1 && !strncmp(argv[1], "---", 3)) {
3628         read_dupsession_data(inst, inst->conf, argv[1]);
3629         /* Splatter this argument so it doesn't clutter a ps listing */
3630         smemclr(argv[1], strlen(argv[1]));
3631     } else {
3632         /* By default, we bring up the config dialog, rather than launching
3633          * a session. This gets set to TRUE if something happens to change
3634          * that (e.g., a hostname is specified on the command-line). */
3635         int allow_launch = FALSE;
3636         if (do_cmdline(argc, argv, 0, &allow_launch, inst, inst->conf))
3637             exit(1);                   /* pre-defaults pass to get -class */
3638         do_defaults(NULL, inst->conf);
3639         if (do_cmdline(argc, argv, 1, &allow_launch, inst, inst->conf))
3640             exit(1);                   /* post-defaults, do everything */
3641
3642         cmdline_run_saved(inst->conf);
3643
3644         if (loaded_session)
3645             allow_launch = TRUE;
3646
3647         if ((!allow_launch || !conf_launchable(inst->conf)) &&
3648             !cfgbox(inst->conf))
3649             exit(0);                   /* config box hit Cancel */
3650     }
3651
3652     if (!compound_text_atom)
3653         compound_text_atom = gdk_atom_intern("COMPOUND_TEXT", FALSE);
3654     if (!utf8_string_atom)
3655         utf8_string_atom = gdk_atom_intern("UTF8_STRING", FALSE);
3656
3657     inst->area = gtk_drawing_area_new();
3658
3659 #if GTK_CHECK_VERSION(2,0,0)
3660     inst->imc = gtk_im_multicontext_new();
3661 #endif
3662
3663     {
3664         char *errmsg = setup_fonts_ucs(inst);
3665         if (errmsg) {
3666             fprintf(stderr, "%s: %s\n", appname, errmsg);
3667             exit(1);
3668         }
3669     }
3670     init_cutbuffers();
3671
3672     inst->window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
3673     {
3674         const char *winclass = conf_get_str(inst->conf, CONF_winclass);
3675         if (*winclass)
3676             gtk_window_set_wmclass(GTK_WINDOW(inst->window),
3677                                    winclass, winclass);
3678     }
3679
3680     /*
3681      * Set up the colour map.
3682      */
3683     palette_reset(inst);
3684
3685     inst->width = conf_get_int(inst->conf, CONF_width);
3686     inst->height = conf_get_int(inst->conf, CONF_height);
3687     cache_conf_values(inst);
3688
3689     gtk_drawing_area_size(GTK_DRAWING_AREA(inst->area),
3690                           inst->font_width * inst->width + 2*inst->window_border,
3691                           inst->font_height * inst->height + 2*inst->window_border);
3692     inst->sbar_adjust = GTK_ADJUSTMENT(gtk_adjustment_new(0,0,0,0,0,0));
3693     inst->sbar = gtk_vscrollbar_new(inst->sbar_adjust);
3694     inst->hbox = GTK_BOX(gtk_hbox_new(FALSE, 0));
3695     /*
3696      * We always create the scrollbar; it remains invisible if
3697      * unwanted, so we can pop it up quickly if it suddenly becomes
3698      * desirable.
3699      */
3700     if (conf_get_int(inst->conf, CONF_scrollbar_on_left))
3701         gtk_box_pack_start(inst->hbox, inst->sbar, FALSE, FALSE, 0);
3702     gtk_box_pack_start(inst->hbox, inst->area, TRUE, TRUE, 0);
3703     if (!conf_get_int(inst->conf, CONF_scrollbar_on_left))
3704         gtk_box_pack_start(inst->hbox, inst->sbar, FALSE, FALSE, 0);
3705
3706     gtk_container_add(GTK_CONTAINER(inst->window), GTK_WIDGET(inst->hbox));
3707
3708     set_geom_hints(inst);
3709
3710     gtk_widget_show(inst->area);
3711     if (conf_get_int(inst->conf, CONF_scrollbar))
3712         gtk_widget_show(inst->sbar);
3713     else
3714         gtk_widget_hide(inst->sbar);
3715     gtk_widget_show(GTK_WIDGET(inst->hbox));
3716
3717     if (inst->gotpos) {
3718         int x = inst->xpos, y = inst->ypos;
3719         GtkRequisition req;
3720         gtk_widget_size_request(GTK_WIDGET(inst->window), &req);
3721         if (inst->gravity & 1) x += gdk_screen_width() - req.width;
3722         if (inst->gravity & 2) y += gdk_screen_height() - req.height;
3723         gtk_window_set_position(GTK_WINDOW(inst->window), GTK_WIN_POS_NONE);
3724         gtk_widget_set_uposition(GTK_WIDGET(inst->window), x, y);
3725     }
3726
3727     gtk_signal_connect(GTK_OBJECT(inst->window), "destroy",
3728                        GTK_SIGNAL_FUNC(destroy), inst);
3729     gtk_signal_connect(GTK_OBJECT(inst->window), "delete_event",
3730                        GTK_SIGNAL_FUNC(delete_window), inst);
3731     gtk_signal_connect(GTK_OBJECT(inst->window), "key_press_event",
3732                        GTK_SIGNAL_FUNC(key_event), inst);
3733     gtk_signal_connect(GTK_OBJECT(inst->window), "key_release_event",
3734                        GTK_SIGNAL_FUNC(key_event), inst);
3735     gtk_signal_connect(GTK_OBJECT(inst->window), "focus_in_event",
3736                        GTK_SIGNAL_FUNC(focus_event), inst);
3737     gtk_signal_connect(GTK_OBJECT(inst->window), "focus_out_event",
3738                        GTK_SIGNAL_FUNC(focus_event), inst);
3739     gtk_signal_connect(GTK_OBJECT(inst->area), "configure_event",
3740                        GTK_SIGNAL_FUNC(configure_area), inst);
3741     gtk_signal_connect(GTK_OBJECT(inst->area), "expose_event",
3742                        GTK_SIGNAL_FUNC(expose_area), inst);
3743     gtk_signal_connect(GTK_OBJECT(inst->area), "button_press_event",
3744                        GTK_SIGNAL_FUNC(button_event), inst);
3745     gtk_signal_connect(GTK_OBJECT(inst->area), "button_release_event",
3746                        GTK_SIGNAL_FUNC(button_event), inst);
3747 #if GTK_CHECK_VERSION(2,0,0)
3748     gtk_signal_connect(GTK_OBJECT(inst->area), "scroll_event",
3749                        GTK_SIGNAL_FUNC(scroll_event), inst);
3750 #endif
3751     gtk_signal_connect(GTK_OBJECT(inst->area), "motion_notify_event",
3752                        GTK_SIGNAL_FUNC(motion_event), inst);
3753     gtk_signal_connect(GTK_OBJECT(inst->area), "selection_received",
3754                        GTK_SIGNAL_FUNC(selection_received), inst);
3755     gtk_signal_connect(GTK_OBJECT(inst->area), "selection_get",
3756                        GTK_SIGNAL_FUNC(selection_get), inst);
3757     gtk_signal_connect(GTK_OBJECT(inst->area), "selection_clear_event",
3758                        GTK_SIGNAL_FUNC(selection_clear), inst);
3759 #if GTK_CHECK_VERSION(2,0,0)
3760     g_signal_connect(G_OBJECT(inst->imc), "commit",
3761                      G_CALLBACK(input_method_commit_event), inst);
3762 #endif
3763     if (conf_get_int(inst->conf, CONF_scrollbar))
3764         gtk_signal_connect(GTK_OBJECT(inst->sbar_adjust), "value_changed",
3765                            GTK_SIGNAL_FUNC(scrollbar_moved), inst);
3766     gtk_widget_add_events(GTK_WIDGET(inst->area),
3767                           GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK |
3768                           GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK |
3769                           GDK_POINTER_MOTION_MASK | GDK_BUTTON_MOTION_MASK);
3770
3771     {
3772         extern const char *const *const main_icon[];
3773         extern const int n_main_icon;
3774         set_window_icon(inst->window, main_icon, n_main_icon);
3775     }
3776
3777     gtk_widget_show(inst->window);
3778
3779     set_window_background(inst);
3780
3781     /*
3782      * Set up the Ctrl+rightclick context menu.
3783      */
3784     {
3785         GtkWidget *menuitem;
3786         char *s;
3787         extern const int use_event_log, new_session, saved_sessions;
3788
3789         inst->menu = gtk_menu_new();
3790
3791 #define MKMENUITEM(title, func) do                                      \
3792         {                                                               \
3793             menuitem = gtk_menu_item_new_with_label(title);             \
3794             gtk_container_add(GTK_CONTAINER(inst->menu), menuitem);     \
3795             gtk_widget_show(menuitem);                                  \
3796             gtk_signal_connect(GTK_OBJECT(menuitem), "activate",        \
3797                                GTK_SIGNAL_FUNC(func), inst);            \
3798         } while (0)
3799
3800 #define MKSUBMENU(title) do                                             \
3801         {                                                               \
3802             menuitem = gtk_menu_item_new_with_label(title);             \
3803             gtk_container_add(GTK_CONTAINER(inst->menu), menuitem);     \
3804             gtk_widget_show(menuitem);                                  \
3805         } while (0)
3806
3807 #define MKSEP() do                                                      \
3808         {                                                               \
3809             menuitem = gtk_menu_item_new();                             \
3810             gtk_container_add(GTK_CONTAINER(inst->menu), menuitem);     \
3811             gtk_widget_show(menuitem);                                  \
3812         } while (0)
3813
3814         if (new_session)
3815             MKMENUITEM("New Session...", new_session_menuitem);
3816         MKMENUITEM("Restart Session", restart_session_menuitem);
3817         inst->restartitem = menuitem;
3818         gtk_widget_set_sensitive(inst->restartitem, FALSE);
3819         MKMENUITEM("Duplicate Session", dup_session_menuitem);
3820         if (saved_sessions) {
3821             inst->sessionsmenu = gtk_menu_new();
3822             /* sessionsmenu will be updated when it's invoked */
3823             /* XXX is this the right way to do dynamic menus in Gtk? */
3824             MKMENUITEM("Saved Sessions", update_savedsess_menu);
3825             gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem),
3826                                       inst->sessionsmenu);
3827         }
3828         MKSEP();
3829         MKMENUITEM("Change Settings...", change_settings_menuitem);
3830         MKSEP();
3831         if (use_event_log)
3832             MKMENUITEM("Event Log", event_log_menuitem);
3833         MKSUBMENU("Special Commands");
3834         inst->specialsmenu = gtk_menu_new();
3835         gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), inst->specialsmenu);
3836         inst->specialsitem1 = menuitem;
3837         MKSEP();
3838         inst->specialsitem2 = menuitem;
3839         gtk_widget_hide(inst->specialsitem1);
3840         gtk_widget_hide(inst->specialsitem2);
3841         MKMENUITEM("Clear Scrollback", clear_scrollback_menuitem);
3842         MKMENUITEM("Reset Terminal", reset_terminal_menuitem);
3843         MKMENUITEM("Copy All", copy_all_menuitem);
3844         MKSEP();
3845         s = dupcat("About ", appname, NULL);
3846         MKMENUITEM(s, about_menuitem);
3847         sfree(s);
3848 #undef MKMENUITEM
3849 #undef MKSUBMENU
3850 #undef MKSEP
3851     }
3852
3853     inst->textcursor = make_mouse_ptr(inst, GDK_XTERM);
3854     inst->rawcursor = make_mouse_ptr(inst, GDK_LEFT_PTR);
3855     inst->waitcursor = make_mouse_ptr(inst, GDK_WATCH);
3856     inst->blankcursor = make_mouse_ptr(inst, -1);
3857     make_mouse_ptr(inst, -2);          /* clean up cursor font */
3858     inst->currcursor = inst->textcursor;
3859     show_mouseptr(inst, 1);
3860
3861     inst->eventlogstuff = eventlogstuff_new();
3862
3863     request_callback_notifications(notify_toplevel_callback, inst);
3864
3865     inst->term = term_init(inst->conf, &inst->ucsdata, inst);
3866     inst->logctx = log_init(inst, inst->conf);
3867     term_provide_logctx(inst->term, inst->logctx);
3868
3869     uxsel_init();
3870
3871     term_size(inst->term, inst->height, inst->width,
3872               conf_get_int(inst->conf, CONF_savelines));
3873
3874     start_backend(inst);
3875
3876     ldisc_send(inst->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
3877
3878     /* now we're reday to deal with the child exit handler being
3879      * called */
3880     block_signal(SIGCHLD, 0);
3881
3882     /*
3883      * Block SIGPIPE: if we attempt Duplicate Session or similar
3884      * and it falls over in some way, we certainly don't want
3885      * SIGPIPE terminating the main pterm/PuTTY. Note that we do
3886      * this _after_ (at least pterm) forks off its child process,
3887      * since the child wants SIGPIPE handled in the usual way.
3888      */
3889     block_signal(SIGPIPE, 1);
3890
3891     inst->exited = FALSE;
3892
3893     gtk_main();
3894
3895     return 0;
3896 }