]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - unix/gtkwin.c
de0f7a56e7cde57456c913967c62bcf1f8fe9891
[PuTTY.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 #if !GTK_CHECK_VERSION(3,0,0)
23 #include <gdk/gdkkeysyms.h>
24 #endif
25
26 #if GTK_CHECK_VERSION(2,0,0)
27 #include <gtk/gtkimmodule.h>
28 #endif
29
30 #define PUTTY_DO_GLOBALS               /* actually _define_ globals */
31
32 #define MAY_REFER_TO_GTK_IN_HEADERS
33
34 #include "putty.h"
35 #include "terminal.h"
36 #include "gtkcompat.h"
37 #include "gtkfont.h"
38 #include "gtkmisc.h"
39
40 #ifndef NOT_X_WINDOWS
41 #include <gdk/gdkx.h>
42 #include <X11/Xlib.h>
43 #include <X11/Xutil.h>
44 #include <X11/Xatom.h>
45 #endif
46
47 #define CAT2(x,y) x ## y
48 #define CAT(x,y) CAT2(x,y)
49 #define ASSERT(x) enum {CAT(assertion_,__LINE__) = 1 / (x)}
50
51 #if GTK_CHECK_VERSION(2,0,0)
52 ASSERT(sizeof(long) <= sizeof(gsize));
53 #define LONG_TO_GPOINTER(l) GSIZE_TO_POINTER(l)
54 #define GPOINTER_TO_LONG(p) GPOINTER_TO_SIZE(p)
55 #else /* Gtk 1.2 */
56 ASSERT(sizeof(long) <= sizeof(gpointer));
57 #define LONG_TO_GPOINTER(l) ((gpointer)(long)(l))
58 #define GPOINTER_TO_LONG(p) ((long)(p))
59 #endif
60
61 /* Colours come in two flavours: configurable, and xterm-extended. */
62 #define NEXTCOLOURS 240 /* 216 colour-cube plus 24 shades of grey */
63 #define NALLCOLOURS (NCFGCOLOURS + NEXTCOLOURS)
64
65 GdkAtom compound_text_atom, utf8_string_atom;
66
67 extern char **pty_argv;        /* declared in pty.c */
68 extern int use_pty_argv;
69
70 /*
71  * Timers are global across all sessions (even if we were handling
72  * multiple sessions, which we aren't), so the current timer ID is
73  * a global variable.
74  */
75 static guint timer_id = 0;
76
77 struct clipboard_data_instance;
78
79 struct gui_data {
80     GtkWidget *window, *area, *sbar;
81     GtkBox *hbox;
82     GtkAdjustment *sbar_adjust;
83     GtkWidget *menu, *specialsmenu, *specialsitem1, *specialsitem2,
84         *restartitem;
85     GtkWidget *sessionsmenu;
86 #ifndef NO_BACKING_PIXMAPS
87     /*
88      * Server-side pixmap which we use to cache the terminal window's
89      * contents. When we draw text in the terminal, we draw it to this
90      * pixmap first, and then blit from there to the actual window;
91      * this way, X expose events can be handled with an absolute
92      * minimum of network traffic, by just sending a command to
93      * re-blit an appropriate rectangle from this pixmap.
94      */
95     GdkPixmap *pixmap;
96 #endif
97 #ifdef DRAW_TEXT_CAIRO
98     /*
99      * If we're drawing using Cairo, we cache the same image on the
100      * client side in a Cairo surface.
101      *
102      * In GTK2+Cairo, this happens _as well_ as having the server-side
103      * pixmap cache above; in GTK3+Cairo, server-side pixmaps are
104      * deprecated, so we _just_ have this client-side cache. In the
105      * latter case that means we have to transmit a big wodge of
106      * bitmap data over the X connection on every expose event; but
107      * GTK3 apparently deliberately provides no way to avoid that
108      * inefficiency, and at least this way we don't _also_ have to
109      * redo any font rendering just because the window was temporarily
110      * covered.
111      */
112     cairo_surface_t *surface;
113 #endif
114 #if GTK_CHECK_VERSION(2,0,0)
115     GtkIMContext *imc;
116 #endif
117     unifont *fonts[4];                 /* normal, bold, wide, widebold */
118 #if GTK_CHECK_VERSION(2,0,0)
119     const char *geometry;
120 #else
121     int xpos, ypos, gotpos, gravity;
122 #endif
123     GdkCursor *rawcursor, *textcursor, *blankcursor, *waitcursor, *currcursor;
124     GdkColor cols[NALLCOLOURS];
125 #if !GTK_CHECK_VERSION(3,0,0)
126     GdkColormap *colmap;
127 #endif
128     int direct_to_font;
129     wchar_t *pastein_data;
130     int pastein_data_len;
131 #ifdef JUST_USE_GTK_CLIPBOARD_UTF8
132     GtkClipboard *clipboard;
133     struct clipboard_data_instance *current_cdi;
134 #else
135     char *pasteout_data, *pasteout_data_ctext, *pasteout_data_utf8;
136     int pasteout_data_len, pasteout_data_ctext_len, pasteout_data_utf8_len;
137 #endif
138     int font_width, font_height;
139     int width, height;
140     int ignore_sbar;
141     int mouseptr_visible;
142     int busy_status;
143     guint toplevel_callback_idle_id;
144     int idle_fn_scheduled, quit_fn_scheduled;
145     int alt_keycode;
146     int alt_digits;
147     char *wintitle;
148     char *icontitle;
149     int master_fd, master_func_id;
150     void *ldisc;
151     Backend *back;
152     void *backhandle;
153     Terminal *term;
154     void *logctx;
155     int exited;
156     struct unicode_data ucsdata;
157     Conf *conf;
158     void *eventlogstuff;
159     char *progname, **gtkargvstart;
160     int ngtkargs;
161     guint32 input_event_time; /* Timestamp of the most recent input event. */
162     int reconfiguring;
163     /* Cached things out of conf that we refer to a lot */
164     int bold_style;
165     int window_border;
166     int cursor_type;
167     int drawtype;
168     int meta_mod_mask;
169 };
170
171 static void cache_conf_values(struct gui_data *inst)
172 {
173     inst->bold_style = conf_get_int(inst->conf, CONF_bold_style);
174     inst->window_border = conf_get_int(inst->conf, CONF_window_border);
175     inst->cursor_type = conf_get_int(inst->conf, CONF_cursor_type);
176 #ifdef OSX_META_KEY_CONFIG
177     inst->meta_mod_mask = 0;
178     if (conf_get_int(inst->conf, CONF_osx_option_meta))
179         inst->meta_mod_mask |= GDK_MOD1_MASK;
180     if (conf_get_int(inst->conf, CONF_osx_command_meta))
181         inst->meta_mod_mask |= GDK_MOD2_MASK;
182 #else
183     inst->meta_mod_mask = GDK_MOD1_MASK;
184 #endif
185 }
186
187 struct draw_ctx {
188     struct gui_data *inst;
189     unifont_drawctx uctx;
190 };
191
192 static int send_raw_mouse;
193
194 static const char *app_name = "pterm";
195
196 static void start_backend(struct gui_data *inst);
197 static void exit_callback(void *vinst);
198
199 char *x_get_default(const char *key)
200 {
201 #ifndef NOT_X_WINDOWS
202     return XGetDefault(GDK_DISPLAY_XDISPLAY(gdk_display_get_default()),
203                        app_name, key);
204 #else
205     return NULL;
206 #endif
207 }
208
209 void connection_fatal(void *frontend, const char *p, ...)
210 {
211     struct gui_data *inst = (struct gui_data *)frontend;
212
213     va_list ap;
214     char *msg;
215     va_start(ap, p);
216     msg = dupvprintf(p, ap);
217     va_end(ap);
218     fatal_message_box(inst->window, msg);
219     sfree(msg);
220
221     queue_toplevel_callback(exit_callback, inst);
222 }
223
224 /*
225  * Default settings that are specific to pterm.
226  */
227 FontSpec *platform_default_fontspec(const char *name)
228 {
229     if (!strcmp(name, "Font"))
230         return fontspec_new(DEFAULT_GTK_FONT);
231     else
232         return fontspec_new("");
233 }
234
235 Filename *platform_default_filename(const char *name)
236 {
237     if (!strcmp(name, "LogFileName"))
238         return filename_from_str("putty.log");
239     else
240         return filename_from_str("");
241 }
242
243 char *platform_default_s(const char *name)
244 {
245     if (!strcmp(name, "SerialLine"))
246         return dupstr("/dev/ttyS0");
247     return NULL;
248 }
249
250 int platform_default_i(const char *name, int def)
251 {
252     if (!strcmp(name, "CloseOnExit"))
253         return 2;  /* maps to FORCE_ON after painful rearrangement :-( */
254     if (!strcmp(name, "WinNameAlways"))
255         return 0;  /* X natively supports icon titles, so use 'em by default */
256     return def;
257 }
258
259 /* Dummy routine, only required in plink. */
260 void frontend_echoedit_update(void *frontend, int echo, int edit)
261 {
262 }
263
264 char *get_ttymode(void *frontend, const char *mode)
265 {
266     struct gui_data *inst = (struct gui_data *)frontend;
267     return term_get_ttymode(inst->term, mode);
268 }
269
270 int from_backend(void *frontend, int is_stderr, const char *data, int len)
271 {
272     struct gui_data *inst = (struct gui_data *)frontend;
273     return term_data(inst->term, is_stderr, data, len);
274 }
275
276 int from_backend_untrusted(void *frontend, const char *data, int len)
277 {
278     struct gui_data *inst = (struct gui_data *)frontend;
279     return term_data_untrusted(inst->term, data, len);
280 }
281
282 int from_backend_eof(void *frontend)
283 {
284     return TRUE;   /* do respond to incoming EOF with outgoing */
285 }
286
287 int get_userpass_input(prompts_t *p, const unsigned char *in, int inlen)
288 {
289     struct gui_data *inst = (struct gui_data *)p->frontend;
290     int ret;
291     ret = cmdline_get_passwd_input(p, in, inlen);
292     if (ret == -1)
293         ret = term_get_userpass_input(inst->term, p, in, inlen);
294     return ret;
295 }
296
297 void logevent(void *frontend, const char *string)
298 {
299     struct gui_data *inst = (struct gui_data *)frontend;
300
301     log_eventlog(inst->logctx, string);
302
303     logevent_dlg(inst->eventlogstuff, string);
304 }
305
306 int font_dimension(void *frontend, int which)/* 0 for width, 1 for height */
307 {
308     struct gui_data *inst = (struct gui_data *)frontend;
309
310     if (which)
311         return inst->font_height;
312     else
313         return inst->font_width;
314 }
315
316 /*
317  * Translate a raw mouse button designation (LEFT, MIDDLE, RIGHT)
318  * into a cooked one (SELECT, EXTEND, PASTE).
319  * 
320  * In Unix, this is not configurable; the X button arrangement is
321  * rock-solid across all applications, everyone has a three-button
322  * mouse or a means of faking it, and there is no need to switch
323  * buttons around at all.
324  */
325 static Mouse_Button translate_button(Mouse_Button button)
326 {
327     /* struct gui_data *inst = (struct gui_data *)frontend; */
328
329     if (button == MBT_LEFT)
330         return MBT_SELECT;
331     if (button == MBT_MIDDLE)
332         return MBT_PASTE;
333     if (button == MBT_RIGHT)
334         return MBT_EXTEND;
335     return 0;                          /* shouldn't happen */
336 }
337
338 /*
339  * Return the top-level GtkWindow associated with a particular
340  * front end instance.
341  */
342 void *get_window(void *frontend)
343 {
344     struct gui_data *inst = (struct gui_data *)frontend;
345     return inst->window;
346 }
347
348 /*
349  * Minimise or restore the window in response to a server-side
350  * request.
351  */
352 void set_iconic(void *frontend, int iconic)
353 {
354     /*
355      * GTK 1.2 doesn't know how to do this.
356      */
357 #if GTK_CHECK_VERSION(2,0,0)
358     struct gui_data *inst = (struct gui_data *)frontend;
359     if (iconic)
360         gtk_window_iconify(GTK_WINDOW(inst->window));
361     else
362         gtk_window_deiconify(GTK_WINDOW(inst->window));
363 #endif
364 }
365
366 /*
367  * Move the window in response to a server-side request.
368  */
369 void move_window(void *frontend, int x, int y)
370 {
371     struct gui_data *inst = (struct gui_data *)frontend;
372     /*
373      * I assume that when the GTK version of this call is available
374      * we should use it. Not sure how it differs from the GDK one,
375      * though.
376      */
377 #if GTK_CHECK_VERSION(2,0,0)
378     gtk_window_move(GTK_WINDOW(inst->window), x, y);
379 #else
380     gdk_window_move(gtk_widget_get_window(inst->window), x, y);
381 #endif
382 }
383
384 /*
385  * Move the window to the top or bottom of the z-order in response
386  * to a server-side request.
387  */
388 void set_zorder(void *frontend, int top)
389 {
390     struct gui_data *inst = (struct gui_data *)frontend;
391     if (top)
392         gdk_window_raise(gtk_widget_get_window(inst->window));
393     else
394         gdk_window_lower(gtk_widget_get_window(inst->window));
395 }
396
397 /*
398  * Refresh the window in response to a server-side request.
399  */
400 void refresh_window(void *frontend)
401 {
402     struct gui_data *inst = (struct gui_data *)frontend;
403     term_invalidate(inst->term);
404 }
405
406 /*
407  * Maximise or restore the window in response to a server-side
408  * request.
409  */
410 void set_zoomed(void *frontend, int zoomed)
411 {
412     /*
413      * GTK 1.2 doesn't know how to do this.
414      */
415 #if GTK_CHECK_VERSION(2,0,0)
416     struct gui_data *inst = (struct gui_data *)frontend;
417     if (zoomed)
418         gtk_window_maximize(GTK_WINDOW(inst->window));
419     else
420         gtk_window_unmaximize(GTK_WINDOW(inst->window));
421 #endif
422 }
423
424 /*
425  * Report whether the window is iconic, for terminal reports.
426  */
427 int is_iconic(void *frontend)
428 {
429     struct gui_data *inst = (struct gui_data *)frontend;
430     return !gdk_window_is_viewable(gtk_widget_get_window(inst->window));
431 }
432
433 /*
434  * Report the window's position, for terminal reports.
435  */
436 void get_window_pos(void *frontend, int *x, int *y)
437 {
438     struct gui_data *inst = (struct gui_data *)frontend;
439     /*
440      * I assume that when the GTK version of this call is available
441      * we should use it. Not sure how it differs from the GDK one,
442      * though.
443      */
444 #if GTK_CHECK_VERSION(2,0,0)
445     gtk_window_get_position(GTK_WINDOW(inst->window), x, y);
446 #else
447     gdk_window_get_position(gtk_widget_get_window(inst->window), x, y);
448 #endif
449 }
450
451 /*
452  * Report the window's pixel size, for terminal reports.
453  */
454 void get_window_pixels(void *frontend, int *x, int *y)
455 {
456     struct gui_data *inst = (struct gui_data *)frontend;
457     /*
458      * I assume that when the GTK version of this call is available
459      * we should use it. Not sure how it differs from the GDK one,
460      * though.
461      */
462 #if GTK_CHECK_VERSION(2,0,0)
463     gtk_window_get_size(GTK_WINDOW(inst->window), x, y);
464 #else
465     gdk_window_get_size(gtk_widget_get_window(inst->window), x, y);
466 #endif
467 }
468
469 /*
470  * Return the window or icon title.
471  */
472 char *get_window_title(void *frontend, int icon)
473 {
474     struct gui_data *inst = (struct gui_data *)frontend;
475     return icon ? inst->icontitle : inst->wintitle;
476 }
477
478 gint delete_window(GtkWidget *widget, GdkEvent *event, gpointer data)
479 {
480     struct gui_data *inst = (struct gui_data *)data;
481     if (!inst->exited && conf_get_int(inst->conf, CONF_warn_on_close)) {
482         if (!reallyclose(inst))
483             return TRUE;
484     }
485     return FALSE;
486 }
487
488 static void update_mouseptr(struct gui_data *inst)
489 {
490     switch (inst->busy_status) {
491       case BUSY_NOT:
492         if (!inst->mouseptr_visible) {
493             gdk_window_set_cursor(gtk_widget_get_window(inst->area),
494                                   inst->blankcursor);
495         } else if (send_raw_mouse) {
496             gdk_window_set_cursor(gtk_widget_get_window(inst->area),
497                                   inst->rawcursor);
498         } else {
499             gdk_window_set_cursor(gtk_widget_get_window(inst->area),
500                                   inst->textcursor);
501         }
502         break;
503       case BUSY_WAITING:    /* XXX can we do better? */
504       case BUSY_CPU:
505         /* We always display these cursors. */
506         gdk_window_set_cursor(gtk_widget_get_window(inst->area),
507                               inst->waitcursor);
508         break;
509       default:
510         assert(0);
511     }
512 }
513
514 static void show_mouseptr(struct gui_data *inst, int show)
515 {
516     if (!conf_get_int(inst->conf, CONF_hide_mouseptr))
517         show = 1;
518     inst->mouseptr_visible = show;
519     update_mouseptr(inst);
520 }
521
522 static void draw_backing_rect(struct gui_data *inst);
523
524 gint configure_area(GtkWidget *widget, GdkEventConfigure *event, gpointer data)
525 {
526     struct gui_data *inst = (struct gui_data *)data;
527     int w, h, need_size = 0;
528
529     /*
530      * See if the terminal size has changed, in which case we must
531      * let the terminal know.
532      */
533     w = (event->width - 2*inst->window_border) / inst->font_width;
534     h = (event->height - 2*inst->window_border) / inst->font_height;
535     if (w != inst->width || h != inst->height) {
536         inst->width = w;
537         inst->height = h;
538         conf_set_int(inst->conf, CONF_width, inst->width);
539         conf_set_int(inst->conf, CONF_height, inst->height);
540         need_size = 1;
541     }
542
543     {
544         int backing_w = w * inst->font_width + 2*inst->window_border;
545         int backing_h = h * inst->font_height + 2*inst->window_border;
546
547 #ifndef NO_BACKING_PIXMAPS
548         if (inst->pixmap) {
549             gdk_pixmap_unref(inst->pixmap);
550             inst->pixmap = NULL;
551         }
552
553         inst->pixmap = gdk_pixmap_new(gtk_widget_get_window(widget),
554                                       backing_w, backing_h, -1);
555 #endif
556
557 #ifdef DRAW_TEXT_CAIRO
558         if (inst->surface) {
559             cairo_surface_destroy(inst->surface);
560             inst->surface = NULL;
561         }
562
563         inst->surface = cairo_image_surface_create(CAIRO_FORMAT_RGB24,
564                                                    backing_w, backing_h);
565 #endif
566     }
567
568     draw_backing_rect(inst);
569
570     if (need_size && inst->term) {
571         term_size(inst->term, h, w, conf_get_int(inst->conf, CONF_savelines));
572     }
573
574     if (inst->term)
575         term_invalidate(inst->term);
576
577 #if GTK_CHECK_VERSION(2,0,0)
578     gtk_im_context_set_client_window(inst->imc, gtk_widget_get_window(widget));
579 #endif
580
581     return TRUE;
582 }
583
584 #ifdef DRAW_TEXT_CAIRO
585 static void cairo_setup_dctx(struct draw_ctx *dctx)
586 {
587     cairo_get_matrix(dctx->uctx.u.cairo.cr,
588                      &dctx->uctx.u.cairo.origmatrix);
589     cairo_set_line_width(dctx->uctx.u.cairo.cr, 1.0);
590     cairo_set_line_cap(dctx->uctx.u.cairo.cr, CAIRO_LINE_CAP_SQUARE);
591     cairo_set_line_join(dctx->uctx.u.cairo.cr, CAIRO_LINE_JOIN_MITER);
592     /* This antialiasing setting appears to be ignored for Pango
593      * font rendering but honoured for stroking and filling paths;
594      * I don't quite understand the logic of that, but I won't
595      * complain since it's exactly what I happen to want */
596     cairo_set_antialias(dctx->uctx.u.cairo.cr, CAIRO_ANTIALIAS_NONE);
597 }
598 #endif
599
600 #if GTK_CHECK_VERSION(3,0,0)
601 static gint draw_area(GtkWidget *widget, cairo_t *cr, gpointer data)
602 {
603     struct gui_data *inst = (struct gui_data *)data;
604
605     /*
606      * GTK3 window redraw: we always expect Cairo to be enabled, so
607      * that inst->surface exists, and pixmaps to be disabled, so that
608      * inst->pixmap does not exist. Hence, we just blit from
609      * inst->surface to the window.
610      */
611     if (inst->surface) {
612         GdkRectangle dirtyrect;
613
614         gdk_cairo_get_clip_rectangle(cr, &dirtyrect);
615
616         cairo_set_source_surface(cr, inst->surface, 0, 0);
617         cairo_rectangle(cr, dirtyrect.x, dirtyrect.y,
618                         dirtyrect.width, dirtyrect.height);
619         cairo_fill(cr);
620     }
621
622     return TRUE;
623 }
624 #else
625 gint expose_area(GtkWidget *widget, GdkEventExpose *event, gpointer data)
626 {
627     struct gui_data *inst = (struct gui_data *)data;
628
629 #ifndef NO_BACKING_PIXMAPS
630     /*
631      * Draw to the exposed part of the window from the server-side
632      * backing pixmap.
633      */
634     if (inst->pixmap) {
635         gdk_draw_pixmap(gtk_widget_get_window(widget),
636                         (gtk_widget_get_style(widget)->fg_gc
637                          [gtk_widget_get_state(widget)]),
638                         inst->pixmap,
639                         event->area.x, event->area.y,
640                         event->area.x, event->area.y,
641                         event->area.width, event->area.height);
642     }
643 #else
644     /*
645      * Failing that, draw from the client-side Cairo surface. (We
646      * should never be compiled in a context where we have _neither_
647      * inst->surface nor inst->pixmap.)
648      */
649     if (inst->surface) {
650         cairo_t *cr = gdk_cairo_create(gtk_widget_get_window(widget));
651         cairo_set_source_surface(cr, inst->surface, 0, 0);
652         cairo_rectangle(cr, event->area.x, event->area.y,
653                         event->area.width, event->area.height);
654         cairo_fill(cr);
655         cairo_destroy(cr);
656     }
657 #endif
658
659     return TRUE;
660 }
661 #endif
662
663 #define KEY_PRESSED(k) \
664     (inst->keystate[(k) / 32] & (1 << ((k) % 32)))
665
666 #ifdef KEY_EVENT_DIAGNOSTICS
667 char *dup_keyval_name(guint keyval)
668 {
669     const char *name = gdk_keyval_name(keyval);
670     if (name)
671         return dupstr(name);
672     else
673         return dupprintf("UNKNOWN[%u]", (unsigned)keyval);
674 }
675 #endif
676
677 gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data)
678 {
679     struct gui_data *inst = (struct gui_data *)data;
680     char output[256];
681     wchar_t ucsoutput[2];
682     int ucsval, start, end, special, output_charset, use_ucsoutput;
683     int nethack_mode, app_keypad_mode;
684
685     /* Remember the timestamp. */
686     inst->input_event_time = event->time;
687
688     /* By default, nothing is generated. */
689     end = start = 0;
690     special = use_ucsoutput = FALSE;
691     output_charset = CS_ISO8859_1;
692
693 #ifdef KEY_EVENT_DIAGNOSTICS
694     {
695         char *type_string, *state_string, *keyval_string, *string_string;
696
697         type_string = (event->type == GDK_KEY_PRESS ? dupstr("PRESS") :
698                        event->type == GDK_KEY_RELEASE ? dupstr("RELEASE") :
699                        dupprintf("UNKNOWN[%d]", (int)event->type));
700
701         {
702             static const struct {
703                 int mod_bit;
704                 const char *name;
705             } mod_bits[] = {
706                 {GDK_SHIFT_MASK, "SHIFT"},
707                 {GDK_LOCK_MASK, "LOCK"},
708                 {GDK_CONTROL_MASK, "CONTROL"},
709                 {GDK_MOD1_MASK, "MOD1"},
710                 {GDK_MOD2_MASK, "MOD2"},
711                 {GDK_MOD3_MASK, "MOD3"},
712                 {GDK_MOD4_MASK, "MOD4"},
713                 {GDK_MOD5_MASK, "MOD5"},
714                 {GDK_SUPER_MASK, "SUPER"},
715                 {GDK_HYPER_MASK, "HYPER"},
716                 {GDK_META_MASK, "META"},
717             };
718             int i;
719             int val = event->state;
720
721             state_string = dupstr("");
722
723             for (i = 0; i < lenof(mod_bits); i++) {
724                 if (val & mod_bits[i].mod_bit) {
725                     char *old = state_string;
726                     state_string = dupcat(state_string,
727                                           state_string[0] ? "|" : "",
728                                           mod_bits[i].name,
729                                           (char *)NULL);
730                     sfree(old);
731
732                     val &= ~mod_bits[i].mod_bit;
733                 }
734             }
735
736             if (val || !state_string[0]) {
737                 char *old = state_string;
738                 state_string = dupprintf("%s%s%d", state_string,
739                                          state_string[0] ? "|" : "", val);
740                 sfree(old);
741             }
742         }
743
744         keyval_string = dup_keyval_name(event->keyval);
745
746         string_string = dupstr("");
747         {
748             int i;
749             for (i = 0; event->string[i]; i++) {
750                 char *old = string_string;
751                 string_string = dupprintf("%s%s%02x", string_string,
752                                           string_string[0] ? " " : "",
753                                           (unsigned)event->string[i] & 0xFF);
754                 sfree(old);
755             }
756         }
757
758         debug(("key_event: type=%s keyval=%s state=%s "
759                "hardware_keycode=%d is_modifier=%s string=[%s]\n",
760                type_string, keyval_string, state_string,
761                (int)event->hardware_keycode,
762                event->is_modifier ? "TRUE" : "FALSE",
763                string_string));
764
765         sfree(type_string);
766         sfree(state_string);
767         sfree(keyval_string);
768         sfree(string_string);
769     }
770 #endif /* KEY_EVENT_DIAGNOSTICS */
771
772     /*
773      * If Alt is being released after typing an Alt+numberpad
774      * sequence, we should generate the code that was typed.
775      * 
776      * Note that we only do this if more than one key was actually
777      * pressed - I don't think Alt+NumPad4 should be ^D or that
778      * Alt+NumPad3 should be ^C, for example. There's no serious
779      * inconvenience in having to type a zero before a single-digit
780      * character code.
781      */
782     if (event->type == GDK_KEY_RELEASE) {
783         if ((event->keyval == GDK_KEY_Meta_L ||
784              event->keyval == GDK_KEY_Meta_R ||
785              event->keyval == GDK_KEY_Alt_L ||
786              event->keyval == GDK_KEY_Alt_R) &&
787             inst->alt_keycode >= 0 && inst->alt_digits > 1) {
788 #ifdef KEY_EVENT_DIAGNOSTICS
789             debug((" - modifier release terminates Alt+numberpad input, "
790                    "keycode = %d\n", inst->alt_keycode));
791 #endif
792             /*
793              * FIXME: we might usefully try to do something clever here
794              * about interpreting the generated key code in a way that's
795              * appropriate to the line code page.
796              */
797             output[0] = inst->alt_keycode;
798             end = 1;
799             goto done;
800         }
801 #if GTK_CHECK_VERSION(2,0,0)
802 #ifdef KEY_EVENT_DIAGNOSTICS
803         debug((" - key release, passing to IM\n"));
804 #endif
805         if (gtk_im_context_filter_keypress(inst->imc, event)) {
806 #ifdef KEY_EVENT_DIAGNOSTICS
807             debug((" - key release accepted by IM\n"));
808 #endif
809             return TRUE;
810         } else {
811 #ifdef KEY_EVENT_DIAGNOSTICS
812             debug((" - key release not accepted by IM\n"));
813 #endif
814         }
815 #endif
816     }
817
818     if (event->type == GDK_KEY_PRESS) {
819         /*
820          * NYI: Compose key (!!! requires Unicode faff before even trying)
821          */
822
823         /*
824          * If Alt has just been pressed, we start potentially
825          * accumulating an Alt+numberpad code. We do this by
826          * setting alt_keycode to -1 (nothing yet but plausible).
827          */
828         if ((event->keyval == GDK_KEY_Meta_L ||
829              event->keyval == GDK_KEY_Meta_R ||
830              event->keyval == GDK_KEY_Alt_L ||
831              event->keyval == GDK_KEY_Alt_R)) {
832 #ifdef KEY_EVENT_DIAGNOSTICS
833             debug((" - modifier press potentially begins Alt+numberpad "
834                    "input\n"));
835 #endif
836             inst->alt_keycode = -1;
837             inst->alt_digits = 0;
838             goto done;                 /* this generates nothing else */
839         }
840
841         /*
842          * If we're seeing a numberpad key press with Meta down,
843          * consider adding it to alt_keycode if that's sensible.
844          * Anything _else_ with Meta down cancels any possibility
845          * of an ALT keycode: we set alt_keycode to -2.
846          */
847         if ((event->state & inst->meta_mod_mask) && inst->alt_keycode != -2) {
848             int digit = -1;
849             switch (event->keyval) {
850               case GDK_KEY_KP_0: case GDK_KEY_KP_Insert: digit = 0; break;
851               case GDK_KEY_KP_1: case GDK_KEY_KP_End: digit = 1; break;
852               case GDK_KEY_KP_2: case GDK_KEY_KP_Down: digit = 2; break;
853               case GDK_KEY_KP_3: case GDK_KEY_KP_Page_Down: digit = 3; break;
854               case GDK_KEY_KP_4: case GDK_KEY_KP_Left: digit = 4; break;
855               case GDK_KEY_KP_5: case GDK_KEY_KP_Begin: digit = 5; break;
856               case GDK_KEY_KP_6: case GDK_KEY_KP_Right: digit = 6; break;
857               case GDK_KEY_KP_7: case GDK_KEY_KP_Home: digit = 7; break;
858               case GDK_KEY_KP_8: case GDK_KEY_KP_Up: digit = 8; break;
859               case GDK_KEY_KP_9: case GDK_KEY_KP_Page_Up: digit = 9; break;
860             }
861             if (digit < 0)
862                 inst->alt_keycode = -2;   /* it's invalid */
863             else {
864 #ifdef KEY_EVENT_DIAGNOSTICS
865                 int old_keycode = inst->alt_keycode;
866 #endif
867                 if (inst->alt_keycode == -1)
868                     inst->alt_keycode = digit;   /* one-digit code */
869                 else
870                     inst->alt_keycode = inst->alt_keycode * 10 + digit;
871                 inst->alt_digits++;
872 #ifdef KEY_EVENT_DIAGNOSTICS
873                 debug((" - Alt+numberpad digit %d added to keycode %d"
874                        " gives %d\n", digit, old_keycode, inst->alt_keycode));
875 #endif
876                 /* Having used this digit, we now do nothing more with it. */
877                 goto done;
878             }
879         }
880
881         /*
882          * Shift-PgUp and Shift-PgDn don't even generate keystrokes
883          * at all.
884          */
885         if (event->keyval == GDK_KEY_Page_Up &&
886             (event->state & GDK_SHIFT_MASK)) {
887 #ifdef KEY_EVENT_DIAGNOSTICS
888             debug((" - Shift-PgUp scroll\n"));
889 #endif
890             term_scroll(inst->term, 0, -inst->height/2);
891             return TRUE;
892         }
893         if (event->keyval == GDK_KEY_Page_Up &&
894             (event->state & GDK_CONTROL_MASK)) {
895 #ifdef KEY_EVENT_DIAGNOSTICS
896             debug((" - Ctrl-PgUp scroll\n"));
897 #endif
898             term_scroll(inst->term, 0, -1);
899             return TRUE;
900         }
901         if (event->keyval == GDK_KEY_Page_Down &&
902             (event->state & GDK_SHIFT_MASK)) {
903 #ifdef KEY_EVENT_DIAGNOSTICS
904             debug((" - Shift-PgDn scroll\n"));
905 #endif
906             term_scroll(inst->term, 0, +inst->height/2);
907             return TRUE;
908         }
909         if (event->keyval == GDK_KEY_Page_Down &&
910             (event->state & GDK_CONTROL_MASK)) {
911 #ifdef KEY_EVENT_DIAGNOSTICS
912             debug((" - Ctrl-PgDn scroll\n"));
913 #endif
914             term_scroll(inst->term, 0, +1);
915             return TRUE;
916         }
917
918         /*
919          * Neither does Shift-Ins.
920          */
921         if (event->keyval == GDK_KEY_Insert &&
922             (event->state & GDK_SHIFT_MASK)) {
923 #ifdef KEY_EVENT_DIAGNOSTICS
924             debug((" - Shift-Insert paste\n"));
925 #endif
926             request_paste(inst);
927             return TRUE;
928         }
929
930         special = FALSE;
931         use_ucsoutput = FALSE;
932
933         nethack_mode = conf_get_int(inst->conf, CONF_nethack_keypad);
934         app_keypad_mode = (inst->term->app_keypad_keys &&
935                            !conf_get_int(inst->conf, CONF_no_applic_k));
936
937         /* ALT+things gives leading Escape. */
938         output[0] = '\033';
939 #if !GTK_CHECK_VERSION(2,0,0)
940         /*
941          * In vanilla X, and hence also GDK 1.2, the string received
942          * as part of a keyboard event is assumed to be in
943          * ISO-8859-1. (Seems woefully shortsighted in i18n terms,
944          * but it's true: see the man page for XLookupString(3) for
945          * confirmation.)
946          */
947         output_charset = CS_ISO8859_1;
948         strncpy(output+1, event->string, lenof(output)-1);
949 #else /* !GTK_CHECK_VERSION(2,0,0) */
950         /*
951          * Most things can now be passed to
952          * gtk_im_context_filter_keypress without breaking anything
953          * below this point. An exception is the numeric keypad if
954          * we're in Nethack or application mode: the IM will eat
955          * numeric keypad presses if Num Lock is on, but we don't want
956          * it to.
957          */
958         if (app_keypad_mode &&
959             (event->keyval == GDK_KEY_Num_Lock ||
960              event->keyval == GDK_KEY_KP_Divide ||
961              event->keyval == GDK_KEY_KP_Multiply ||
962              event->keyval == GDK_KEY_KP_Subtract ||
963              event->keyval == GDK_KEY_KP_Add ||
964              event->keyval == GDK_KEY_KP_Enter ||
965              event->keyval == GDK_KEY_KP_0 ||
966              event->keyval == GDK_KEY_KP_Insert ||
967              event->keyval == GDK_KEY_KP_1 ||
968              event->keyval == GDK_KEY_KP_End ||
969              event->keyval == GDK_KEY_KP_2 ||
970              event->keyval == GDK_KEY_KP_Down ||
971              event->keyval == GDK_KEY_KP_3 ||
972              event->keyval == GDK_KEY_KP_Page_Down ||
973              event->keyval == GDK_KEY_KP_4 ||
974              event->keyval == GDK_KEY_KP_Left ||
975              event->keyval == GDK_KEY_KP_5 ||
976              event->keyval == GDK_KEY_KP_Begin ||
977              event->keyval == GDK_KEY_KP_6 ||
978              event->keyval == GDK_KEY_KP_Right ||
979              event->keyval == GDK_KEY_KP_7 ||
980              event->keyval == GDK_KEY_KP_Home ||
981              event->keyval == GDK_KEY_KP_8 ||
982              event->keyval == GDK_KEY_KP_Up ||
983              event->keyval == GDK_KEY_KP_9 ||
984              event->keyval == GDK_KEY_KP_Page_Up ||
985              event->keyval == GDK_KEY_KP_Decimal ||
986              event->keyval == GDK_KEY_KP_Delete)) {
987             /* app keypad; do nothing */
988         } else if (nethack_mode &&
989                    (event->keyval == GDK_KEY_KP_1 ||
990                     event->keyval == GDK_KEY_KP_End ||
991                     event->keyval == GDK_KEY_KP_2 ||
992                     event->keyval == GDK_KEY_KP_Down ||
993                     event->keyval == GDK_KEY_KP_3 ||
994                     event->keyval == GDK_KEY_KP_Page_Down ||
995                     event->keyval == GDK_KEY_KP_4 ||
996                     event->keyval == GDK_KEY_KP_Left ||
997                     event->keyval == GDK_KEY_KP_5 ||
998                     event->keyval == GDK_KEY_KP_Begin ||
999                     event->keyval == GDK_KEY_KP_6 ||
1000                     event->keyval == GDK_KEY_KP_Right ||
1001                     event->keyval == GDK_KEY_KP_7 ||
1002                     event->keyval == GDK_KEY_KP_Home ||
1003                     event->keyval == GDK_KEY_KP_8 ||
1004                     event->keyval == GDK_KEY_KP_Up ||
1005                     event->keyval == GDK_KEY_KP_9 ||
1006                     event->keyval == GDK_KEY_KP_Page_Up)) {
1007             /* nethack mode; do nothing */
1008         } else {
1009             int try_filter = TRUE;
1010
1011 #ifdef META_MANUAL_MASK
1012             if (event->state & META_MANUAL_MASK & inst->meta_mod_mask) {
1013                 /*
1014                  * If this key event had a Meta modifier bit set which
1015                  * is also in META_MANUAL_MASK, that means passing
1016                  * such an event to the GtkIMContext will be unhelpful
1017                  * (it will eat the keystroke and turn it into
1018                  * something not what we wanted).
1019                  */
1020 #ifdef KEY_EVENT_DIAGNOSTICS
1021                 debug((" - Meta modifier requiring manual intervention, "
1022                        "suppressing IM filtering\n"));
1023 #endif
1024                 try_filter = FALSE;
1025             }
1026 #endif
1027
1028             if (try_filter) {
1029 #ifdef KEY_EVENT_DIAGNOSTICS
1030                 debug((" - general key press, passing to IM\n"));
1031 #endif
1032                 if (gtk_im_context_filter_keypress(inst->imc, event)) {
1033 #ifdef KEY_EVENT_DIAGNOSTICS
1034                     debug((" - key press accepted by IM\n"));
1035 #endif
1036                     return TRUE;
1037                 } else {
1038 #ifdef KEY_EVENT_DIAGNOSTICS
1039                     debug((" - key press not accepted by IM\n"));
1040 #endif
1041                 }
1042             }
1043         }
1044
1045         /*
1046          * GDK 2.0 arranges to have done some translation for us: in
1047          * GDK 2.0, event->string is encoded in the current locale.
1048          *
1049          * So we use the standard C library function mbstowcs() to
1050          * convert from the current locale into Unicode; from there
1051          * we can convert to whatever PuTTY is currently working in.
1052          * (In fact I convert straight back to UTF-8 from
1053          * wide-character Unicode, for the sake of simplicity: that
1054          * way we can still use exactly the same code to manipulate
1055          * the string, such as prefixing ESC.)
1056          */
1057         output_charset = CS_UTF8;
1058         {
1059             wchar_t widedata[32];
1060             const wchar_t *wp;
1061             int wlen;
1062             int ulen;
1063
1064             wlen = mb_to_wc(DEFAULT_CODEPAGE, 0,
1065                             event->string, strlen(event->string),
1066                             widedata, lenof(widedata)-1);
1067
1068 #ifdef KEY_EVENT_DIAGNOSTICS
1069             {
1070                 char *string_string = dupstr("");
1071                 int i;
1072
1073                 for (i = 0; i < wlen; i++) {
1074                     char *old = string_string;
1075                     string_string = dupprintf("%s%s%04x", string_string,
1076                                               string_string[0] ? " " : "",
1077                                               (unsigned)widedata[i]);
1078                     sfree(old);
1079                 }
1080                 debug((" - string translated into Unicode = [%s]\n",
1081                        string_string));
1082                 sfree(string_string);
1083             }
1084 #endif
1085
1086             wp = widedata;
1087             ulen = charset_from_unicode(&wp, &wlen, output+1, lenof(output)-2,
1088                                         CS_UTF8, NULL, NULL, 0);
1089
1090 #ifdef KEY_EVENT_DIAGNOSTICS
1091             {
1092                 char *string_string = dupstr("");
1093                 int i;
1094
1095                 for (i = 0; i < ulen; i++) {
1096                     char *old = string_string;
1097                     string_string = dupprintf("%s%s%02x", string_string,
1098                                               string_string[0] ? " " : "",
1099                                               (unsigned)output[i+1] & 0xFF);
1100                     sfree(old);
1101                 }
1102                 debug((" - string translated into UTF-8 = [%s]\n",
1103                        string_string));
1104                 sfree(string_string);
1105             }
1106 #endif
1107
1108             output[1+ulen] = '\0';
1109         }
1110 #endif /* !GTK_CHECK_VERSION(2,0,0) */
1111
1112         if (!output[1] &&
1113             (ucsval = keysym_to_unicode(event->keyval)) >= 0) {
1114             ucsoutput[0] = '\033';
1115             ucsoutput[1] = ucsval;
1116 #ifdef KEY_EVENT_DIAGNOSTICS
1117             debug((" - keysym_to_unicode gave %04x\n",
1118                    (unsigned)ucsoutput[1]));
1119 #endif
1120             use_ucsoutput = TRUE;
1121             end = 2;
1122         } else {
1123             output[lenof(output)-1] = '\0';
1124             end = strlen(output);
1125         }
1126         if (event->state & inst->meta_mod_mask) {
1127             start = 0;
1128             if (end == 1) end = 0;
1129
1130 #ifdef META_MANUAL_MASK
1131             if (event->state & META_MANUAL_MASK) {
1132                 /*
1133                  * Key events which have a META_MANUAL_MASK meta bit
1134                  * set may have a keyval reflecting that, e.g. on OS X
1135                  * the Option key acts as an AltGr-like modifier and
1136                  * causes different Unicode characters to be output.
1137                  *
1138                  * To work around this, we clear the dangerous
1139                  * modifier bit and retranslate from the hardware
1140                  * keycode as if the key had been pressed without that
1141                  * modifier. Then we prefix Esc to *that*.
1142                  */
1143                 guint new_keyval;
1144                 GdkModifierType consumed;
1145                 if (gdk_keymap_translate_keyboard_state
1146                     (gdk_keymap_get_for_display(gdk_display_get_default()),
1147                      event->hardware_keycode, event->state & ~META_MANUAL_MASK,
1148                      0, &new_keyval, NULL, NULL, &consumed)) {
1149                     ucsoutput[0] = '\033';
1150                     ucsoutput[1] = gdk_keyval_to_unicode(new_keyval);
1151 #ifdef KEY_EVENT_DIAGNOSTICS
1152                     {
1153                         char *keyval_name = dup_keyval_name(new_keyval);
1154                         debug((" - retranslation for manual Meta: "
1155                                "new keyval = %s, Unicode = %04x\n",
1156                                keyval_name, (unsigned)ucsoutput[1]));
1157                         sfree(keyval_name);
1158                     }
1159 #endif
1160                     use_ucsoutput = TRUE;
1161                     end = 2;
1162                 }
1163             }
1164 #endif
1165         } else
1166             start = 1;
1167
1168         /* Control-` is the same as Control-\ (unless gtk has a better idea) */
1169         if (!output[1] && event->keyval == '`' &&
1170             (event->state & GDK_CONTROL_MASK)) {
1171 #ifdef KEY_EVENT_DIAGNOSTICS
1172             debug((" - Ctrl-` special case, translating as 1c\n"));
1173 #endif
1174             output[1] = '\x1C';
1175             use_ucsoutput = FALSE;
1176             end = 2;
1177         }
1178
1179         /* Some GTK backends (e.g. Quartz) do not change event->string
1180          * in response to the Control modifier. So we do it ourselves
1181          * here, if it's not already happened.
1182          *
1183          * The translations below are in line with X11 policy as far
1184          * as I know. */
1185         if ((event->state & GDK_CONTROL_MASK) && end == 2) {
1186 #ifdef KEY_EVENT_DIAGNOSTICS
1187             int orig = output[1];
1188 #endif
1189
1190             if (output[1] >= '3' && output[1] <= '7') {
1191                 /* ^3,...,^7 map to 0x1B,...,0x1F */
1192                 output[1] += '\x1B' - '3';
1193             } else if (output[1] == '2' || output[1] == ' ') {
1194                 /* ^2 and ^Space are both ^@, i.e. \0 */
1195                 output[1] = '\0';
1196             } else if (output[1] == '8') {
1197                 /* ^8 is DEL */
1198                 output[1] = '\x7F';
1199             } else if (output[1] == '/') {
1200                 /* ^/ is the same as ^_ */
1201                 output[1] = '\x1F';
1202             } else if (output[1] >= 0x40 && output[1] < 0x7F) {
1203                 /* Everything anywhere near the alphabetics just gets
1204                  * masked. */
1205                 output[1] &= 0x1F;
1206             }
1207             /* Anything else, e.g. '0', is unchanged. */
1208
1209 #ifdef KEY_EVENT_DIAGNOSTICS
1210             if (orig == output[1])
1211                 debug((" - manual Ctrl key handling did nothing\n"));
1212             else
1213                 debug((" - manual Ctrl key handling: %02x -> %02x\n",
1214                        (unsigned)orig, (unsigned)output[1]));
1215 #endif
1216         }
1217
1218         /* Control-Break sends a Break special to the backend */
1219         if (event->keyval == GDK_KEY_Break &&
1220             (event->state & GDK_CONTROL_MASK)) {
1221 #ifdef KEY_EVENT_DIAGNOSTICS
1222             debug((" - Ctrl-Break special case, sending TS_BRK\n"));
1223 #endif
1224             if (inst->back)
1225                 inst->back->special(inst->backhandle, TS_BRK);
1226             return TRUE;
1227         }
1228
1229         /* We handle Return ourselves, because it needs to be flagged as
1230          * special to ldisc. */
1231         if (event->keyval == GDK_KEY_Return) {
1232 #ifdef KEY_EVENT_DIAGNOSTICS
1233             debug((" - Return special case, translating as 0d + special\n"));
1234 #endif
1235             output[1] = '\015';
1236             use_ucsoutput = FALSE;
1237             end = 2;
1238             special = TRUE;
1239         }
1240
1241         /* Control-2, Control-Space and Control-@ are NUL */
1242         if (!output[1] &&
1243             (event->keyval == ' ' || event->keyval == '2' ||
1244              event->keyval == '@') &&
1245             (event->state & (GDK_SHIFT_MASK |
1246                              GDK_CONTROL_MASK)) == GDK_CONTROL_MASK) {
1247 #ifdef KEY_EVENT_DIAGNOSTICS
1248             debug((" - Ctrl-{space,2,@} special case, translating as 00\n"));
1249 #endif
1250             output[1] = '\0';
1251             use_ucsoutput = FALSE;
1252             end = 2;
1253         }
1254
1255         /* Control-Shift-Space is 160 (ISO8859 nonbreaking space) */
1256         if (!output[1] && event->keyval == ' ' &&
1257             (event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK)) ==
1258             (GDK_SHIFT_MASK | GDK_CONTROL_MASK)) {
1259 #ifdef KEY_EVENT_DIAGNOSTICS
1260             debug((" - Ctrl-Shift-space special case, translating as 00a0\n"));
1261 #endif
1262             output[1] = '\240';
1263             output_charset = CS_ISO8859_1;
1264             use_ucsoutput = FALSE;
1265             end = 2;
1266         }
1267
1268         /* We don't let GTK tell us what Backspace is! We know better. */
1269         if (event->keyval == GDK_KEY_BackSpace &&
1270             !(event->state & GDK_SHIFT_MASK)) {
1271             output[1] = conf_get_int(inst->conf, CONF_bksp_is_delete) ?
1272                 '\x7F' : '\x08';
1273 #ifdef KEY_EVENT_DIAGNOSTICS
1274             debug((" - Backspace, translating as %02x\n",
1275                    (unsigned)output[1]));
1276 #endif
1277             use_ucsoutput = FALSE;
1278             end = 2;
1279             special = TRUE;
1280         }
1281         /* For Shift Backspace, do opposite of what is configured. */
1282         if (event->keyval == GDK_KEY_BackSpace &&
1283             (event->state & GDK_SHIFT_MASK)) {
1284             output[1] = conf_get_int(inst->conf, CONF_bksp_is_delete) ?
1285                 '\x08' : '\x7F';
1286 #ifdef KEY_EVENT_DIAGNOSTICS
1287             debug((" - Shift-Backspace, translating as %02x\n",
1288                    (unsigned)output[1]));
1289 #endif
1290             use_ucsoutput = FALSE;
1291             end = 2;
1292             special = TRUE;
1293         }
1294
1295         /* Shift-Tab is ESC [ Z */
1296         if (event->keyval == GDK_KEY_ISO_Left_Tab ||
1297             (event->keyval == GDK_KEY_Tab &&
1298              (event->state & GDK_SHIFT_MASK))) {
1299 #ifdef KEY_EVENT_DIAGNOSTICS
1300             debug((" - Shift-Tab, translating as ESC [ Z\n"));
1301 #endif
1302             end = 1 + sprintf(output+1, "\033[Z");
1303             use_ucsoutput = FALSE;
1304         }
1305         /* And normal Tab is Tab, if the keymap hasn't already told us.
1306          * (Curiously, at least one version of the MacOS 10.5 X server
1307          * doesn't translate Tab for us. */
1308         if (event->keyval == GDK_KEY_Tab && end <= 1) {
1309 #ifdef KEY_EVENT_DIAGNOSTICS
1310             debug((" - Tab, translating as 09\n"));
1311 #endif
1312             output[1] = '\t';
1313             end = 2;
1314         }
1315
1316         /*
1317          * NetHack keypad mode.
1318          */
1319         if (nethack_mode) {
1320             const char *keys = NULL;
1321             switch (event->keyval) {
1322               case GDK_KEY_KP_1: case GDK_KEY_KP_End:
1323                 keys = "bB\002"; break;
1324               case GDK_KEY_KP_2: case GDK_KEY_KP_Down:
1325                 keys = "jJ\012"; break;
1326               case GDK_KEY_KP_3: case GDK_KEY_KP_Page_Down:
1327                 keys = "nN\016"; break;
1328               case GDK_KEY_KP_4: case GDK_KEY_KP_Left:
1329                 keys = "hH\010"; break;
1330               case GDK_KEY_KP_5: case GDK_KEY_KP_Begin:
1331                 keys = "..."; break;
1332               case GDK_KEY_KP_6: case GDK_KEY_KP_Right:
1333                 keys = "lL\014"; break;
1334               case GDK_KEY_KP_7: case GDK_KEY_KP_Home:
1335                 keys = "yY\031"; break;
1336               case GDK_KEY_KP_8: case GDK_KEY_KP_Up:
1337                 keys = "kK\013"; break;
1338               case GDK_KEY_KP_9: case GDK_KEY_KP_Page_Up:
1339                 keys = "uU\025"; break;
1340             }
1341             if (keys) {
1342                 end = 2;
1343                 if (event->state & GDK_CONTROL_MASK)
1344                     output[1] = keys[2];
1345                 else if (event->state & GDK_SHIFT_MASK)
1346                     output[1] = keys[1];
1347                 else
1348                     output[1] = keys[0];
1349 #ifdef KEY_EVENT_DIAGNOSTICS
1350                 debug((" - Nethack-mode key"));
1351 #endif
1352                 use_ucsoutput = FALSE;
1353                 goto done;
1354             }
1355         }
1356
1357         /*
1358          * Application keypad mode.
1359          */
1360         if (app_keypad_mode) {
1361             int xkey = 0;
1362             switch (event->keyval) {
1363               case GDK_KEY_Num_Lock: xkey = 'P'; break;
1364               case GDK_KEY_KP_Divide: xkey = 'Q'; break;
1365               case GDK_KEY_KP_Multiply: xkey = 'R'; break;
1366               case GDK_KEY_KP_Subtract: xkey = 'S'; break;
1367                 /*
1368                  * Keypad + is tricky. It covers a space that would
1369                  * be taken up on the VT100 by _two_ keys; so we
1370                  * let Shift select between the two. Worse still,
1371                  * in xterm function key mode we change which two...
1372                  */
1373               case GDK_KEY_KP_Add:
1374                 if (conf_get_int(inst->conf, CONF_funky_type) == FUNKY_XTERM) {
1375                     if (event->state & GDK_SHIFT_MASK)
1376                         xkey = 'l';
1377                     else
1378                         xkey = 'k';
1379                 } else if (event->state & GDK_SHIFT_MASK)
1380                         xkey = 'm';
1381                 else
1382                     xkey = 'l';
1383                 break;
1384               case GDK_KEY_KP_Enter: xkey = 'M'; break;
1385               case GDK_KEY_KP_0: case GDK_KEY_KP_Insert: xkey = 'p'; break;
1386               case GDK_KEY_KP_1: case GDK_KEY_KP_End: xkey = 'q'; break;
1387               case GDK_KEY_KP_2: case GDK_KEY_KP_Down: xkey = 'r'; break;
1388               case GDK_KEY_KP_3: case GDK_KEY_KP_Page_Down: xkey = 's'; break;
1389               case GDK_KEY_KP_4: case GDK_KEY_KP_Left: xkey = 't'; break;
1390               case GDK_KEY_KP_5: case GDK_KEY_KP_Begin: xkey = 'u'; break;
1391               case GDK_KEY_KP_6: case GDK_KEY_KP_Right: xkey = 'v'; break;
1392               case GDK_KEY_KP_7: case GDK_KEY_KP_Home: xkey = 'w'; break;
1393               case GDK_KEY_KP_8: case GDK_KEY_KP_Up: xkey = 'x'; break;
1394               case GDK_KEY_KP_9: case GDK_KEY_KP_Page_Up: xkey = 'y'; break;
1395               case GDK_KEY_KP_Decimal: case GDK_KEY_KP_Delete:
1396                 xkey = 'n'; break;
1397             }
1398             if (xkey) {
1399                 if (inst->term->vt52_mode) {
1400                     if (xkey >= 'P' && xkey <= 'S')
1401                         end = 1 + sprintf(output+1, "\033%c", xkey);
1402                     else
1403                         end = 1 + sprintf(output+1, "\033?%c", xkey);
1404                 } else
1405                     end = 1 + sprintf(output+1, "\033O%c", xkey);
1406                 use_ucsoutput = FALSE;
1407 #ifdef KEY_EVENT_DIAGNOSTICS
1408                 debug((" - Application keypad mode key"));
1409 #endif
1410                 goto done;
1411             }
1412         }
1413
1414         /*
1415          * Next, all the keys that do tilde codes. (ESC '[' nn '~',
1416          * for integer decimal nn.)
1417          *
1418          * We also deal with the weird ones here. Linux VCs replace F1
1419          * to F5 by ESC [ [ A to ESC [ [ E. rxvt doesn't do _that_, but
1420          * does replace Home and End (1~ and 4~) by ESC [ H and ESC O w
1421          * respectively.
1422          */
1423         {
1424             int code = 0;
1425             int funky_type = conf_get_int(inst->conf, CONF_funky_type);
1426             switch (event->keyval) {
1427               case GDK_KEY_F1:
1428                 code = (event->state & GDK_SHIFT_MASK ? 23 : 11);
1429                 break;
1430               case GDK_KEY_F2:
1431                 code = (event->state & GDK_SHIFT_MASK ? 24 : 12);
1432                 break;
1433               case GDK_KEY_F3:
1434                 code = (event->state & GDK_SHIFT_MASK ? 25 : 13);
1435                 break;
1436               case GDK_KEY_F4:
1437                 code = (event->state & GDK_SHIFT_MASK ? 26 : 14);
1438                 break;
1439               case GDK_KEY_F5:
1440                 code = (event->state & GDK_SHIFT_MASK ? 28 : 15);
1441                 break;
1442               case GDK_KEY_F6:
1443                 code = (event->state & GDK_SHIFT_MASK ? 29 : 17);
1444                 break;
1445               case GDK_KEY_F7:
1446                 code = (event->state & GDK_SHIFT_MASK ? 31 : 18);
1447                 break;
1448               case GDK_KEY_F8:
1449                 code = (event->state & GDK_SHIFT_MASK ? 32 : 19);
1450                 break;
1451               case GDK_KEY_F9:
1452                 code = (event->state & GDK_SHIFT_MASK ? 33 : 20);
1453                 break;
1454               case GDK_KEY_F10:
1455                 code = (event->state & GDK_SHIFT_MASK ? 34 : 21);
1456                 break;
1457               case GDK_KEY_F11:
1458                 code = 23;
1459                 break;
1460               case GDK_KEY_F12:
1461                 code = 24;
1462                 break;
1463               case GDK_KEY_F13:
1464                 code = 25;
1465                 break;
1466               case GDK_KEY_F14:
1467                 code = 26;
1468                 break;
1469               case GDK_KEY_F15:
1470                 code = 28;
1471                 break;
1472               case GDK_KEY_F16:
1473                 code = 29;
1474                 break;
1475               case GDK_KEY_F17:
1476                 code = 31;
1477                 break;
1478               case GDK_KEY_F18:
1479                 code = 32;
1480                 break;
1481               case GDK_KEY_F19:
1482                 code = 33;
1483                 break;
1484               case GDK_KEY_F20:
1485                 code = 34;
1486                 break;
1487             }
1488             if (!(event->state & GDK_CONTROL_MASK)) switch (event->keyval) {
1489               case GDK_KEY_Home: case GDK_KEY_KP_Home:
1490                 code = 1;
1491                 break;
1492               case GDK_KEY_Insert: case GDK_KEY_KP_Insert:
1493                 code = 2;
1494                 break;
1495               case GDK_KEY_Delete: case GDK_KEY_KP_Delete:
1496                 code = 3;
1497                 break;
1498               case GDK_KEY_End: case GDK_KEY_KP_End:
1499                 code = 4;
1500                 break;
1501               case GDK_KEY_Page_Up: case GDK_KEY_KP_Page_Up:
1502                 code = 5;
1503                 break;
1504               case GDK_KEY_Page_Down: case GDK_KEY_KP_Page_Down:
1505                 code = 6;
1506                 break;
1507             }
1508             /* Reorder edit keys to physical order */
1509             if (funky_type == FUNKY_VT400 && code <= 6)
1510                 code = "\0\2\1\4\5\3\6"[code];
1511
1512             if (inst->term->vt52_mode && code > 0 && code <= 6) {
1513                 end = 1 + sprintf(output+1, "\x1B%c", " HLMEIG"[code]);
1514 #ifdef KEY_EVENT_DIAGNOSTICS
1515                 debug((" - VT52 mode small keypad key"));
1516 #endif
1517                 use_ucsoutput = FALSE;
1518                 goto done;
1519             }
1520
1521             if (funky_type == FUNKY_SCO &&     /* SCO function keys */
1522                 code >= 11 && code <= 34) {
1523                 char codes[] = "MNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@[\\]^_`{";
1524                 int index = 0;
1525                 switch (event->keyval) {
1526                   case GDK_KEY_F1: index = 0; break;
1527                   case GDK_KEY_F2: index = 1; break;
1528                   case GDK_KEY_F3: index = 2; break;
1529                   case GDK_KEY_F4: index = 3; break;
1530                   case GDK_KEY_F5: index = 4; break;
1531                   case GDK_KEY_F6: index = 5; break;
1532                   case GDK_KEY_F7: index = 6; break;
1533                   case GDK_KEY_F8: index = 7; break;
1534                   case GDK_KEY_F9: index = 8; break;
1535                   case GDK_KEY_F10: index = 9; break;
1536                   case GDK_KEY_F11: index = 10; break;
1537                   case GDK_KEY_F12: index = 11; break;
1538                 }
1539                 if (event->state & GDK_SHIFT_MASK) index += 12;
1540                 if (event->state & GDK_CONTROL_MASK) index += 24;
1541                 end = 1 + sprintf(output+1, "\x1B[%c", codes[index]);
1542 #ifdef KEY_EVENT_DIAGNOSTICS
1543                 debug((" - SCO mode function key"));
1544 #endif
1545                 use_ucsoutput = FALSE;
1546                 goto done;
1547             }
1548             if (funky_type == FUNKY_SCO &&     /* SCO small keypad */
1549                 code >= 1 && code <= 6) {
1550                 char codes[] = "HL.FIG";
1551                 if (code == 3) {
1552                     output[1] = '\x7F';
1553                     end = 2;
1554                 } else {
1555                     end = 1 + sprintf(output+1, "\x1B[%c", codes[code-1]);
1556                 }
1557 #ifdef KEY_EVENT_DIAGNOSTICS
1558                 debug((" - SCO mode small keypad key"));
1559 #endif
1560                 use_ucsoutput = FALSE;
1561                 goto done;
1562             }
1563             if ((inst->term->vt52_mode || funky_type == FUNKY_VT100P) &&
1564                 code >= 11 && code <= 24) {
1565                 int offt = 0;
1566                 if (code > 15)
1567                     offt++;
1568                 if (code > 21)
1569                     offt++;
1570                 if (inst->term->vt52_mode) {
1571 #ifdef KEY_EVENT_DIAGNOSTICS
1572                     debug((" - VT52 mode function key"));
1573 #endif
1574                     end = 1 + sprintf(output+1,
1575                                       "\x1B%c", code + 'P' - 11 - offt);
1576                 } else {
1577 #ifdef KEY_EVENT_DIAGNOSTICS
1578                     debug((" - VT100+ mode function key"));
1579 #endif
1580                     end = 1 + sprintf(output+1,
1581                                       "\x1BO%c", code + 'P' - 11 - offt);
1582                 }
1583                 use_ucsoutput = FALSE;
1584                 goto done;
1585             }
1586             if (funky_type == FUNKY_LINUX && code >= 11 && code <= 15) {
1587                 end = 1 + sprintf(output+1, "\x1B[[%c", code + 'A' - 11);
1588 #ifdef KEY_EVENT_DIAGNOSTICS
1589                 debug((" - Linux mode F1-F5 function key"));
1590 #endif
1591                 use_ucsoutput = FALSE;
1592                 goto done;
1593             }
1594             if (funky_type == FUNKY_XTERM && code >= 11 && code <= 14) {
1595                 if (inst->term->vt52_mode) {
1596 #ifdef KEY_EVENT_DIAGNOSTICS
1597                     debug((" - VT52 mode (overriding xterm) F1-F4 function"
1598                            " key"));
1599 #endif
1600                     end = 1 + sprintf(output+1, "\x1B%c", code + 'P' - 11);
1601                 } else {
1602 #ifdef KEY_EVENT_DIAGNOSTICS
1603                     debug((" - xterm mode F1-F4 function key"));
1604 #endif
1605                     end = 1 + sprintf(output+1, "\x1BO%c", code + 'P' - 11);
1606                 }
1607                 use_ucsoutput = FALSE;
1608                 goto done;
1609             }
1610             if ((code == 1 || code == 4) &&
1611                 conf_get_int(inst->conf, CONF_rxvt_homeend)) {
1612 #ifdef KEY_EVENT_DIAGNOSTICS
1613                 debug((" - rxvt style Home/End"));
1614 #endif
1615                 end = 1 + sprintf(output+1, code == 1 ? "\x1B[H" : "\x1BOw");
1616                 use_ucsoutput = FALSE;
1617                 goto done;
1618             }
1619             if (code) {
1620 #ifdef KEY_EVENT_DIAGNOSTICS
1621                 debug((" - ordinary function key encoding"));
1622 #endif
1623                 end = 1 + sprintf(output+1, "\x1B[%d~", code);
1624                 use_ucsoutput = FALSE;
1625                 goto done;
1626             }
1627         }
1628
1629         /*
1630          * Cursor keys. (This includes the numberpad cursor keys,
1631          * if we haven't already done them due to app keypad mode.)
1632          * 
1633          * Here we also process un-numlocked un-appkeypadded KP5,
1634          * which sends ESC [ G.
1635          */
1636         {
1637             int xkey = 0;
1638             switch (event->keyval) {
1639               case GDK_KEY_Up: case GDK_KEY_KP_Up: xkey = 'A'; break;
1640               case GDK_KEY_Down: case GDK_KEY_KP_Down: xkey = 'B'; break;
1641               case GDK_KEY_Right: case GDK_KEY_KP_Right: xkey = 'C'; break;
1642               case GDK_KEY_Left: case GDK_KEY_KP_Left: xkey = 'D'; break;
1643               case GDK_KEY_Begin: case GDK_KEY_KP_Begin: xkey = 'G'; break;
1644             }
1645             if (xkey) {
1646                 end = 1 + format_arrow_key(output+1, inst->term, xkey,
1647                                            event->state & GDK_CONTROL_MASK);
1648 #ifdef KEY_EVENT_DIAGNOSTICS
1649                 debug((" - arrow key"));
1650 #endif
1651                 use_ucsoutput = FALSE;
1652                 goto done;
1653             }
1654         }
1655         goto done;
1656     }
1657
1658     done:
1659
1660     if (end-start > 0) {
1661         if (special) {
1662 #ifdef KEY_EVENT_DIAGNOSTICS
1663             char *string_string = dupstr("");
1664             int i;
1665
1666             for (i = start; i < end; i++) {
1667                 char *old = string_string;
1668                 string_string = dupprintf("%s%s%02x", string_string,
1669                                           string_string[0] ? " " : "",
1670                                           (unsigned)output[i] & 0xFF);
1671                 sfree(old);
1672             }
1673             debug((" - final output, special, generic encoding = [%s]\n",
1674                    charset_to_localenc(output_charset), string_string));
1675             sfree(string_string);
1676 #endif
1677             /*
1678              * For special control characters, the character set
1679              * should never matter.
1680              */
1681             output[end] = '\0';        /* NUL-terminate */
1682             if (inst->ldisc)
1683                 ldisc_send(inst->ldisc, output+start, -2, 1);
1684         } else if (!inst->direct_to_font) {
1685             if (!use_ucsoutput) {
1686 #ifdef KEY_EVENT_DIAGNOSTICS
1687                 char *string_string = dupstr("");
1688                 int i;
1689
1690                 for (i = start; i < end; i++) {
1691                     char *old = string_string;
1692                     string_string = dupprintf("%s%s%02x", string_string,
1693                                               string_string[0] ? " " : "",
1694                                               (unsigned)output[i] & 0xFF);
1695                     sfree(old);
1696                 }
1697                 debug((" - final output in %s = [%s]\n",
1698                        charset_to_localenc(output_charset), string_string));
1699                 sfree(string_string);
1700 #endif
1701                 if (inst->ldisc)
1702                     lpage_send(inst->ldisc, output_charset, output+start,
1703                                end-start, 1);
1704             } else {
1705 #ifdef KEY_EVENT_DIAGNOSTICS
1706                 char *string_string = dupstr("");
1707                 int i;
1708
1709                 for (i = start; i < end; i++) {
1710                     char *old = string_string;
1711                     string_string = dupprintf("%s%s%04x", string_string,
1712                                               string_string[0] ? " " : "",
1713                                               (unsigned)ucsoutput[i]);
1714                     sfree(old);
1715                 }
1716                 debug((" - final output in Unicode = [%s]\n",
1717                        string_string));
1718                 sfree(string_string);
1719 #endif
1720
1721                 /*
1722                  * We generated our own Unicode key data from the
1723                  * keysym, so use that instead.
1724                  */
1725                 if (inst->ldisc)
1726                     luni_send(inst->ldisc, ucsoutput+start, end-start, 1);
1727             }
1728         } else {
1729             /*
1730              * In direct-to-font mode, we just send the string
1731              * exactly as we received it.
1732              */
1733 #ifdef KEY_EVENT_DIAGNOSTICS
1734             char *string_string = dupstr("");
1735             int i;
1736
1737             for (i = start; i < end; i++) {
1738                 char *old = string_string;
1739                 string_string = dupprintf("%s%s%02x", string_string,
1740                                           string_string[0] ? " " : "",
1741                                           (unsigned)output[i] & 0xFF);
1742                 sfree(old);
1743             }
1744             debug((" - final output in direct-to-font encoding = [%s]\n",
1745                    string_string));
1746             sfree(string_string);
1747 #endif
1748             if (inst->ldisc)
1749                 ldisc_send(inst->ldisc, output+start, end-start, 1);
1750         }
1751
1752         show_mouseptr(inst, 0);
1753         term_seen_key_event(inst->term);
1754     }
1755
1756     return TRUE;
1757 }
1758
1759 #if GTK_CHECK_VERSION(2,0,0)
1760 void input_method_commit_event(GtkIMContext *imc, gchar *str, gpointer data)
1761 {
1762     struct gui_data *inst = (struct gui_data *)data;
1763
1764 #ifdef KEY_EVENT_DIAGNOSTICS
1765     char *string_string = dupstr("");
1766     int i;
1767
1768     for (i = 0; str[i]; i++) {
1769         char *old = string_string;
1770         string_string = dupprintf("%s%s%02x", string_string,
1771                                   string_string[0] ? " " : "",
1772                                   (unsigned)str[i] & 0xFF);
1773         sfree(old);
1774     }
1775     debug((" - IM commit event in UTF-8 = [%s]\n", string_string));
1776     sfree(string_string);
1777 #endif
1778
1779     if (inst->ldisc)
1780         lpage_send(inst->ldisc, CS_UTF8, str, strlen(str), 1);
1781     show_mouseptr(inst, 0);
1782     term_seen_key_event(inst->term);
1783 }
1784 #endif
1785
1786 gboolean button_internal(struct gui_data *inst, guint32 timestamp,
1787                          GdkEventType type, guint ebutton, guint state,
1788                          gdouble ex, gdouble ey)
1789 {
1790     int shift, ctrl, alt, x, y, button, act, raw_mouse_mode;
1791
1792     /* Remember the timestamp. */
1793     inst->input_event_time = timestamp;
1794
1795     show_mouseptr(inst, 1);
1796
1797     shift = state & GDK_SHIFT_MASK;
1798     ctrl = state & GDK_CONTROL_MASK;
1799     alt = state & inst->meta_mod_mask;
1800
1801     raw_mouse_mode =
1802         send_raw_mouse && !(shift && conf_get_int(inst->conf,
1803                                                   CONF_mouse_override));
1804
1805     if (!raw_mouse_mode) {
1806         if (ebutton == 4 && type == GDK_BUTTON_PRESS) {
1807             term_scroll(inst->term, 0, -5);
1808             return TRUE;
1809         }
1810         if (ebutton == 5 && type == GDK_BUTTON_PRESS) {
1811             term_scroll(inst->term, 0, +5);
1812             return TRUE;
1813         }
1814     }
1815
1816     if (ebutton == 3 && ctrl) {
1817         gtk_menu_popup(GTK_MENU(inst->menu), NULL, NULL, NULL, NULL,
1818                        ebutton, timestamp);
1819         return TRUE;
1820     }
1821
1822     if (ebutton == 1)
1823         button = MBT_LEFT;
1824     else if (ebutton == 2)
1825         button = MBT_MIDDLE;
1826     else if (ebutton == 3)
1827         button = MBT_RIGHT;
1828     else if (ebutton == 4)
1829         button = MBT_WHEEL_UP;
1830     else if (ebutton == 5)
1831         button = MBT_WHEEL_DOWN;
1832     else
1833         return FALSE;                  /* don't even know what button! */
1834
1835     switch (type) {
1836       case GDK_BUTTON_PRESS: act = MA_CLICK; break;
1837       case GDK_BUTTON_RELEASE: act = MA_RELEASE; break;
1838       case GDK_2BUTTON_PRESS: act = MA_2CLK; break;
1839       case GDK_3BUTTON_PRESS: act = MA_3CLK; break;
1840       default: return FALSE;           /* don't know this event type */
1841     }
1842
1843     if (raw_mouse_mode && act != MA_CLICK && act != MA_RELEASE)
1844         return TRUE;                   /* we ignore these in raw mouse mode */
1845
1846     x = (ex - inst->window_border) / inst->font_width;
1847     y = (ey - inst->window_border) / inst->font_height;
1848
1849     term_mouse(inst->term, button, translate_button(button), act,
1850                x, y, shift, ctrl, alt);
1851
1852     return TRUE;
1853 }
1854
1855 gboolean button_event(GtkWidget *widget, GdkEventButton *event, gpointer data)
1856 {
1857     struct gui_data *inst = (struct gui_data *)data;
1858     return button_internal(inst, event->time, event->type, event->button,
1859                            event->state, event->x, event->y);
1860 }
1861
1862 #if GTK_CHECK_VERSION(2,0,0)
1863 /*
1864  * In GTK 2, mouse wheel events have become a new type of event.
1865  * This handler translates them back into button-4 and button-5
1866  * presses so that I don't have to change my old code too much :-)
1867  */
1868 gboolean scroll_event(GtkWidget *widget, GdkEventScroll *event, gpointer data)
1869 {
1870     struct gui_data *inst = (struct gui_data *)data;
1871     guint button;
1872
1873     if (event->direction == GDK_SCROLL_UP)
1874         button = 4;
1875     else if (event->direction == GDK_SCROLL_DOWN)
1876         button = 5;
1877     else
1878         return FALSE;
1879
1880     return button_internal(inst, event->time, GDK_BUTTON_PRESS,
1881                            button, event->state, event->x, event->y);
1882 }
1883 #endif
1884
1885 gint motion_event(GtkWidget *widget, GdkEventMotion *event, gpointer data)
1886 {
1887     struct gui_data *inst = (struct gui_data *)data;
1888     int shift, ctrl, alt, x, y, button;
1889
1890     /* Remember the timestamp. */
1891     inst->input_event_time = event->time;
1892
1893     show_mouseptr(inst, 1);
1894
1895     shift = event->state & GDK_SHIFT_MASK;
1896     ctrl = event->state & GDK_CONTROL_MASK;
1897     alt = event->state & inst->meta_mod_mask;
1898     if (event->state & GDK_BUTTON1_MASK)
1899         button = MBT_LEFT;
1900     else if (event->state & GDK_BUTTON2_MASK)
1901         button = MBT_MIDDLE;
1902     else if (event->state & GDK_BUTTON3_MASK)
1903         button = MBT_RIGHT;
1904     else
1905         return FALSE;                  /* don't even know what button! */
1906
1907     x = (event->x - inst->window_border) / inst->font_width;
1908     y = (event->y - inst->window_border) / inst->font_height;
1909
1910     term_mouse(inst->term, button, translate_button(button), MA_DRAG,
1911                x, y, shift, ctrl, alt);
1912
1913     return TRUE;
1914 }
1915
1916 void frontend_keypress(void *handle)
1917 {
1918     struct gui_data *inst = (struct gui_data *)handle;
1919
1920     /*
1921      * If our child process has exited but not closed, terminate on
1922      * any keypress.
1923      */
1924     if (inst->exited)
1925         cleanup_exit(0);
1926 }
1927
1928 static void exit_callback(void *vinst)
1929 {
1930     struct gui_data *inst = (struct gui_data *)vinst;
1931     int exitcode, close_on_exit;
1932
1933     if (!inst->exited &&
1934         (exitcode = inst->back->exitcode(inst->backhandle)) >= 0) {
1935         inst->exited = TRUE;
1936         close_on_exit = conf_get_int(inst->conf, CONF_close_on_exit);
1937         if (close_on_exit == FORCE_ON ||
1938             (close_on_exit == AUTO && exitcode == 0))
1939             gtk_main_quit();           /* just go */
1940         if (inst->ldisc) {
1941             ldisc_free(inst->ldisc);
1942             inst->ldisc = NULL;
1943         }
1944         inst->back->free(inst->backhandle);
1945         inst->backhandle = NULL;
1946         inst->back = NULL;
1947         term_provide_resize_fn(inst->term, NULL, NULL);
1948         update_specials_menu(inst);
1949         gtk_widget_set_sensitive(inst->restartitem, TRUE);
1950     }
1951 }
1952
1953 /*
1954  * Replacement code for the gtk_quit_add() function, which GTK2 - in
1955  * their unbounded wisdom - deprecated without providing any usable
1956  * replacement, and which we were using to ensure that our idle
1957  * function for toplevel callbacks was only run from the outermost
1958  * gtk_main().
1959  *
1960  * We maintain a global variable with a list of 'struct gui_data'
1961  * instances on which we should call inst_post_main() when a
1962  * subsidiary gtk_main() terminates; then we must make sure that all
1963  * our subsidiary calls to gtk_main() are followed by a call to
1964  * post_main().
1965  *
1966  * This is kind of overkill in the sense that at the time of writing
1967  * we don't actually ever run more than one 'struct gui_data' instance
1968  * in the same process, but we're _so nearly_ prepared to do that that
1969  * I want to remain futureproof against the possibility of doing so in
1970  * future.
1971  */
1972 struct post_main_context {
1973     struct post_main_context *next;
1974     struct gui_data *inst;
1975 };
1976 struct post_main_context *post_main_list_head = NULL;
1977 static void request_post_main(struct gui_data *inst)
1978 {
1979     struct post_main_context *node = snew(struct post_main_context);
1980     node->next = post_main_list_head;
1981     node->inst = inst;
1982     post_main_list_head = node;
1983 }
1984 static void inst_post_main(struct gui_data *inst);
1985 void post_main(void)
1986 {
1987     while (post_main_list_head) {
1988         struct post_main_context *node = post_main_list_head;
1989         post_main_list_head = node->next;
1990         inst_post_main(node->inst);
1991         sfree(node);
1992     }
1993 }
1994
1995 void notify_remote_exit(void *frontend)
1996 {
1997     struct gui_data *inst = (struct gui_data *)frontend;
1998
1999     queue_toplevel_callback(exit_callback, inst);
2000 }
2001
2002 static void notify_toplevel_callback(void *frontend);
2003
2004 static void inst_post_main(struct gui_data *inst)
2005 {
2006     if (gtk_main_level() == 1) {
2007         notify_toplevel_callback(inst);
2008         inst->quit_fn_scheduled = FALSE;
2009     } else {
2010         /* Apparently we're _still_ more than one level deep in
2011          * gtk_main() instances, so we'll need another callback for
2012          * when we get out of the next one. */
2013         request_post_main(inst);
2014     }
2015 }
2016
2017 static gint idle_toplevel_callback_func(gpointer data)
2018 {
2019     struct gui_data *inst = (struct gui_data *)data;
2020
2021     if (gtk_main_level() > 1) {
2022         /*
2023          * We don't run the callbacks if we're in the middle of a
2024          * subsidiary gtk_main. Instead, ask for a callback when we
2025          * get back out of the subsidiary main loop (if we haven't
2026          * already arranged one), so we can reschedule ourself then.
2027          */
2028         if (!inst->quit_fn_scheduled) {
2029             request_post_main(inst);
2030             inst->quit_fn_scheduled = TRUE;
2031         }
2032         /*
2033          * And unschedule this idle function, since we've now done
2034          * everything we can until the innermost gtk_main has quit and
2035          * can reschedule us with a chance of actually taking action.
2036          */
2037         if (inst->idle_fn_scheduled) { /* double-check, just in case */
2038             g_source_remove(inst->toplevel_callback_idle_id);
2039             inst->idle_fn_scheduled = FALSE;
2040         }
2041     } else {
2042         run_toplevel_callbacks();
2043     }
2044
2045     /*
2046      * If we've emptied our toplevel callback queue, unschedule
2047      * ourself. Otherwise, leave ourselves pending so we'll be called
2048      * again to deal with more callbacks after another round of the
2049      * event loop.
2050      */
2051     if (!toplevel_callback_pending() && inst->idle_fn_scheduled) {
2052         g_source_remove(inst->toplevel_callback_idle_id);
2053         inst->idle_fn_scheduled = FALSE;
2054     }
2055
2056     return TRUE;
2057 }
2058
2059 static void notify_toplevel_callback(void *frontend)
2060 {
2061     struct gui_data *inst = (struct gui_data *)frontend;
2062
2063     if (!inst->idle_fn_scheduled) {
2064         inst->toplevel_callback_idle_id =
2065             g_idle_add(idle_toplevel_callback_func, inst);
2066         inst->idle_fn_scheduled = TRUE;
2067     }
2068 }
2069
2070 static gint timer_trigger(gpointer data)
2071 {
2072     unsigned long now = GPOINTER_TO_LONG(data);
2073     unsigned long next, then;
2074     long ticks;
2075
2076     /*
2077      * Destroy the timer we got here on.
2078      */
2079     if (timer_id) {
2080         g_source_remove(timer_id);
2081         timer_id = 0;
2082     }
2083
2084     /*
2085      * run_timers() may cause a call to timer_change_notify, in which
2086      * case a new timer will already have been set up and left in
2087      * timer_id. If it hasn't, and run_timers reports that some timing
2088      * still needs to be done, we do it ourselves.
2089      */
2090     if (run_timers(now, &next) && !timer_id) {
2091         then = now;
2092         now = GETTICKCOUNT();
2093         if (now - then > next - then)
2094             ticks = 0;
2095         else
2096             ticks = next - now;
2097         timer_id = g_timeout_add(ticks, timer_trigger, LONG_TO_GPOINTER(next));
2098     }
2099
2100     /*
2101      * Returning FALSE means 'don't call this timer again', which
2102      * _should_ be redundant given that we removed it above, but just
2103      * in case, return FALSE anyway.
2104      */
2105     return FALSE;
2106 }
2107
2108 void timer_change_notify(unsigned long next)
2109 {
2110     long ticks;
2111
2112     if (timer_id)
2113         g_source_remove(timer_id);
2114
2115     ticks = next - GETTICKCOUNT();
2116     if (ticks <= 0)
2117         ticks = 1;                     /* just in case */
2118
2119     timer_id = g_timeout_add(ticks, timer_trigger, LONG_TO_GPOINTER(next));
2120 }
2121
2122 #if GTK_CHECK_VERSION(2,0,0)
2123 gboolean fd_input_func(GIOChannel *source, GIOCondition condition,
2124                        gpointer data)
2125 {
2126     int sourcefd = g_io_channel_unix_get_fd(source);
2127     /*
2128      * We must process exceptional notifications before ordinary
2129      * readability ones, or we may go straight past the urgent
2130      * marker.
2131      */
2132     if (condition & G_IO_PRI)
2133         select_result(sourcefd, 4);
2134     if (condition & G_IO_IN)
2135         select_result(sourcefd, 1);
2136     if (condition & G_IO_OUT)
2137         select_result(sourcefd, 2);
2138
2139     return TRUE;
2140 }
2141 #else
2142 void fd_input_func(gpointer data, gint sourcefd, GdkInputCondition condition)
2143 {
2144     if (condition & GDK_INPUT_EXCEPTION)
2145         select_result(sourcefd, 4);
2146     if (condition & GDK_INPUT_READ)
2147         select_result(sourcefd, 1);
2148     if (condition & GDK_INPUT_WRITE)
2149         select_result(sourcefd, 2);
2150 }
2151 #endif
2152
2153 void destroy(GtkWidget *widget, gpointer data)
2154 {
2155     gtk_main_quit();
2156 }
2157
2158 gint focus_event(GtkWidget *widget, GdkEventFocus *event, gpointer data)
2159 {
2160     struct gui_data *inst = (struct gui_data *)data;
2161     term_set_focus(inst->term, event->in);
2162     term_update(inst->term);
2163     show_mouseptr(inst, 1);
2164     return FALSE;
2165 }
2166
2167 void set_busy_status(void *frontend, int status)
2168 {
2169     struct gui_data *inst = (struct gui_data *)frontend;
2170     inst->busy_status = status;
2171     update_mouseptr(inst);
2172 }
2173
2174 /*
2175  * set or clear the "raw mouse message" mode
2176  */
2177 void set_raw_mouse_mode(void *frontend, int activate)
2178 {
2179     struct gui_data *inst = (struct gui_data *)frontend;
2180     activate = activate && !conf_get_int(inst->conf, CONF_no_mouse_rep);
2181     send_raw_mouse = activate;
2182     update_mouseptr(inst);
2183 }
2184
2185 void request_resize(void *frontend, int w, int h)
2186 {
2187     struct gui_data *inst = (struct gui_data *)frontend;
2188
2189 #if !GTK_CHECK_VERSION(3,0,0)
2190
2191     int large_x, large_y;
2192     int offset_x, offset_y;
2193     int area_x, area_y;
2194     GtkRequisition inner, outer;
2195
2196     /*
2197      * This is a heinous hack dreamed up by the gnome-terminal
2198      * people to get around a limitation in gtk. The problem is
2199      * that in order to set the size correctly we really need to be
2200      * calling gtk_window_resize - but that needs to know the size
2201      * of the _whole window_, not the drawing area. So what we do
2202      * is to set an artificially huge size request on the drawing
2203      * area, recompute the resulting size request on the window,
2204      * and look at the difference between the two. That gives us
2205      * the x and y offsets we need to translate drawing area size
2206      * into window size for real, and then we call
2207      * gtk_window_resize.
2208      */
2209
2210     /*
2211      * We start by retrieving the current size of the whole window.
2212      * Adding a bit to _that_ will give us a value we can use as a
2213      * bogus size request which guarantees to be bigger than the
2214      * current size of the drawing area.
2215      */
2216     get_window_pixels(inst, &large_x, &large_y);
2217     large_x += 32;
2218     large_y += 32;
2219
2220     gtk_widget_set_size_request(inst->area, large_x, large_y);
2221     gtk_widget_size_request(inst->area, &inner);
2222     gtk_widget_size_request(inst->window, &outer);
2223
2224     offset_x = outer.width - inner.width;
2225     offset_y = outer.height - inner.height;
2226
2227     area_x = inst->font_width * w + 2*inst->window_border;
2228     area_y = inst->font_height * h + 2*inst->window_border;
2229
2230     /*
2231      * Now we must set the size request on the drawing area back to
2232      * something sensible before we commit the real resize. Best
2233      * way to do this, I think, is to set it to what the size is
2234      * really going to end up being.
2235      */
2236     gtk_widget_set_size_request(inst->area, area_x, area_y);
2237 #if GTK_CHECK_VERSION(2,0,0)
2238     gtk_window_resize(GTK_WINDOW(inst->window),
2239                       area_x + offset_x, area_y + offset_y);
2240 #else
2241     gtk_drawing_area_size(GTK_DRAWING_AREA(inst->area), area_x, area_y);
2242     /*
2243      * I can no longer remember what this call to
2244      * gtk_container_dequeue_resize_handler is for. It was
2245      * introduced in r3092 with no comment, and the commit log
2246      * message was uninformative. I'm _guessing_ its purpose is to
2247      * prevent gratuitous resize processing on the window given
2248      * that we're about to resize it anyway, but I have no idea
2249      * why that's so incredibly vital.
2250      * 
2251      * I've tried removing the call, and nothing seems to go
2252      * wrong. I've backtracked to r3092 and tried removing the
2253      * call there, and still nothing goes wrong. So I'm going to
2254      * adopt the working hypothesis that it's superfluous; I won't
2255      * actually remove it from the GTK 1.2 code, but I won't
2256      * attempt to replicate its functionality in the GTK 2 code
2257      * above.
2258      */
2259     gtk_container_dequeue_resize_handler(GTK_CONTAINER(inst->window));
2260     gdk_window_resize(gtk_widget_get_window(inst->window),
2261                       area_x + offset_x, area_y + offset_y);
2262 #endif
2263
2264 #else /* GTK_CHECK_VERSION(3,0,0) */
2265
2266     /*
2267      * In GTK3, we can do this by using gtk_window_resize_to_geometry,
2268      * which uses the fact that we've already set up the main window's
2269      * WM hints to reflect the terminal drawing area's resize
2270      * increment (i.e. character cell) and the fixed amount of stuff
2271      * round the edges.
2272      */
2273     gtk_window_resize_to_geometry(GTK_WINDOW(inst->window), w, h);
2274
2275 #endif
2276
2277 }
2278
2279 static void real_palette_set(struct gui_data *inst, int n, int r, int g, int b)
2280 {
2281     inst->cols[n].red = r * 0x0101;
2282     inst->cols[n].green = g * 0x0101;
2283     inst->cols[n].blue = b * 0x0101;
2284
2285 #if !GTK_CHECK_VERSION(3,0,0)
2286     {
2287         gboolean success[1];
2288         gdk_colormap_free_colors(inst->colmap, inst->cols + n, 1);
2289         gdk_colormap_alloc_colors(inst->colmap, inst->cols + n, 1,
2290                                   FALSE, TRUE, success);
2291         if (!success[0])
2292             g_error("%s: couldn't allocate colour %d (#%02x%02x%02x)\n",
2293                     appname, n, r, g, b);
2294     }
2295 #endif
2296 }
2297
2298 void set_gdk_window_background(GdkWindow *win, const GdkColor *col)
2299 {
2300 #if GTK_CHECK_VERSION(3,0,0)
2301     /* gdk_window_set_background is deprecated; work around its
2302      * absence. */
2303     GdkRGBA rgba;
2304     rgba.red = col->red / 65535.0;
2305     rgba.green = col->green / 65535.0;
2306     rgba.blue = col->blue / 65535.0;
2307     rgba.alpha = 1.0;
2308     gdk_window_set_background_rgba(win, &rgba);
2309 #else
2310     {
2311         /* For GTK1, which doesn't have a 'const' on
2312          * gdk_window_set_background's second parameter type. */
2313         GdkColor col_mutable = *col;
2314         gdk_window_set_background(win, &col_mutable);
2315     }
2316 #endif
2317 }
2318
2319 void set_window_background(struct gui_data *inst)
2320 {
2321     if (inst->area && gtk_widget_get_window(inst->area))
2322         set_gdk_window_background(gtk_widget_get_window(inst->area),
2323                                   &inst->cols[258]);
2324     if (inst->window && gtk_widget_get_window(inst->window))
2325         set_gdk_window_background(gtk_widget_get_window(inst->window),
2326                                   &inst->cols[258]);
2327 }
2328
2329 void palette_set(void *frontend, int n, int r, int g, int b)
2330 {
2331     struct gui_data *inst = (struct gui_data *)frontend;
2332     if (n >= 16)
2333         n += 256 - 16;
2334     if (n >= NALLCOLOURS)
2335         return;
2336     real_palette_set(inst, n, r, g, b);
2337     if (n == 258) {
2338         /* Default Background changed. Ensure space between text area and
2339          * window border is redrawn */
2340         set_window_background(inst);
2341         draw_backing_rect(inst);
2342         gtk_widget_queue_draw(inst->area);
2343     }
2344 }
2345
2346 void palette_reset(void *frontend)
2347 {
2348     struct gui_data *inst = (struct gui_data *)frontend;
2349     /* This maps colour indices in inst->conf to those used in inst->cols. */
2350     static const int ww[] = {
2351         256, 257, 258, 259, 260, 261,
2352         0, 8, 1, 9, 2, 10, 3, 11,
2353         4, 12, 5, 13, 6, 14, 7, 15
2354     };
2355     int i;
2356
2357     assert(lenof(ww) == NCFGCOLOURS);
2358
2359 #if !GTK_CHECK_VERSION(3,0,0)
2360     if (!inst->colmap) {
2361         inst->colmap = gdk_colormap_get_system();
2362     } else {
2363         gdk_colormap_free_colors(inst->colmap, inst->cols, NALLCOLOURS);
2364     }
2365 #endif
2366
2367     for (i = 0; i < NCFGCOLOURS; i++) {
2368         inst->cols[ww[i]].red =
2369             conf_get_int_int(inst->conf, CONF_colours, i*3+0) * 0x0101;
2370         inst->cols[ww[i]].green =
2371             conf_get_int_int(inst->conf, CONF_colours, i*3+1) * 0x0101;
2372         inst->cols[ww[i]].blue = 
2373             conf_get_int_int(inst->conf, CONF_colours, i*3+2) * 0x0101;
2374     }
2375
2376     for (i = 0; i < NEXTCOLOURS; i++) {
2377         if (i < 216) {
2378             int r = i / 36, g = (i / 6) % 6, b = i % 6;
2379             inst->cols[i+16].red = r ? r * 0x2828 + 0x3737 : 0;
2380             inst->cols[i+16].green = g ? g * 0x2828 + 0x3737 : 0;
2381             inst->cols[i+16].blue = b ? b * 0x2828 + 0x3737 : 0;
2382         } else {
2383             int shade = i - 216;
2384             shade = shade * 0x0a0a + 0x0808;
2385             inst->cols[i+16].red = inst->cols[i+16].green =
2386                 inst->cols[i+16].blue = shade;
2387         }
2388     }
2389
2390 #if !GTK_CHECK_VERSION(3,0,0)
2391     {
2392         gboolean success[NALLCOLOURS];
2393         gdk_colormap_alloc_colors(inst->colmap, inst->cols, NALLCOLOURS,
2394                                   FALSE, TRUE, success);
2395         for (i = 0; i < NALLCOLOURS; i++) {
2396             if (!success[i])
2397                 g_error("%s: couldn't allocate colour %d (#%02x%02x%02x)\n",
2398                         appname, i,
2399                         conf_get_int_int(inst->conf, CONF_colours, i*3+0),
2400                         conf_get_int_int(inst->conf, CONF_colours, i*3+1),
2401                         conf_get_int_int(inst->conf, CONF_colours, i*3+2));
2402         }
2403     }
2404 #endif
2405
2406     /* Since Default Background may have changed, ensure that space
2407      * between text area and window border is refreshed. */
2408     set_window_background(inst);
2409     if (inst->area && gtk_widget_get_window(inst->area)) {
2410         draw_backing_rect(inst);
2411         gtk_widget_queue_draw(inst->area);
2412     }
2413 }
2414
2415 #ifdef JUST_USE_GTK_CLIPBOARD_UTF8
2416
2417 /* ----------------------------------------------------------------------
2418  * Clipboard handling, using the high-level GtkClipboard interface in
2419  * as hands-off a way as possible. We write and read the clipboard as
2420  * UTF-8 text, and let GTK deal with converting to any other text
2421  * formats it feels like.
2422  */
2423
2424 void init_clipboard(struct gui_data *inst)
2425 {
2426     inst->clipboard = gtk_clipboard_get_for_display(gdk_display_get_default(),
2427                                                     DEFAULT_CLIPBOARD);
2428 }
2429
2430 /*
2431  * Because calling gtk_clipboard_set_with_data triggers a call to the
2432  * clipboard_clear function from the last time, we need to arrange a
2433  * way to distinguish a real call to clipboard_clear for the _new_
2434  * instance of the clipboard data from the leftover call for the
2435  * outgoing one. We do this by setting the user data field in our
2436  * gtk_clipboard_set_with_data() call, instead of the obvious pointer
2437  * to 'inst', to one of these.
2438  */
2439 struct clipboard_data_instance {
2440     struct gui_data *inst;
2441     char *pasteout_data_utf8;
2442     int pasteout_data_utf8_len;
2443 };
2444
2445 static void clipboard_provide_data(GtkClipboard *clipboard,
2446                                    GtkSelectionData *selection_data,
2447                                    guint info, gpointer data)
2448 {
2449     struct clipboard_data_instance *cdi =
2450         (struct clipboard_data_instance *)data;
2451     struct gui_data *inst = cdi->inst;
2452
2453     if (inst->current_cdi == cdi) {
2454         gtk_selection_data_set_text(selection_data, cdi->pasteout_data_utf8,
2455                                     cdi->pasteout_data_utf8_len);
2456     }
2457 }
2458
2459 static void clipboard_clear(GtkClipboard *clipboard, gpointer data)
2460 {
2461     struct clipboard_data_instance *cdi =
2462         (struct clipboard_data_instance *)data;
2463     struct gui_data *inst = cdi->inst;
2464
2465     if (inst->current_cdi == cdi) {
2466         term_deselect(inst->term);
2467         inst->current_cdi = NULL;
2468     }
2469     sfree(cdi->pasteout_data_utf8);
2470     sfree(cdi);
2471 }
2472
2473 void write_clip(void *frontend, wchar_t *data, int *attr, int len,
2474                 int must_deselect)
2475 {
2476     struct gui_data *inst = (struct gui_data *)frontend;
2477     struct clipboard_data_instance *cdi;
2478
2479     if (inst->direct_to_font) {
2480         /* In this clipboard mode, we just can't paste if we're in
2481          * direct-to-font mode. Fortunately, that shouldn't be
2482          * important, because we'll only use this clipboard handling
2483          * code on systems where that kind of font doesn't exist
2484          * anyway. */
2485         return;
2486     }
2487
2488     cdi = snew(struct clipboard_data_instance);
2489     cdi->inst = inst;
2490     inst->current_cdi = cdi;
2491     cdi->pasteout_data_utf8 = snewn(len*6, char);
2492     {
2493         const wchar_t *tmp = data;
2494         int tmplen = len;
2495         cdi->pasteout_data_utf8_len =
2496             charset_from_unicode(&tmp, &tmplen, cdi->pasteout_data_utf8,
2497                                  len*6, CS_UTF8, NULL, NULL, 0);
2498     }
2499
2500     /*
2501      * It would be nice to just call gtk_clipboard_set_text() in place
2502      * of all of the faffing below. Unfortunately, that won't give me
2503      * access to the clipboard-clear event, which we use to visually
2504      * deselect text in the terminal.
2505      */
2506     {
2507         GtkTargetList *targetlist;
2508         GtkTargetEntry *targettable;
2509         gint n_targets;
2510
2511         targetlist = gtk_target_list_new(NULL, 0);
2512         gtk_target_list_add_text_targets(targetlist, 0);
2513         targettable = gtk_target_table_new_from_list(targetlist, &n_targets);
2514         gtk_clipboard_set_with_data(inst->clipboard, targettable, n_targets,
2515                                     clipboard_provide_data, clipboard_clear,
2516                                     cdi);
2517         gtk_target_table_free(targettable, n_targets);
2518         gtk_target_list_unref(targetlist);
2519     }
2520 }
2521
2522 static void clipboard_text_received(GtkClipboard *clipboard,
2523                                     const gchar *text, gpointer data)
2524 {
2525     struct gui_data *inst = (struct gui_data *)data;
2526     int length;
2527
2528     if (!text)
2529         return;
2530
2531     length = strlen(text);
2532
2533     if (inst->pastein_data)
2534         sfree(inst->pastein_data);
2535
2536     inst->pastein_data = snewn(length, wchar_t);
2537     inst->pastein_data_len = mb_to_wc(CS_UTF8, 0, text, length,
2538                                       inst->pastein_data, length);
2539
2540     term_do_paste(inst->term);
2541 }
2542
2543 void request_paste(void *frontend)
2544 {
2545     struct gui_data *inst = (struct gui_data *)frontend;
2546     gtk_clipboard_request_text(inst->clipboard, clipboard_text_received, inst);
2547 }
2548
2549 #else /* JUST_USE_GTK_CLIPBOARD_UTF8 */
2550
2551 /* ----------------------------------------------------------------------
2552  * Clipboard handling for X, using the low-level gtk_selection_*
2553  * interface, handling conversions to fiddly things like compound text
2554  * ourselves, and storing in X cut buffers too.
2555  *
2556  * This version of the clipboard code has to be kept around for GTK1,
2557  * which doesn't have the higher-level GtkClipboard interface at all.
2558  * And since it works on GTK2 and GTK3 too and has had a good few
2559  * years of shakedown and bug fixing, we might as well keep using it
2560  * where it's applicable.
2561  *
2562  * It's _possible_ that we might be able to replicate all the
2563  * important wrinkles of this code in GtkClipboard. (In particular,
2564  * cut buffers or local analogue look as if they might be accessible
2565  * via gtk_clipboard_set_can_store(), and delivering text in
2566  * non-Unicode formats only in the direct-to-font case ought to be
2567  * possible if we can figure out the right set of things to put in the
2568  * GtkTargetList.) But that work can wait until there's a need for it!
2569  */
2570
2571 /* Store the data in a cut-buffer. */
2572 static void store_cutbuffer(char * ptr, int len)
2573 {
2574 #ifndef NOT_X_WINDOWS
2575     Display *disp = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
2576     /* ICCCM says we must rotate the buffers before storing to buffer 0. */
2577     XRotateBuffers(disp, 1);
2578     XStoreBytes(disp, ptr, len);
2579 #endif
2580 }
2581
2582 /* Retrieve data from a cut-buffer.
2583  * Returned data needs to be freed with XFree().
2584  */
2585 static char *retrieve_cutbuffer(int *nbytes)
2586 {
2587 #ifndef NOT_X_WINDOWS
2588     Display *disp = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
2589     char * ptr;
2590     ptr = XFetchBytes(disp, nbytes);
2591     if (*nbytes <= 0 && ptr != 0) {
2592         XFree(ptr);
2593         ptr = 0;
2594     }
2595     return ptr;
2596 #else
2597     return NULL;
2598 #endif
2599 }
2600
2601 void write_clip(void *frontend, wchar_t *data, int *attr, int len,
2602                 int must_deselect)
2603 {
2604     struct gui_data *inst = (struct gui_data *)frontend;
2605     if (inst->pasteout_data)
2606         sfree(inst->pasteout_data);
2607     if (inst->pasteout_data_ctext)
2608         sfree(inst->pasteout_data_ctext);
2609     if (inst->pasteout_data_utf8)
2610         sfree(inst->pasteout_data_utf8);
2611
2612     /*
2613      * Set up UTF-8 and compound text paste data. This only happens
2614      * if we aren't in direct-to-font mode using the D800 hack.
2615      */
2616     if (!inst->direct_to_font) {
2617         const wchar_t *tmp = data;
2618         int tmplen = len;
2619 #ifndef NOT_X_WINDOWS
2620         XTextProperty tp;
2621         char *list[1];
2622         Display *disp = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
2623 #endif
2624
2625         inst->pasteout_data_utf8 = snewn(len*6, char);
2626         inst->pasteout_data_utf8_len = len*6;
2627         inst->pasteout_data_utf8_len =
2628             charset_from_unicode(&tmp, &tmplen, inst->pasteout_data_utf8,
2629                                  inst->pasteout_data_utf8_len,
2630                                  CS_UTF8, NULL, NULL, 0);
2631         if (inst->pasteout_data_utf8_len == 0) {
2632             sfree(inst->pasteout_data_utf8);
2633             inst->pasteout_data_utf8 = NULL;
2634         } else {
2635             inst->pasteout_data_utf8 =
2636                 sresize(inst->pasteout_data_utf8,
2637                         inst->pasteout_data_utf8_len + 1, char);
2638             inst->pasteout_data_utf8[inst->pasteout_data_utf8_len] = '\0';
2639         }
2640
2641         /*
2642          * Now let Xlib convert our UTF-8 data into compound text.
2643          */
2644 #ifndef NOT_X_WINDOWS
2645         list[0] = inst->pasteout_data_utf8;
2646         if (Xutf8TextListToTextProperty(disp, list, 1,
2647                                         XCompoundTextStyle, &tp) == 0) {
2648             inst->pasteout_data_ctext = snewn(tp.nitems+1, char);
2649             memcpy(inst->pasteout_data_ctext, tp.value, tp.nitems);
2650             inst->pasteout_data_ctext_len = tp.nitems;
2651             XFree(tp.value);
2652         } else
2653 #endif
2654         {
2655             inst->pasteout_data_ctext = NULL;
2656             inst->pasteout_data_ctext_len = 0;
2657         }
2658     } else {
2659         inst->pasteout_data_utf8 = NULL;
2660         inst->pasteout_data_utf8_len = 0;
2661         inst->pasteout_data_ctext = NULL;
2662         inst->pasteout_data_ctext_len = 0;
2663     }
2664
2665     inst->pasteout_data = snewn(len*6, char);
2666     inst->pasteout_data_len = len*6;
2667     inst->pasteout_data_len = wc_to_mb(inst->ucsdata.line_codepage, 0,
2668                                        data, len, inst->pasteout_data,
2669                                        inst->pasteout_data_len,
2670                                        NULL, NULL, NULL);
2671     if (inst->pasteout_data_len == 0) {
2672         sfree(inst->pasteout_data);
2673         inst->pasteout_data = NULL;
2674     } else {
2675         inst->pasteout_data =
2676             sresize(inst->pasteout_data, inst->pasteout_data_len, char);
2677     }
2678
2679     store_cutbuffer(inst->pasteout_data, inst->pasteout_data_len);
2680
2681     if (gtk_selection_owner_set(inst->area, GDK_SELECTION_PRIMARY,
2682                                 inst->input_event_time)) {
2683 #if GTK_CHECK_VERSION(2,0,0)
2684         gtk_selection_clear_targets(inst->area, GDK_SELECTION_PRIMARY);
2685 #endif
2686         gtk_selection_add_target(inst->area, GDK_SELECTION_PRIMARY,
2687                                  GDK_SELECTION_TYPE_STRING, 1);
2688         if (inst->pasteout_data_ctext)
2689             gtk_selection_add_target(inst->area, GDK_SELECTION_PRIMARY,
2690                                      compound_text_atom, 1);
2691         if (inst->pasteout_data_utf8)
2692             gtk_selection_add_target(inst->area, GDK_SELECTION_PRIMARY,
2693                                      utf8_string_atom, 1);
2694     }
2695
2696     if (must_deselect)
2697         term_deselect(inst->term);
2698 }
2699
2700 static void selection_get(GtkWidget *widget, GtkSelectionData *seldata,
2701                           guint info, guint time_stamp, gpointer data)
2702 {
2703     struct gui_data *inst = (struct gui_data *)data;
2704     GdkAtom target = gtk_selection_data_get_target(seldata);
2705     if (target == utf8_string_atom)
2706         gtk_selection_data_set(seldata, target, 8,
2707                                (unsigned char *)inst->pasteout_data_utf8,
2708                                inst->pasteout_data_utf8_len);
2709     else if (target == compound_text_atom)
2710         gtk_selection_data_set(seldata, target, 8,
2711                                (unsigned char *)inst->pasteout_data_ctext,
2712                                inst->pasteout_data_ctext_len);
2713     else
2714         gtk_selection_data_set(seldata, target, 8,
2715                                (unsigned char *)inst->pasteout_data,
2716                                inst->pasteout_data_len);
2717 }
2718
2719 static gint selection_clear(GtkWidget *widget, GdkEventSelection *seldata,
2720                             gpointer data)
2721 {
2722     struct gui_data *inst = (struct gui_data *)data;
2723
2724     term_deselect(inst->term);
2725     if (inst->pasteout_data)
2726         sfree(inst->pasteout_data);
2727     if (inst->pasteout_data_ctext)
2728         sfree(inst->pasteout_data_ctext);
2729     if (inst->pasteout_data_utf8)
2730         sfree(inst->pasteout_data_utf8);
2731     inst->pasteout_data = NULL;
2732     inst->pasteout_data_len = 0;
2733     inst->pasteout_data_ctext = NULL;
2734     inst->pasteout_data_ctext_len = 0;
2735     inst->pasteout_data_utf8 = NULL;
2736     inst->pasteout_data_utf8_len = 0;
2737     return TRUE;
2738 }
2739
2740 void request_paste(void *frontend)
2741 {
2742     struct gui_data *inst = (struct gui_data *)frontend;
2743     /*
2744      * In Unix, pasting is asynchronous: all we can do at the
2745      * moment is to call gtk_selection_convert(), and when the data
2746      * comes back _then_ we can call term_do_paste().
2747      */
2748
2749     if (!inst->direct_to_font) {
2750         /*
2751          * First we attempt to retrieve the selection as a UTF-8
2752          * string (which we will convert to the correct code page
2753          * before sending to the session, of course). If that
2754          * fails, selection_received() will be informed and will
2755          * fall back to an ordinary string.
2756          */
2757         gtk_selection_convert(inst->area, GDK_SELECTION_PRIMARY,
2758                               utf8_string_atom,
2759                               inst->input_event_time);
2760     } else {
2761         /*
2762          * If we're in direct-to-font mode, we disable UTF-8
2763          * pasting, and go straight to ordinary string data.
2764          */
2765         gtk_selection_convert(inst->area, GDK_SELECTION_PRIMARY,
2766                               GDK_SELECTION_TYPE_STRING,
2767                               inst->input_event_time);
2768     }
2769 }
2770
2771 static void selection_received(GtkWidget *widget, GtkSelectionData *seldata,
2772                                guint time, gpointer data)
2773 {
2774     struct gui_data *inst = (struct gui_data *)data;
2775     char *text;
2776     int length;
2777 #ifndef NOT_X_WINDOWS
2778     char **list;
2779     int free_list_required = 0;
2780     int free_required = 0;
2781 #endif
2782     int charset;
2783     GdkAtom seldata_target = gtk_selection_data_get_target(seldata);
2784     GdkAtom seldata_type = gtk_selection_data_get_data_type(seldata);
2785     const guchar *seldata_data = gtk_selection_data_get_data(seldata);
2786     gint seldata_length = gtk_selection_data_get_length(seldata);
2787
2788     if (seldata_target == utf8_string_atom && seldata_length <= 0) {
2789         /*
2790          * Failed to get a UTF-8 selection string. Try compound
2791          * text next.
2792          */
2793         gtk_selection_convert(inst->area, GDK_SELECTION_PRIMARY,
2794                               compound_text_atom,
2795                               inst->input_event_time);
2796         return;
2797     }
2798
2799     if (seldata_target == compound_text_atom && seldata_length <= 0) {
2800         /*
2801          * Failed to get UTF-8 or compound text. Try an ordinary
2802          * string.
2803          */
2804         gtk_selection_convert(inst->area, GDK_SELECTION_PRIMARY,
2805                               GDK_SELECTION_TYPE_STRING,
2806                               inst->input_event_time);
2807         return;
2808     }
2809
2810     /*
2811      * If we have data, but it's not of a type we can deal with,
2812      * we have to ignore the data.
2813      */
2814     if (seldata_length > 0 &&
2815         seldata_type != GDK_SELECTION_TYPE_STRING &&
2816         seldata_type != compound_text_atom &&
2817         seldata_type != utf8_string_atom)
2818         return;
2819
2820     /*
2821      * If we have no data, try looking in a cut buffer.
2822      */
2823     if (seldata_length <= 0) {
2824 #ifndef NOT_X_WINDOWS
2825         text = retrieve_cutbuffer(&length);
2826         if (length == 0)
2827             return;
2828         /* Xterm is rumoured to expect Latin-1, though I havn't checked the
2829          * source, so use that as a de-facto standard. */
2830         charset = CS_ISO8859_1;
2831         free_required = 1;
2832 #else
2833         return;
2834 #endif
2835     } else {
2836         /*
2837          * Convert COMPOUND_TEXT into UTF-8.
2838          */
2839         if (seldata_type == compound_text_atom) {
2840 #ifndef NOT_X_WINDOWS
2841             XTextProperty tp;
2842             int ret, count;
2843             Display *disp = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
2844
2845             tp.value = (unsigned char *)seldata_data;
2846             tp.encoding = (Atom) seldata_type;
2847             tp.format = gtk_selection_data_get_format(seldata);
2848             tp.nitems = seldata_length;
2849             ret = Xutf8TextPropertyToTextList(disp, &tp, &list, &count);
2850             if (ret == 0 && count == 1) {
2851                 text = list[0];
2852                 length = strlen(list[0]);
2853                 charset = CS_UTF8;
2854                 free_list_required = 1;
2855             } else
2856 #endif
2857             {
2858                 /*
2859                  * Compound text failed; fall back to STRING.
2860                  */
2861                 gtk_selection_convert(inst->area, GDK_SELECTION_PRIMARY,
2862                                       GDK_SELECTION_TYPE_STRING,
2863                                       inst->input_event_time);
2864                 return;
2865             }
2866         } else {
2867             text = (char *)seldata_data;
2868             length = seldata_length;
2869             charset = (seldata_type == utf8_string_atom ?
2870                        CS_UTF8 : inst->ucsdata.line_codepage);
2871         }
2872     }
2873
2874     if (inst->pastein_data)
2875         sfree(inst->pastein_data);
2876
2877     inst->pastein_data = snewn(length, wchar_t);
2878     inst->pastein_data_len = length;
2879     inst->pastein_data_len =
2880         mb_to_wc(charset, 0, text, length,
2881                  inst->pastein_data, inst->pastein_data_len);
2882
2883     term_do_paste(inst->term);
2884
2885 #ifndef NOT_X_WINDOWS
2886     if (free_list_required)
2887         XFreeStringList(list);
2888     if (free_required)
2889         XFree(text);
2890 #endif
2891 }
2892
2893 void init_clipboard(struct gui_data *inst)
2894 {
2895 #ifndef NOT_X_WINDOWS
2896     /*
2897      * Ensure that all the cut buffers exist - according to the ICCCM,
2898      * we must do this before we start using cut buffers.
2899      */
2900     unsigned char empty[] = "";
2901     Display *disp = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
2902     XChangeProperty(disp, GDK_ROOT_WINDOW(),
2903                     XA_CUT_BUFFER0, XA_STRING, 8, PropModeAppend, empty, 0);
2904     XChangeProperty(disp, GDK_ROOT_WINDOW(),
2905                     XA_CUT_BUFFER1, XA_STRING, 8, PropModeAppend, empty, 0);
2906     XChangeProperty(disp, GDK_ROOT_WINDOW(),
2907                     XA_CUT_BUFFER2, XA_STRING, 8, PropModeAppend, empty, 0);
2908     XChangeProperty(disp, GDK_ROOT_WINDOW(),
2909                     XA_CUT_BUFFER3, XA_STRING, 8, PropModeAppend, empty, 0);
2910     XChangeProperty(disp, GDK_ROOT_WINDOW(),
2911                     XA_CUT_BUFFER4, XA_STRING, 8, PropModeAppend, empty, 0);
2912     XChangeProperty(disp, GDK_ROOT_WINDOW(),
2913                     XA_CUT_BUFFER5, XA_STRING, 8, PropModeAppend, empty, 0);
2914     XChangeProperty(disp, GDK_ROOT_WINDOW(),
2915                     XA_CUT_BUFFER6, XA_STRING, 8, PropModeAppend, empty, 0);
2916     XChangeProperty(disp, GDK_ROOT_WINDOW(),
2917                     XA_CUT_BUFFER7, XA_STRING, 8, PropModeAppend, empty, 0);
2918 #endif
2919
2920     g_signal_connect(G_OBJECT(inst->area), "selection_received",
2921                      G_CALLBACK(selection_received), inst);
2922     g_signal_connect(G_OBJECT(inst->area), "selection_get",
2923                      G_CALLBACK(selection_get), inst);
2924     g_signal_connect(G_OBJECT(inst->area), "selection_clear_event",
2925                      G_CALLBACK(selection_clear), inst);
2926 }
2927
2928 /*
2929  * End of selection/clipboard handling.
2930  * ----------------------------------------------------------------------
2931  */
2932
2933 #endif /* JUST_USE_GTK_CLIPBOARD_UTF8 */
2934
2935 void get_clip(void *frontend, wchar_t ** p, int *len)
2936 {
2937     struct gui_data *inst = (struct gui_data *)frontend;
2938
2939     if (p) {
2940         *p = inst->pastein_data;
2941         *len = inst->pastein_data_len;
2942     }
2943 }
2944
2945 static void set_window_titles(struct gui_data *inst)
2946 {
2947     /*
2948      * We must always call set_icon_name after calling set_title,
2949      * since set_title will write both names. Irritating, but such
2950      * is life.
2951      */
2952     gtk_window_set_title(GTK_WINDOW(inst->window), inst->wintitle);
2953     if (!conf_get_int(inst->conf, CONF_win_name_always))
2954         gdk_window_set_icon_name(gtk_widget_get_window(inst->window),
2955                                  inst->icontitle);
2956 }
2957
2958 void set_title(void *frontend, char *title)
2959 {
2960     struct gui_data *inst = (struct gui_data *)frontend;
2961     sfree(inst->wintitle);
2962     inst->wintitle = dupstr(title);
2963     set_window_titles(inst);
2964 }
2965
2966 void set_icon(void *frontend, char *title)
2967 {
2968     struct gui_data *inst = (struct gui_data *)frontend;
2969     sfree(inst->icontitle);
2970     inst->icontitle = dupstr(title);
2971     set_window_titles(inst);
2972 }
2973
2974 void set_title_and_icon(void *frontend, char *title, char *icon)
2975 {
2976     struct gui_data *inst = (struct gui_data *)frontend;
2977     sfree(inst->wintitle);
2978     inst->wintitle = dupstr(title);
2979     sfree(inst->icontitle);
2980     inst->icontitle = dupstr(icon);
2981     set_window_titles(inst);
2982 }
2983
2984 void set_sbar(void *frontend, int total, int start, int page)
2985 {
2986     struct gui_data *inst = (struct gui_data *)frontend;
2987     if (!conf_get_int(inst->conf, CONF_scrollbar))
2988         return;
2989     gtk_adjustment_set_lower(inst->sbar_adjust, 0);
2990     gtk_adjustment_set_upper(inst->sbar_adjust, total);
2991     gtk_adjustment_set_value(inst->sbar_adjust, start);
2992     gtk_adjustment_set_page_size(inst->sbar_adjust, page);
2993     gtk_adjustment_set_step_increment(inst->sbar_adjust, 1);
2994     gtk_adjustment_set_page_increment(inst->sbar_adjust, page/2);
2995     inst->ignore_sbar = TRUE;
2996     gtk_adjustment_changed(inst->sbar_adjust);
2997     inst->ignore_sbar = FALSE;
2998 }
2999
3000 void scrollbar_moved(GtkAdjustment *adj, gpointer data)
3001 {
3002     struct gui_data *inst = (struct gui_data *)data;
3003
3004     if (!conf_get_int(inst->conf, CONF_scrollbar))
3005         return;
3006     if (!inst->ignore_sbar)
3007         term_scroll(inst->term, 1, (int)gtk_adjustment_get_value(adj));
3008 }
3009
3010 void sys_cursor(void *frontend, int x, int y)
3011 {
3012     /*
3013      * This is meaningless under X.
3014      */
3015 }
3016
3017 /*
3018  * This is still called when mode==BELL_VISUAL, even though the
3019  * visual bell is handled entirely within terminal.c, because we
3020  * may want to perform additional actions on any kind of bell (for
3021  * example, taskbar flashing in Windows).
3022  */
3023 void do_beep(void *frontend, int mode)
3024 {
3025     if (mode == BELL_DEFAULT)
3026         gdk_beep();
3027 }
3028
3029 int char_width(Context ctx, int uc)
3030 {
3031     /*
3032      * Under X, any fixed-width font really _is_ fixed-width.
3033      * Double-width characters will be dealt with using a separate
3034      * font. For the moment we can simply return 1.
3035      * 
3036      * FIXME: but is that also true of Pango?
3037      */
3038     return 1;
3039 }
3040
3041 Context get_ctx(void *frontend)
3042 {
3043     struct gui_data *inst = (struct gui_data *)frontend;
3044     struct draw_ctx *dctx;
3045
3046     if (!gtk_widget_get_window(inst->area))
3047         return NULL;
3048
3049     dctx = snew(struct draw_ctx);
3050     dctx->inst = inst;
3051     dctx->uctx.type = inst->drawtype;
3052 #ifdef DRAW_TEXT_GDK
3053     if (dctx->uctx.type == DRAWTYPE_GDK) {
3054         /* If we're doing GDK-based drawing, then we also expect
3055          * inst->pixmap to exist. */
3056         dctx->uctx.u.gdk.target = inst->pixmap;
3057         dctx->uctx.u.gdk.gc = gdk_gc_new(gtk_widget_get_window(inst->area));
3058     }
3059 #endif
3060 #ifdef DRAW_TEXT_CAIRO
3061     if (dctx->uctx.type == DRAWTYPE_CAIRO) {
3062         dctx->uctx.u.cairo.widget = GTK_WIDGET(inst->area);
3063         /* If we're doing Cairo drawing, we expect inst->surface to
3064          * exist, and we draw to that first, regardless of whether we
3065          * subsequently copy the results to inst->pixmap. */
3066         dctx->uctx.u.cairo.cr = cairo_create(inst->surface);
3067         cairo_setup_dctx(dctx);
3068     }
3069 #endif
3070     return dctx;
3071 }
3072
3073 void free_ctx(Context ctx)
3074 {
3075     struct draw_ctx *dctx = (struct draw_ctx *)ctx;
3076     /* struct gui_data *inst = dctx->inst; */
3077 #ifdef DRAW_TEXT_GDK
3078     if (dctx->uctx.type == DRAWTYPE_GDK) {
3079         gdk_gc_unref(dctx->uctx.u.gdk.gc);
3080     }
3081 #endif
3082 #ifdef DRAW_TEXT_CAIRO
3083     if (dctx->uctx.type == DRAWTYPE_CAIRO) {
3084         cairo_destroy(dctx->uctx.u.cairo.cr);
3085     }
3086 #endif
3087     sfree(dctx);
3088 }
3089
3090
3091 static void draw_update(struct draw_ctx *dctx, int x, int y, int w, int h)
3092 {
3093 #if defined DRAW_TEXT_CAIRO && !defined NO_BACKING_PIXMAPS
3094     if (dctx->uctx.type == DRAWTYPE_CAIRO) {
3095         /*
3096          * If inst->surface and inst->pixmap both exist, then we've
3097          * just drawn new content to the former which we must copy to
3098          * the latter.
3099          */
3100         cairo_t *cr = gdk_cairo_create(dctx->inst->pixmap);
3101         cairo_set_source_surface(cr, dctx->inst->surface, 0, 0);
3102         cairo_rectangle(cr, x, y, w, h);
3103         cairo_fill(cr);
3104         cairo_destroy(cr);
3105     }
3106 #endif
3107
3108     /*
3109      * Now we just queue a window redraw, which will cause
3110      * inst->surface or inst->pixmap (whichever is appropriate for our
3111      * compile mode) to be copied to the real window when we receive
3112      * the resulting "expose" or "draw" event.
3113      *
3114      * Amazingly, this one API call is actually valid in all versions
3115      * of GTK :-)
3116      */
3117     gtk_widget_queue_draw_area(dctx->inst->area, x, y, w, h);
3118 }
3119
3120 static void draw_set_colour(struct draw_ctx *dctx, int col)
3121 {
3122 #ifdef DRAW_TEXT_GDK
3123     if (dctx->uctx.type == DRAWTYPE_GDK) {
3124         gdk_gc_set_foreground(dctx->uctx.u.gdk.gc, &dctx->inst->cols[col]);
3125     }
3126 #endif
3127 #ifdef DRAW_TEXT_CAIRO
3128     if (dctx->uctx.type == DRAWTYPE_CAIRO) {
3129         cairo_set_source_rgb(dctx->uctx.u.cairo.cr,
3130                              dctx->inst->cols[col].red / 65535.0,
3131                              dctx->inst->cols[col].green / 65535.0,
3132                              dctx->inst->cols[col].blue / 65535.0);
3133     }
3134 #endif
3135 }
3136
3137 static void draw_rectangle(struct draw_ctx *dctx, int filled,
3138                            int x, int y, int w, int h)
3139 {
3140 #ifdef DRAW_TEXT_GDK
3141     if (dctx->uctx.type == DRAWTYPE_GDK) {
3142         gdk_draw_rectangle(dctx->uctx.u.gdk.target, dctx->uctx.u.gdk.gc,
3143                            filled, x, y, w, h);
3144     }
3145 #endif
3146 #ifdef DRAW_TEXT_CAIRO
3147     if (dctx->uctx.type == DRAWTYPE_CAIRO) {
3148         cairo_new_path(dctx->uctx.u.cairo.cr);
3149         if (filled) {
3150             cairo_rectangle(dctx->uctx.u.cairo.cr, x, y, w, h);
3151             cairo_fill(dctx->uctx.u.cairo.cr);
3152         } else {
3153             cairo_rectangle(dctx->uctx.u.cairo.cr,
3154                             x + 0.5, y + 0.5, w, h);
3155             cairo_close_path(dctx->uctx.u.cairo.cr);
3156             cairo_stroke(dctx->uctx.u.cairo.cr);
3157         }
3158     }
3159 #endif
3160 }
3161
3162 static void draw_clip(struct draw_ctx *dctx, int x, int y, int w, int h)
3163 {
3164 #ifdef DRAW_TEXT_GDK
3165     if (dctx->uctx.type == DRAWTYPE_GDK) {
3166         GdkRectangle r;
3167
3168         r.x = x;
3169         r.y = y;
3170         r.width = w;
3171         r.height = h;
3172
3173         gdk_gc_set_clip_rectangle(dctx->uctx.u.gdk.gc, &r);
3174     }
3175 #endif
3176 #ifdef DRAW_TEXT_CAIRO
3177     if (dctx->uctx.type == DRAWTYPE_CAIRO) {
3178         cairo_reset_clip(dctx->uctx.u.cairo.cr);
3179         cairo_new_path(dctx->uctx.u.cairo.cr);
3180         cairo_rectangle(dctx->uctx.u.cairo.cr, x, y, w, h);
3181         cairo_clip(dctx->uctx.u.cairo.cr);
3182     }
3183 #endif
3184 }
3185
3186 static void draw_point(struct draw_ctx *dctx, int x, int y)
3187 {
3188 #ifdef DRAW_TEXT_GDK
3189     if (dctx->uctx.type == DRAWTYPE_GDK) {
3190         gdk_draw_point(dctx->uctx.u.gdk.target, dctx->uctx.u.gdk.gc, x, y);
3191     }
3192 #endif
3193 #ifdef DRAW_TEXT_CAIRO
3194     if (dctx->uctx.type == DRAWTYPE_CAIRO) {
3195         cairo_new_path(dctx->uctx.u.cairo.cr);
3196         cairo_rectangle(dctx->uctx.u.cairo.cr, x, y, 1, 1);
3197         cairo_fill(dctx->uctx.u.cairo.cr);
3198     }
3199 #endif
3200 }
3201
3202 static void draw_line(struct draw_ctx *dctx, int x0, int y0, int x1, int y1)
3203 {
3204 #ifdef DRAW_TEXT_GDK
3205     if (dctx->uctx.type == DRAWTYPE_GDK) {
3206         gdk_draw_line(dctx->uctx.u.gdk.target, dctx->uctx.u.gdk.gc,
3207                       x0, y0, x1, y1);
3208     }
3209 #endif
3210 #ifdef DRAW_TEXT_CAIRO
3211     if (dctx->uctx.type == DRAWTYPE_CAIRO) {
3212         cairo_new_path(dctx->uctx.u.cairo.cr);
3213         cairo_move_to(dctx->uctx.u.cairo.cr, x0 + 0.5, y0 + 0.5);
3214         cairo_line_to(dctx->uctx.u.cairo.cr, x1 + 0.5, y1 + 0.5);
3215         cairo_stroke(dctx->uctx.u.cairo.cr);
3216     }
3217 #endif
3218 }
3219
3220 static void draw_stretch_before(struct draw_ctx *dctx, int x, int y,
3221                                 int w, int wdouble,
3222                                 int h, int hdouble, int hbothalf)
3223 {
3224 #ifdef DRAW_TEXT_CAIRO
3225     if (dctx->uctx.type == DRAWTYPE_CAIRO) {
3226         cairo_matrix_t matrix;
3227
3228         matrix.xy = 0;
3229         matrix.yx = 0;
3230
3231         if (wdouble) {
3232             matrix.xx = 2;
3233             matrix.x0 = -x;
3234         } else {
3235             matrix.xx = 1;
3236             matrix.x0 = 0;
3237         }
3238
3239         if (hdouble) {
3240             matrix.yy = 2;
3241             if (hbothalf) {
3242                 matrix.y0 = -(y+h);
3243             } else {
3244                 matrix.y0 = -y;
3245             }
3246         } else {
3247             matrix.yy = 1;
3248             matrix.y0 = 0;
3249         }
3250         cairo_transform(dctx->uctx.u.cairo.cr, &matrix);
3251     }
3252 #endif
3253 }
3254
3255 static void draw_stretch_after(struct draw_ctx *dctx, int x, int y,
3256                                int w, int wdouble,
3257                                int h, int hdouble, int hbothalf)
3258 {
3259 #ifdef DRAW_TEXT_GDK
3260 #ifndef NO_BACKING_PIXMAPS
3261     if (dctx->uctx.type == DRAWTYPE_GDK) {
3262         /*
3263          * I can't find any plausible StretchBlt equivalent in the X
3264          * server, so I'm going to do this the slow and painful way.
3265          * This will involve repeated calls to gdk_draw_pixmap() to
3266          * stretch the text horizontally. It's O(N^2) in time and O(N)
3267          * in network bandwidth, but you try thinking of a better way.
3268          * :-(
3269          */
3270         int i;
3271         if (wdouble) {
3272             for (i = 0; i < w; i++) {
3273                 gdk_draw_pixmap(dctx->uctx.u.gdk.target,
3274                                 dctx->uctx.u.gdk.gc,
3275                                 dctx->uctx.u.gdk.target,
3276                                 x + 2*i, y,
3277                                 x + 2*i+1, y,
3278                                 w - i, h);
3279             }
3280             w *= 2;
3281         }
3282
3283         if (hdouble) {
3284             int dt, db;
3285             /* Now stretch vertically, in the same way. */
3286             if (hbothalf)
3287                 dt = 0, db = 1;
3288             else
3289                 dt = 1, db = 0;
3290             for (i = 0; i < h; i += 2) {
3291                 gdk_draw_pixmap(dctx->uctx.u.gdk.target,
3292                                 dctx->uctx.u.gdk.gc,
3293                                 dctx->uctx.u.gdk.target,
3294                                 x, y + dt*i + db,
3295                                 x, y + dt*(i+1),
3296                                 w, h-i-1);
3297             }
3298         }
3299     }
3300 #else
3301 #error No way to implement stretching in GDK without a reliable backing pixmap
3302 #endif
3303 #endif /* DRAW_TEXT_GDK */
3304 #ifdef DRAW_TEXT_CAIRO
3305     if (dctx->uctx.type == DRAWTYPE_CAIRO) {
3306         cairo_set_matrix(dctx->uctx.u.cairo.cr,
3307                          &dctx->uctx.u.cairo.origmatrix);
3308     }
3309 #endif
3310 }
3311
3312 static void draw_backing_rect(struct gui_data *inst)
3313 {
3314     struct draw_ctx *dctx = get_ctx(inst);
3315     int w = inst->width * inst->font_width + 2*inst->window_border;
3316     int h = inst->height * inst->font_height + 2*inst->window_border;
3317     draw_set_colour(dctx, 258);
3318     draw_rectangle(dctx, 1, 0, 0, w, h);
3319     draw_update(dctx, 0, 0, w, h);
3320     free_ctx(dctx);
3321 }
3322
3323 /*
3324  * Draw a line of text in the window, at given character
3325  * coordinates, in given attributes.
3326  *
3327  * We are allowed to fiddle with the contents of `text'.
3328  */
3329 void do_text_internal(Context ctx, int x, int y, wchar_t *text, int len,
3330                       unsigned long attr, int lattr)
3331 {
3332     struct draw_ctx *dctx = (struct draw_ctx *)ctx;
3333     struct gui_data *inst = dctx->inst;
3334     int ncombining, combining;
3335     int nfg, nbg, t, fontid, shadow, rlen, widefactor, bold;
3336     int monochrome =
3337         gdk_visual_get_depth(gtk_widget_get_visual(inst->area)) == 1;
3338
3339     if (attr & TATTR_COMBINING) {
3340         ncombining = len;
3341         len = 1;
3342     } else
3343         ncombining = 1;
3344
3345     nfg = ((monochrome ? ATTR_DEFFG : (attr & ATTR_FGMASK)) >> ATTR_FGSHIFT);
3346     nbg = ((monochrome ? ATTR_DEFBG : (attr & ATTR_BGMASK)) >> ATTR_BGSHIFT);
3347     if (!!(attr & ATTR_REVERSE) ^ (monochrome && (attr & TATTR_ACTCURS))) {
3348         t = nfg;
3349         nfg = nbg;
3350         nbg = t;
3351     }
3352     if ((inst->bold_style & 2) && (attr & ATTR_BOLD)) {
3353         if (nfg < 16) nfg |= 8;
3354         else if (nfg >= 256) nfg |= 1;
3355     }
3356     if ((inst->bold_style & 2) && (attr & ATTR_BLINK)) {
3357         if (nbg < 16) nbg |= 8;
3358         else if (nbg >= 256) nbg |= 1;
3359     }
3360     if ((attr & TATTR_ACTCURS) && !monochrome) {
3361         nfg = 260;
3362         nbg = 261;
3363     }
3364
3365     fontid = shadow = 0;
3366
3367     if (attr & ATTR_WIDE) {
3368         widefactor = 2;
3369         fontid |= 2;
3370     } else {
3371         widefactor = 1;
3372     }
3373
3374     if ((attr & ATTR_BOLD) && (inst->bold_style & 1)) {
3375         bold = 1;
3376         fontid |= 1;
3377     } else {
3378         bold = 0;
3379     }
3380
3381     if (!inst->fonts[fontid]) {
3382         int i;
3383         /*
3384          * Fall back through font ids with subsets of this one's
3385          * set bits, in order.
3386          */
3387         for (i = fontid; i-- > 0 ;) {
3388             if (i & ~fontid)
3389                 continue;              /* some other bit is set */
3390             if (inst->fonts[i]) {
3391                 fontid = i;
3392                 break;
3393             }
3394         }
3395         assert(inst->fonts[fontid]);   /* we should at least have hit zero */
3396     }
3397
3398     if ((lattr & LATTR_MODE) != LATTR_NORM) {
3399         x *= 2;
3400         if (x >= inst->term->cols)
3401             return;
3402         if (x + len*2*widefactor > inst->term->cols)
3403             len = (inst->term->cols-x)/2/widefactor;/* trim to LH half */
3404         rlen = len * 2;
3405     } else
3406         rlen = len;
3407
3408     draw_clip(dctx,
3409               x*inst->font_width+inst->window_border,
3410               y*inst->font_height+inst->window_border,
3411               rlen*widefactor*inst->font_width,
3412               inst->font_height);
3413
3414     if ((lattr & LATTR_MODE) != LATTR_NORM) {
3415         draw_stretch_before(dctx,
3416                             x*inst->font_width+inst->window_border,
3417                             y*inst->font_height+inst->window_border,
3418                             rlen*widefactor*inst->font_width, TRUE,
3419                             inst->font_height,
3420                             ((lattr & LATTR_MODE) != LATTR_WIDE),
3421                             ((lattr & LATTR_MODE) == LATTR_BOT));
3422     }
3423
3424     draw_set_colour(dctx, nbg);
3425     draw_rectangle(dctx, TRUE,
3426                    x*inst->font_width+inst->window_border,
3427                    y*inst->font_height+inst->window_border,
3428                    rlen*widefactor*inst->font_width, inst->font_height);
3429
3430     draw_set_colour(dctx, nfg);
3431     for (combining = 0; combining < ncombining; combining++) {
3432         unifont_draw_text(&dctx->uctx, inst->fonts[fontid],
3433                           x*inst->font_width+inst->window_border,
3434                           y*inst->font_height+inst->window_border+inst->fonts[0]->ascent,
3435                           text + combining, len, widefactor > 1,
3436                           bold, inst->font_width);
3437     }
3438
3439     if (attr & ATTR_UNDER) {
3440         int uheight = inst->fonts[0]->ascent + 1;
3441         if (uheight >= inst->font_height)
3442             uheight = inst->font_height - 1;
3443         draw_line(dctx, x*inst->font_width+inst->window_border,
3444                   y*inst->font_height + uheight + inst->window_border,
3445                   (x+len)*widefactor*inst->font_width-1+inst->window_border,
3446                   y*inst->font_height + uheight + inst->window_border);
3447     }
3448
3449     if ((lattr & LATTR_MODE) != LATTR_NORM) {
3450         draw_stretch_after(dctx,
3451                            x*inst->font_width+inst->window_border,
3452                            y*inst->font_height+inst->window_border,
3453                            rlen*widefactor*inst->font_width, TRUE,
3454                            inst->font_height,
3455                            ((lattr & LATTR_MODE) != LATTR_WIDE),
3456                            ((lattr & LATTR_MODE) == LATTR_BOT));
3457     }
3458 }
3459
3460 void do_text(Context ctx, int x, int y, wchar_t *text, int len,
3461              unsigned long attr, int lattr)
3462 {
3463     struct draw_ctx *dctx = (struct draw_ctx *)ctx;
3464     struct gui_data *inst = dctx->inst;
3465     int widefactor;
3466
3467     do_text_internal(ctx, x, y, text, len, attr, lattr);
3468
3469     if (attr & ATTR_WIDE) {
3470         widefactor = 2;
3471     } else {
3472         widefactor = 1;
3473     }
3474
3475     if ((lattr & LATTR_MODE) != LATTR_NORM) {
3476         x *= 2;
3477         if (x >= inst->term->cols)
3478             return;
3479         if (x + len*2*widefactor > inst->term->cols)
3480             len = (inst->term->cols-x)/2/widefactor;/* trim to LH half */
3481         len *= 2;
3482     }
3483
3484     draw_update(dctx,
3485                 x*inst->font_width+inst->window_border,
3486                 y*inst->font_height+inst->window_border,
3487                 len*widefactor*inst->font_width, inst->font_height);
3488 }
3489
3490 void do_cursor(Context ctx, int x, int y, wchar_t *text, int len,
3491                unsigned long attr, int lattr)
3492 {
3493     struct draw_ctx *dctx = (struct draw_ctx *)ctx;
3494     struct gui_data *inst = dctx->inst;
3495
3496     int active, passive, widefactor;
3497
3498     if (attr & TATTR_PASCURS) {
3499         attr &= ~TATTR_PASCURS;
3500         passive = 1;
3501     } else
3502         passive = 0;
3503     if ((attr & TATTR_ACTCURS) && inst->cursor_type != 0) {
3504         attr &= ~TATTR_ACTCURS;
3505         active = 1;
3506     } else
3507         active = 0;
3508     do_text_internal(ctx, x, y, text, len, attr, lattr);
3509
3510     if (attr & TATTR_COMBINING)
3511         len = 1;
3512
3513     if (attr & ATTR_WIDE) {
3514         widefactor = 2;
3515     } else {
3516         widefactor = 1;
3517     }
3518
3519     if ((lattr & LATTR_MODE) != LATTR_NORM) {
3520         x *= 2;
3521         if (x >= inst->term->cols)
3522             return;
3523         if (x + len*2*widefactor > inst->term->cols)
3524             len = (inst->term->cols-x)/2/widefactor;/* trim to LH half */
3525         len *= 2;
3526     }
3527
3528     if (inst->cursor_type == 0) {
3529         /*
3530          * An active block cursor will already have been done by
3531          * the above do_text call, so we only need to do anything
3532          * if it's passive.
3533          */
3534         if (passive) {
3535             draw_set_colour(dctx, 261);
3536             draw_rectangle(dctx, FALSE,
3537                            x*inst->font_width+inst->window_border,
3538                            y*inst->font_height+inst->window_border,
3539                            len*widefactor*inst->font_width-1,
3540                            inst->font_height-1);
3541         }
3542     } else {
3543         int uheight;
3544         int startx, starty, dx, dy, length, i;
3545
3546         int char_width;
3547
3548         if ((attr & ATTR_WIDE) || (lattr & LATTR_MODE) != LATTR_NORM)
3549             char_width = 2*inst->font_width;
3550         else
3551             char_width = inst->font_width;
3552
3553         if (inst->cursor_type == 1) {
3554             uheight = inst->fonts[0]->ascent + 1;
3555             if (uheight >= inst->font_height)
3556                 uheight = inst->font_height - 1;
3557
3558             startx = x * inst->font_width + inst->window_border;
3559             starty = y * inst->font_height + inst->window_border + uheight;
3560             dx = 1;
3561             dy = 0;
3562             length = len * widefactor * char_width;
3563         } else {
3564             int xadjust = 0;
3565             if (attr & TATTR_RIGHTCURS)
3566                 xadjust = char_width - 1;
3567             startx = x * inst->font_width + inst->window_border + xadjust;
3568             starty = y * inst->font_height + inst->window_border;
3569             dx = 0;
3570             dy = 1;
3571             length = inst->font_height;
3572         }
3573
3574         draw_set_colour(dctx, 261);
3575         if (passive) {
3576             for (i = 0; i < length; i++) {
3577                 if (i % 2 == 0) {
3578                     draw_point(dctx, startx, starty);
3579                 }
3580                 startx += dx;
3581                 starty += dy;
3582             }
3583         } else if (active) {
3584             draw_line(dctx, startx, starty,
3585                       startx + (length-1) * dx, starty + (length-1) * dy);
3586         } /* else no cursor (e.g., blinked off) */
3587     }
3588
3589     draw_update(dctx,
3590                 x*inst->font_width+inst->window_border,
3591                 y*inst->font_height+inst->window_border,
3592                 len*widefactor*inst->font_width, inst->font_height);
3593
3594 #if GTK_CHECK_VERSION(2,0,0)
3595     {
3596         GdkRectangle cursorrect;
3597         cursorrect.x = x*inst->font_width+inst->window_border;
3598         cursorrect.y = y*inst->font_height+inst->window_border;
3599         cursorrect.width = len*widefactor*inst->font_width;
3600         cursorrect.height = inst->font_height;
3601         gtk_im_context_set_cursor_location(inst->imc, &cursorrect);
3602     }
3603 #endif
3604 }
3605
3606 GdkCursor *make_mouse_ptr(struct gui_data *inst, int cursor_val)
3607 {
3608     if (cursor_val == -1) {
3609 #if GTK_CHECK_VERSION(2,16,0)
3610         cursor_val = GDK_BLANK_CURSOR;
3611 #else
3612         /*
3613          * Work around absence of GDK_BLANK_CURSOR by inventing a
3614          * blank pixmap.
3615          */
3616         GdkCursor *ret;
3617         GdkColor bg = { 0, 0, 0, 0 };
3618         GdkPixmap *pm = gdk_pixmap_new(NULL, 1, 1, 1);
3619         GdkGC *gc = gdk_gc_new(pm);
3620         gdk_gc_set_foreground(gc, &bg);
3621         gdk_draw_rectangle(pm, gc, 1, 0, 0, 1, 1);
3622         gdk_gc_unref(gc);
3623         ret = gdk_cursor_new_from_pixmap(pm, pm, &bg, &bg, 1, 1);
3624         gdk_pixmap_unref(pm);
3625         return ret;
3626 #endif
3627     }
3628
3629     return gdk_cursor_new(cursor_val);
3630 }
3631
3632 void modalfatalbox(const char *p, ...)
3633 {
3634     va_list ap;
3635     fprintf(stderr, "FATAL ERROR: ");
3636     va_start(ap, p);
3637     vfprintf(stderr, p, ap);
3638     va_end(ap);
3639     fputc('\n', stderr);
3640     exit(1);
3641 }
3642
3643 void cmdline_error(const char *p, ...)
3644 {
3645     va_list ap;
3646     fprintf(stderr, "%s: ", appname);
3647     va_start(ap, p);
3648     vfprintf(stderr, p, ap);
3649     va_end(ap);
3650     fputc('\n', stderr);
3651     exit(1);
3652 }
3653
3654 const char *get_x_display(void *frontend)
3655 {
3656     return gdk_get_display();
3657 }
3658
3659 #ifndef NOT_X_WINDOWS
3660 long get_windowid(void *frontend)
3661 {
3662     struct gui_data *inst = (struct gui_data *)frontend;
3663     return (long)GDK_WINDOW_XID(gtk_widget_get_window(inst->area));
3664 }
3665 #endif
3666
3667 static void help(FILE *fp) {
3668     if(fprintf(fp,
3669 "pterm option summary:\n"
3670 "\n"
3671 "  --display DISPLAY         Specify X display to use (note '--')\n"
3672 "  -name PREFIX              Prefix when looking up resources (default: pterm)\n"
3673 "  -fn FONT                  Normal text font\n"
3674 "  -fb FONT                  Bold text font\n"
3675 "  -geometry GEOMETRY        Position and size of window (size in characters)\n"
3676 "  -sl LINES                 Number of lines of scrollback\n"
3677 "  -fg COLOUR, -bg COLOUR    Foreground/background colour\n"
3678 "  -bfg COLOUR, -bbg COLOUR  Foreground/background bold colour\n"
3679 "  -cfg COLOUR, -bfg COLOUR  Foreground/background cursor colour\n"
3680 "  -T TITLE                  Window title\n"
3681 "  -ut, +ut                  Do(default) or do not update utmp\n"
3682 "  -ls, +ls                  Do(default) or do not make shell a login shell\n"
3683 "  -sb, +sb                  Do(default) or do not display a scrollbar\n"
3684 "  -log PATH                 Log all output to a file\n"
3685 "  -nethack                  Map numeric keypad to hjklyubn direction keys\n"
3686 "  -xrm RESOURCE-STRING      Set an X resource\n"
3687 "  -e COMMAND [ARGS...]      Execute command (consumes all remaining args)\n"
3688          ) < 0 || fflush(fp) < 0) {
3689         perror("output error");
3690         exit(1);
3691     }
3692 }
3693
3694 static void version(FILE *fp) {
3695     if(fprintf(fp, "%s: %s\n", appname, ver) < 0 || fflush(fp) < 0) {
3696         perror("output error");
3697         exit(1);
3698     }
3699 }
3700
3701 int do_cmdline(int argc, char **argv, int do_everything, int *allow_launch,
3702                struct gui_data *inst, Conf *conf)
3703 {
3704     int err = 0;
3705     char *val;
3706
3707     /*
3708      * Macros to make argument handling easier. Note that because
3709      * they need to call `continue', they cannot be contained in
3710      * the usual do {...} while (0) wrapper to make them
3711      * syntactically single statements; hence it is not legal to
3712      * use one of these macros as an unbraced statement between
3713      * `if' and `else'.
3714      */
3715 #define EXPECTS_ARG { \
3716     if (--argc <= 0) { \
3717         err = 1; \
3718         fprintf(stderr, "%s: %s expects an argument\n", appname, p); \
3719         continue; \
3720     } else \
3721         val = *++argv; \
3722 }
3723 #define SECOND_PASS_ONLY { if (!do_everything) continue; }
3724
3725     while (--argc > 0) {
3726         const char *p = *++argv;
3727         int ret;
3728
3729         /*
3730          * Shameless cheating. Debian requires all X terminal
3731          * emulators to support `-T title'; but
3732          * cmdline_process_param will eat -T (it means no-pty) and
3733          * complain that pterm doesn't support it. So, in pterm
3734          * only, we convert -T into -title.
3735          */
3736         if ((cmdline_tooltype & TOOLTYPE_NONNETWORK) &&
3737             !strcmp(p, "-T"))
3738             p = "-title";
3739
3740         ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
3741                                     do_everything ? 1 : -1, conf);
3742
3743         if (ret == -2) {
3744             cmdline_error("option \"%s\" requires an argument", p);
3745         } else if (ret == 2) {
3746             --argc, ++argv;            /* skip next argument */
3747             continue;
3748         } else if (ret == 1) {
3749             continue;
3750         }
3751
3752         if (!strcmp(p, "-fn") || !strcmp(p, "-font")) {
3753             FontSpec *fs;
3754             EXPECTS_ARG;
3755             SECOND_PASS_ONLY;
3756             fs = fontspec_new(val);
3757             conf_set_fontspec(conf, CONF_font, fs);
3758             fontspec_free(fs);
3759
3760         } else if (!strcmp(p, "-fb")) {
3761             FontSpec *fs;
3762             EXPECTS_ARG;
3763             SECOND_PASS_ONLY;
3764             fs = fontspec_new(val);
3765             conf_set_fontspec(conf, CONF_boldfont, fs);
3766             fontspec_free(fs);
3767
3768         } else if (!strcmp(p, "-fw")) {
3769             FontSpec *fs;
3770             EXPECTS_ARG;
3771             SECOND_PASS_ONLY;
3772             fs = fontspec_new(val);
3773             conf_set_fontspec(conf, CONF_widefont, fs);
3774             fontspec_free(fs);
3775
3776         } else if (!strcmp(p, "-fwb")) {
3777             FontSpec *fs;
3778             EXPECTS_ARG;
3779             SECOND_PASS_ONLY;
3780             fs = fontspec_new(val);
3781             conf_set_fontspec(conf, CONF_wideboldfont, fs);
3782             fontspec_free(fs);
3783
3784         } else if (!strcmp(p, "-cs")) {
3785             EXPECTS_ARG;
3786             SECOND_PASS_ONLY;
3787             conf_set_str(conf, CONF_line_codepage, val);
3788
3789         } else if (!strcmp(p, "-geometry")) {
3790             EXPECTS_ARG;
3791             SECOND_PASS_ONLY;
3792
3793 #if GTK_CHECK_VERSION(2,0,0)
3794             inst->geometry = val;
3795 #else
3796             /* On GTK 1, we have to do this using raw Xlib */
3797             {
3798                 int flags, x, y;
3799                 unsigned int w, h;
3800                 flags = XParseGeometry(val, &x, &y, &w, &h);
3801                 if (flags & WidthValue)
3802                     conf_set_int(conf, CONF_width, w);
3803                 if (flags & HeightValue)
3804                     conf_set_int(conf, CONF_height, h);
3805
3806                 if (flags & (XValue | YValue)) {
3807                     inst->xpos = x;
3808                     inst->ypos = y;
3809                     inst->gotpos = TRUE;
3810                     inst->gravity = ((flags & XNegative ? 1 : 0) |
3811                                      (flags & YNegative ? 2 : 0));
3812                 }
3813             }
3814 #endif
3815
3816         } else if (!strcmp(p, "-sl")) {
3817             EXPECTS_ARG;
3818             SECOND_PASS_ONLY;
3819             conf_set_int(conf, CONF_savelines, atoi(val));
3820
3821         } else if (!strcmp(p, "-fg") || !strcmp(p, "-bg") ||
3822                    !strcmp(p, "-bfg") || !strcmp(p, "-bbg") ||
3823                    !strcmp(p, "-cfg") || !strcmp(p, "-cbg")) {
3824             EXPECTS_ARG;
3825             SECOND_PASS_ONLY;
3826
3827             {
3828 #if GTK_CHECK_VERSION(3,0,0)
3829                 GdkRGBA rgba;
3830                 int success = gdk_rgba_parse(&rgba, val);
3831 #else
3832                 GdkColor col;
3833                 int success = gdk_color_parse(val, &col);
3834 #endif
3835
3836                 if (!success) {
3837                     err = 1;
3838                     fprintf(stderr, "%s: unable to parse colour \"%s\"\n",
3839                             appname, val);
3840                 } else {
3841 #if GTK_CHECK_VERSION(3,0,0)
3842                     int r = rgba.red * 255;
3843                     int g = rgba.green * 255;
3844                     int b = rgba.blue * 255;
3845 #else
3846                     int r = col.red / 256;
3847                     int g = col.green / 256;
3848                     int b = col.blue / 256;
3849 #endif
3850
3851                     int index;
3852                     index = (!strcmp(p, "-fg") ? 0 :
3853                              !strcmp(p, "-bg") ? 2 :
3854                              !strcmp(p, "-bfg") ? 1 :
3855                              !strcmp(p, "-bbg") ? 3 :
3856                              !strcmp(p, "-cfg") ? 4 :
3857                              !strcmp(p, "-cbg") ? 5 : -1);
3858                     assert(index != -1);
3859
3860                     conf_set_int_int(conf, CONF_colours, index*3+0, r);
3861                     conf_set_int_int(conf, CONF_colours, index*3+1, g);
3862                     conf_set_int_int(conf, CONF_colours, index*3+2, b);
3863                 }
3864             }
3865
3866         } else if (use_pty_argv && !strcmp(p, "-e")) {
3867             /* This option swallows all further arguments. */
3868             if (!do_everything)
3869                 break;
3870
3871             if (--argc > 0) {
3872                 int i;
3873                 pty_argv = snewn(argc+1, char *);
3874                 ++argv;
3875                 for (i = 0; i < argc; i++)
3876                     pty_argv[i] = argv[i];
3877                 pty_argv[argc] = NULL;
3878                 break;                 /* finished command-line processing */
3879             } else
3880                 err = 1, fprintf(stderr, "%s: -e expects an argument\n",
3881                                  appname);
3882
3883         } else if (!strcmp(p, "-title")) {
3884             EXPECTS_ARG;
3885             SECOND_PASS_ONLY;
3886             conf_set_str(conf, CONF_wintitle, val);
3887
3888         } else if (!strcmp(p, "-log")) {
3889             Filename *fn;
3890             EXPECTS_ARG;
3891             SECOND_PASS_ONLY;
3892             fn = filename_from_str(val);
3893             conf_set_filename(conf, CONF_logfilename, fn);
3894             conf_set_int(conf, CONF_logtype, LGTYP_DEBUG);
3895             filename_free(fn);
3896
3897         } else if (!strcmp(p, "-ut-") || !strcmp(p, "+ut")) {
3898             SECOND_PASS_ONLY;
3899             conf_set_int(conf, CONF_stamp_utmp, 0);
3900
3901         } else if (!strcmp(p, "-ut")) {
3902             SECOND_PASS_ONLY;
3903             conf_set_int(conf, CONF_stamp_utmp, 1);
3904
3905         } else if (!strcmp(p, "-ls-") || !strcmp(p, "+ls")) {
3906             SECOND_PASS_ONLY;
3907             conf_set_int(conf, CONF_login_shell, 0);
3908
3909         } else if (!strcmp(p, "-ls")) {
3910             SECOND_PASS_ONLY;
3911             conf_set_int(conf, CONF_login_shell, 1);
3912
3913         } else if (!strcmp(p, "-nethack")) {
3914             SECOND_PASS_ONLY;
3915             conf_set_int(conf, CONF_nethack_keypad, 1);
3916
3917         } else if (!strcmp(p, "-sb-") || !strcmp(p, "+sb")) {
3918             SECOND_PASS_ONLY;
3919             conf_set_int(conf, CONF_scrollbar, 0);
3920
3921         } else if (!strcmp(p, "-sb")) {
3922             SECOND_PASS_ONLY;
3923             conf_set_int(conf, CONF_scrollbar, 1);
3924
3925         } else if (!strcmp(p, "-name")) {
3926             EXPECTS_ARG;
3927             app_name = val;
3928
3929         } else if (!strcmp(p, "-xrm")) {
3930             EXPECTS_ARG;
3931             provide_xrm_string(val);
3932
3933         } else if(!strcmp(p, "-help") || !strcmp(p, "--help")) {
3934             help(stdout);
3935             exit(0);
3936
3937         } else if(!strcmp(p, "-version") || !strcmp(p, "--version")) {
3938             version(stdout);
3939             exit(0);
3940
3941         } else if (!strcmp(p, "-pgpfp")) {
3942             pgp_fingerprints();
3943             exit(1);
3944
3945         } else if(p[0] != '-' && (!do_everything ||
3946                                   process_nonoption_arg(p, conf,
3947                                                         allow_launch))) {
3948             /* do nothing */
3949
3950         } else {
3951             err = 1;
3952             fprintf(stderr, "%s: unrecognized option '%s'\n", appname, p);
3953         }
3954     }
3955
3956     return err;
3957 }
3958
3959 struct uxsel_id {
3960 #if GTK_CHECK_VERSION(2,0,0)
3961     GIOChannel *chan;
3962     guint watch_id;
3963 #else
3964     int id;
3965 #endif
3966 };
3967
3968 uxsel_id *uxsel_input_add(int fd, int rwx) {
3969     uxsel_id *id = snew(uxsel_id);
3970
3971 #if GTK_CHECK_VERSION(2,0,0)
3972     int flags = 0;
3973     if (rwx & 1) flags |= G_IO_IN;
3974     if (rwx & 2) flags |= G_IO_OUT;
3975     if (rwx & 4) flags |= G_IO_PRI;
3976     id->chan = g_io_channel_unix_new(fd);
3977     g_io_channel_set_encoding(id->chan, NULL, NULL);
3978     id->watch_id = g_io_add_watch(id->chan, flags, fd_input_func, NULL);
3979 #else
3980     int flags = 0;
3981     if (rwx & 1) flags |= GDK_INPUT_READ;
3982     if (rwx & 2) flags |= GDK_INPUT_WRITE;
3983     if (rwx & 4) flags |= GDK_INPUT_EXCEPTION;
3984     assert(flags);
3985     id->id = gdk_input_add(fd, flags, fd_input_func, NULL);
3986 #endif
3987
3988     return id;
3989 }
3990
3991 void uxsel_input_remove(uxsel_id *id) {
3992 #if GTK_CHECK_VERSION(2,0,0)
3993     g_source_remove(id->watch_id);
3994     g_io_channel_unref(id->chan);
3995 #else
3996     gdk_input_remove(id->id);
3997 #endif
3998     sfree(id);
3999 }
4000
4001 int frontend_is_utf8(void *frontend)
4002 {
4003     struct gui_data *inst = (struct gui_data *)frontend;
4004     return inst->ucsdata.line_codepage == CS_UTF8;
4005 }
4006
4007 char *setup_fonts_ucs(struct gui_data *inst)
4008 {
4009     int shadowbold = conf_get_int(inst->conf, CONF_shadowbold);
4010     int shadowboldoffset = conf_get_int(inst->conf, CONF_shadowboldoffset);
4011     FontSpec *fs;
4012     unifont *fonts[4];
4013     int i;
4014
4015     fs = conf_get_fontspec(inst->conf, CONF_font);
4016     fonts[0] = multifont_create(inst->area, fs->name, FALSE, FALSE,
4017                                 shadowboldoffset, shadowbold);
4018     if (!fonts[0]) {
4019         return dupprintf("unable to load font \"%s\"", fs->name);
4020     }
4021
4022     fs = conf_get_fontspec(inst->conf, CONF_boldfont);
4023     if (shadowbold || !fs->name[0]) {
4024         fonts[1] = NULL;
4025     } else {
4026         fonts[1] = multifont_create(inst->area, fs->name, FALSE, TRUE,
4027                                     shadowboldoffset, shadowbold);
4028         if (!fonts[1]) {
4029             if (fonts[0])
4030                 unifont_destroy(fonts[0]);
4031             return dupprintf("unable to load bold font \"%s\"", fs->name);
4032         }
4033     }
4034
4035     fs = conf_get_fontspec(inst->conf, CONF_widefont);
4036     if (fs->name[0]) {
4037         fonts[2] = multifont_create(inst->area, fs->name, TRUE, FALSE,
4038                                     shadowboldoffset, shadowbold);
4039         if (!fonts[2]) {
4040             for (i = 0; i < 2; i++)
4041                 if (fonts[i])
4042                     unifont_destroy(fonts[i]);
4043             return dupprintf("unable to load wide font \"%s\"", fs->name);
4044         }
4045     } else {
4046         fonts[2] = NULL;
4047     }
4048
4049     fs = conf_get_fontspec(inst->conf, CONF_wideboldfont);
4050     if (shadowbold || !fs->name[0]) {
4051         fonts[3] = NULL;
4052     } else {
4053         fonts[3] = multifont_create(inst->area, fs->name, TRUE, TRUE,
4054                                     shadowboldoffset, shadowbold);
4055         if (!fonts[3]) {
4056             for (i = 0; i < 3; i++)
4057                 if (fonts[i])
4058                     unifont_destroy(fonts[i]);
4059             return dupprintf("unable to load wide bold font \"%s\"", fs->name);
4060         }
4061     }
4062
4063     /*
4064      * Now we've got past all the possible error conditions, we can
4065      * actually update our state.
4066      */
4067
4068     for (i = 0; i < 4; i++) {
4069         if (inst->fonts[i])
4070             unifont_destroy(inst->fonts[i]);
4071         inst->fonts[i] = fonts[i];
4072     }
4073
4074     inst->font_width = inst->fonts[0]->width;
4075     inst->font_height = inst->fonts[0]->height;
4076
4077     inst->direct_to_font = init_ucs(&inst->ucsdata,
4078                                     conf_get_str(inst->conf, CONF_line_codepage),
4079                                     conf_get_int(inst->conf, CONF_utf8_override),
4080                                     inst->fonts[0]->public_charset,
4081                                     conf_get_int(inst->conf, CONF_vtmode));
4082
4083     inst->drawtype = inst->fonts[0]->preferred_drawtype;
4084
4085     return NULL;
4086 }
4087
4088 void set_geom_hints(struct gui_data *inst)
4089 {
4090     GdkGeometry geom;
4091     geom.min_width = inst->font_width + 2*inst->window_border;
4092     geom.min_height = inst->font_height + 2*inst->window_border;
4093     geom.max_width = geom.max_height = -1;
4094     geom.base_width = 2*inst->window_border;
4095     geom.base_height = 2*inst->window_border;
4096     geom.width_inc = inst->font_width;
4097     geom.height_inc = inst->font_height;
4098     geom.min_aspect = geom.max_aspect = 0;
4099     gtk_window_set_geometry_hints(GTK_WINDOW(inst->window), inst->area, &geom,
4100                                   GDK_HINT_MIN_SIZE | GDK_HINT_BASE_SIZE |
4101                                   GDK_HINT_RESIZE_INC);
4102 }
4103
4104 void clear_scrollback_menuitem(GtkMenuItem *item, gpointer data)
4105 {
4106     struct gui_data *inst = (struct gui_data *)data;
4107     term_clrsb(inst->term);
4108 }
4109
4110 void reset_terminal_menuitem(GtkMenuItem *item, gpointer data)
4111 {
4112     struct gui_data *inst = (struct gui_data *)data;
4113     term_pwron(inst->term, TRUE);
4114     if (inst->ldisc)
4115         ldisc_echoedit_update(inst->ldisc);
4116 }
4117
4118 void copy_all_menuitem(GtkMenuItem *item, gpointer data)
4119 {
4120     struct gui_data *inst = (struct gui_data *)data;
4121     term_copyall(inst->term);
4122 }
4123
4124 void special_menuitem(GtkMenuItem *item, gpointer data)
4125 {
4126     struct gui_data *inst = (struct gui_data *)data;
4127     int code = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(item),
4128                                                  "user-data"));
4129
4130     if (inst->back)
4131         inst->back->special(inst->backhandle, code);
4132 }
4133
4134 void about_menuitem(GtkMenuItem *item, gpointer data)
4135 {
4136     struct gui_data *inst = (struct gui_data *)data;
4137     about_box(inst->window);
4138 }
4139
4140 void event_log_menuitem(GtkMenuItem *item, gpointer data)
4141 {
4142     struct gui_data *inst = (struct gui_data *)data;
4143     showeventlog(inst->eventlogstuff, inst->window);
4144 }
4145
4146 void change_settings_menuitem(GtkMenuItem *item, gpointer data)
4147 {
4148     /* This maps colour indices in inst->conf to those used in inst->cols. */
4149     static const int ww[] = {
4150         256, 257, 258, 259, 260, 261,
4151         0, 8, 1, 9, 2, 10, 3, 11,
4152         4, 12, 5, 13, 6, 14, 7, 15
4153     };
4154     struct gui_data *inst = (struct gui_data *)data;
4155     char *title;
4156     Conf *oldconf, *newconf;
4157     int i, j, need_size;
4158
4159     assert(lenof(ww) == NCFGCOLOURS);
4160
4161     if (inst->reconfiguring)
4162       return;
4163     else
4164       inst->reconfiguring = TRUE;
4165
4166     title = dupcat(appname, " Reconfiguration", NULL);
4167
4168     oldconf = inst->conf;
4169     newconf = conf_copy(inst->conf);
4170
4171     if (do_config_box(title, newconf, 1,
4172                       inst->back?inst->back->cfg_info(inst->backhandle):0)) {
4173         inst->conf = newconf;
4174
4175         /* Pass new config data to the logging module */
4176         log_reconfig(inst->logctx, inst->conf);
4177         /*
4178          * Flush the line discipline's edit buffer in the case
4179          * where local editing has just been disabled.
4180          */
4181         if (inst->ldisc) {
4182             ldisc_configure(inst->ldisc, inst->conf);
4183             ldisc_echoedit_update(inst->ldisc);
4184         }
4185         /* Pass new config data to the terminal */
4186         term_reconfig(inst->term, inst->conf);
4187         /* Pass new config data to the back end */
4188         if (inst->back)
4189             inst->back->reconfig(inst->backhandle, inst->conf);
4190
4191         cache_conf_values(inst);
4192
4193         /*
4194          * Just setting inst->conf is sufficient to cause colour
4195          * setting changes to appear on the next ESC]R palette
4196          * reset. But we should also check whether any colour
4197          * settings have been changed, and revert the ones that have
4198          * to the new default, on the assumption that the user is
4199          * most likely to want an immediate update.
4200          */
4201         for (i = 0; i < NCFGCOLOURS; i++) {
4202             for (j = 0; j < 3; j++)
4203                 if (conf_get_int_int(oldconf, CONF_colours, i*3+j) !=
4204                     conf_get_int_int(newconf, CONF_colours, i*3+j))
4205                     break;
4206             if (j < 3) {
4207                 real_palette_set(inst, ww[i],
4208                                  conf_get_int_int(newconf,CONF_colours,i*3+0),
4209                                  conf_get_int_int(newconf,CONF_colours,i*3+1),
4210                                  conf_get_int_int(newconf,CONF_colours,i*3+2));
4211
4212                 /*
4213                  * If the default background has changed, we must
4214                  * repaint the space in between the window border
4215                  * and the text area.
4216                  */
4217                 if (ww[i] == 258) {
4218                     set_window_background(inst);
4219                     draw_backing_rect(inst);
4220                 }
4221             }
4222         }
4223
4224         /*
4225          * If the scrollbar needs to be shown, hidden, or moved
4226          * from one end to the other of the window, do so now.
4227          */
4228         if (conf_get_int(oldconf, CONF_scrollbar) !=
4229             conf_get_int(newconf, CONF_scrollbar)) {
4230             if (conf_get_int(newconf, CONF_scrollbar))
4231                 gtk_widget_show(inst->sbar);
4232             else
4233                 gtk_widget_hide(inst->sbar);
4234         }
4235         if (conf_get_int(oldconf, CONF_scrollbar_on_left) !=
4236             conf_get_int(newconf, CONF_scrollbar_on_left)) {
4237             gtk_box_reorder_child(inst->hbox, inst->sbar,
4238                                   conf_get_int(newconf, CONF_scrollbar_on_left)
4239                                   ? 0 : 1);
4240         }
4241
4242         /*
4243          * Change the window title, if required.
4244          */
4245         if (strcmp(conf_get_str(oldconf, CONF_wintitle),
4246                    conf_get_str(newconf, CONF_wintitle)))
4247             set_title(inst, conf_get_str(newconf, CONF_wintitle));
4248         set_window_titles(inst);
4249
4250         /*
4251          * Redo the whole tangled fonts and Unicode mess if
4252          * necessary.
4253          */
4254         need_size = FALSE;
4255         if (strcmp(conf_get_fontspec(oldconf, CONF_font)->name,
4256                    conf_get_fontspec(newconf, CONF_font)->name) ||
4257             strcmp(conf_get_fontspec(oldconf, CONF_boldfont)->name,
4258                    conf_get_fontspec(newconf, CONF_boldfont)->name) ||
4259             strcmp(conf_get_fontspec(oldconf, CONF_widefont)->name,
4260                    conf_get_fontspec(newconf, CONF_widefont)->name) ||
4261             strcmp(conf_get_fontspec(oldconf, CONF_wideboldfont)->name,
4262                    conf_get_fontspec(newconf, CONF_wideboldfont)->name) ||
4263             strcmp(conf_get_str(oldconf, CONF_line_codepage),
4264                    conf_get_str(newconf, CONF_line_codepage)) ||
4265             conf_get_int(oldconf, CONF_utf8_override) !=
4266             conf_get_int(newconf, CONF_utf8_override) ||
4267             conf_get_int(oldconf, CONF_vtmode) !=
4268             conf_get_int(newconf, CONF_vtmode) ||
4269             conf_get_int(oldconf, CONF_shadowbold) !=
4270             conf_get_int(newconf, CONF_shadowbold) ||
4271             conf_get_int(oldconf, CONF_shadowboldoffset) !=
4272             conf_get_int(newconf, CONF_shadowboldoffset)) {
4273             char *errmsg = setup_fonts_ucs(inst);
4274             if (errmsg) {
4275                 char *msgboxtext =
4276                     dupprintf("Could not change fonts in terminal window: %s\n",
4277                               errmsg);
4278                 messagebox(inst->window, "Font setup error", msgboxtext,
4279                            string_width("Could not change fonts in terminal window:"),
4280                            "OK", 'o', +1, 1,
4281                            NULL);
4282                 sfree(msgboxtext);
4283                 sfree(errmsg);
4284             } else {
4285                 need_size = TRUE;
4286             }
4287         }
4288
4289         /*
4290          * Resize the window.
4291          */
4292         if (conf_get_int(oldconf, CONF_width) !=
4293             conf_get_int(newconf, CONF_width) ||
4294             conf_get_int(oldconf, CONF_height) !=
4295             conf_get_int(newconf, CONF_height) ||
4296             conf_get_int(oldconf, CONF_window_border) !=
4297             conf_get_int(newconf, CONF_window_border) ||
4298             need_size) {
4299             set_geom_hints(inst);
4300             request_resize(inst, conf_get_int(newconf, CONF_width),
4301                            conf_get_int(newconf, CONF_height));
4302         } else {
4303             /*
4304              * The above will have caused a call to term_size() for
4305              * us if it happened. If the user has fiddled with only
4306              * the scrollback size, the above will not have
4307              * happened and we will need an explicit term_size()
4308              * here.
4309              */
4310             if (conf_get_int(oldconf, CONF_savelines) !=
4311                 conf_get_int(newconf, CONF_savelines))
4312                 term_size(inst->term, inst->term->rows, inst->term->cols,
4313                           conf_get_int(newconf, CONF_savelines));
4314         }
4315
4316         term_invalidate(inst->term);
4317
4318         /*
4319          * We do an explicit full redraw here to ensure the window
4320          * border has been redrawn as well as the text area.
4321          */
4322         gtk_widget_queue_draw(inst->area);
4323
4324         conf_free(oldconf);
4325     } else {
4326         conf_free(newconf);
4327     }
4328     sfree(title);
4329     inst->reconfiguring = FALSE;
4330 }
4331
4332 void fork_and_exec_self(struct gui_data *inst, int fd_to_close, ...)
4333 {
4334     /*
4335      * Re-execing ourself is not an exact science under Unix. I do
4336      * the best I can by using /proc/self/exe if available and by
4337      * assuming argv[0] can be found on $PATH if not.
4338      * 
4339      * Note that we also have to reconstruct the elements of the
4340      * original argv which gtk swallowed, since the user wants the
4341      * new session to appear on the same X display as the old one.
4342      */
4343     char **args;
4344     va_list ap;
4345     int i, n;
4346     int pid;
4347
4348     /*
4349      * Collect the arguments with which to re-exec ourself.
4350      */
4351     va_start(ap, fd_to_close);
4352     n = 2;                             /* progname and terminating NULL */
4353     n += inst->ngtkargs;
4354     while (va_arg(ap, char *) != NULL)
4355         n++;
4356     va_end(ap);
4357
4358     args = snewn(n, char *);
4359     args[0] = inst->progname;
4360     args[n-1] = NULL;
4361     for (i = 0; i < inst->ngtkargs; i++)
4362         args[i+1] = inst->gtkargvstart[i];
4363
4364     i++;
4365     va_start(ap, fd_to_close);
4366     while ((args[i++] = va_arg(ap, char *)) != NULL);
4367     va_end(ap);
4368
4369     assert(i == n);
4370
4371     /*
4372      * Do the double fork.
4373      */
4374     pid = fork();
4375     if (pid < 0) {
4376         perror("fork");
4377         sfree(args);
4378         return;
4379     }
4380
4381     if (pid == 0) {
4382         int pid2 = fork();
4383         if (pid2 < 0) {
4384             perror("fork");
4385             _exit(1);
4386         } else if (pid2 > 0) {
4387             /*
4388              * First child has successfully forked second child. My
4389              * Work Here Is Done. Note the use of _exit rather than
4390              * exit: the latter appears to cause destroy messages
4391              * to be sent to the X server. I suspect gtk uses
4392              * atexit.
4393              */
4394             _exit(0);
4395         }
4396
4397         /*
4398          * If we reach here, we are the second child, so we now
4399          * actually perform the exec.
4400          */
4401         if (fd_to_close >= 0)
4402             close(fd_to_close);
4403
4404         execv("/proc/self/exe", args);
4405         execvp(inst->progname, args);
4406         perror("exec");
4407         _exit(127);
4408
4409     } else {
4410         int status;
4411         sfree(args);
4412         waitpid(pid, &status, 0);
4413     }
4414
4415 }
4416
4417 void dup_session_menuitem(GtkMenuItem *item, gpointer gdata)
4418 {
4419     struct gui_data *inst = (struct gui_data *)gdata;
4420     /*
4421      * For this feature we must marshal conf and (possibly) pty_argv
4422      * into a byte stream, create a pipe, and send this byte stream
4423      * to the child through the pipe.
4424      */
4425     int i, ret, sersize, size;
4426     char *data;
4427     char option[80];
4428     int pipefd[2];
4429
4430     if (pipe(pipefd) < 0) {
4431         perror("pipe");
4432         return;
4433     }
4434
4435     size = sersize = conf_serialised_size(inst->conf);
4436     if (use_pty_argv && pty_argv) {
4437         for (i = 0; pty_argv[i]; i++)
4438             size += strlen(pty_argv[i]) + 1;
4439     }
4440
4441     data = snewn(size, char);
4442     conf_serialise(inst->conf, data);
4443     if (use_pty_argv && pty_argv) {
4444         int p = sersize;
4445         for (i = 0; pty_argv[i]; i++) {
4446             strcpy(data + p, pty_argv[i]);
4447             p += strlen(pty_argv[i]) + 1;
4448         }
4449         assert(p == size);
4450     }
4451
4452     sprintf(option, "---[%d,%d]", pipefd[0], size);
4453     noncloexec(pipefd[0]);
4454     fork_and_exec_self(inst, pipefd[1], option, NULL);
4455     close(pipefd[0]);
4456
4457     i = ret = 0;
4458     while (i < size && (ret = write(pipefd[1], data + i, size - i)) > 0)
4459         i += ret;
4460     if (ret < 0)
4461         perror("write to pipe");
4462     close(pipefd[1]);
4463     sfree(data);
4464 }
4465
4466 int read_dupsession_data(struct gui_data *inst, Conf *conf, char *arg)
4467 {
4468     int fd, i, ret, size, size_used;
4469     char *data;
4470
4471     if (sscanf(arg, "---[%d,%d]", &fd, &size) != 2) {
4472         fprintf(stderr, "%s: malformed magic argument `%s'\n", appname, arg);
4473         exit(1);
4474     }
4475
4476     data = snewn(size, char);
4477     i = ret = 0;
4478     while (i < size && (ret = read(fd, data + i, size - i)) > 0)
4479         i += ret;
4480     if (ret < 0) {
4481         perror("read from pipe");
4482         exit(1);
4483     } else if (i < size) {
4484         fprintf(stderr, "%s: unexpected EOF in Duplicate Session data\n",
4485                 appname);
4486         exit(1);
4487     }
4488
4489     size_used = conf_deserialise(conf, data, size);
4490     if (use_pty_argv && size > size_used) {
4491         int n = 0;
4492         i = size_used;
4493         while (i < size) {
4494             while (i < size && data[i]) i++;
4495             if (i >= size) {
4496                 fprintf(stderr, "%s: malformed Duplicate Session data\n",
4497                         appname);
4498                 exit(1);
4499             }
4500             i++;
4501             n++;
4502         }
4503         pty_argv = snewn(n+1, char *);
4504         pty_argv[n] = NULL;
4505         n = 0;
4506         i = size_used;
4507         while (i < size) {
4508             char *p = data + i;
4509             while (i < size && data[i]) i++;
4510             assert(i < size);
4511             i++;
4512             pty_argv[n++] = dupstr(p);
4513         }
4514     }
4515
4516     sfree(data);
4517
4518     return 0;
4519 }
4520
4521 void new_session_menuitem(GtkMenuItem *item, gpointer data)
4522 {
4523     struct gui_data *inst = (struct gui_data *)data;
4524
4525     fork_and_exec_self(inst, -1, NULL);
4526 }
4527
4528 void restart_session_menuitem(GtkMenuItem *item, gpointer data)
4529 {
4530     struct gui_data *inst = (struct gui_data *)data;
4531
4532     if (!inst->back) {
4533         logevent(inst, "----- Session restarted -----");
4534         term_pwron(inst->term, FALSE);
4535         start_backend(inst);
4536         inst->exited = FALSE;
4537     }
4538 }
4539
4540 void saved_session_menuitem(GtkMenuItem *item, gpointer data)
4541 {
4542     struct gui_data *inst = (struct gui_data *)data;
4543     char *str = (char *)g_object_get_data(G_OBJECT(item), "user-data");
4544
4545     fork_and_exec_self(inst, -1, "-load", str, NULL);
4546 }
4547
4548 void saved_session_freedata(GtkMenuItem *item, gpointer data)
4549 {
4550     char *str = (char *)g_object_get_data(G_OBJECT(item), "user-data");
4551
4552     sfree(str);
4553 }
4554
4555 static void update_savedsess_menu(GtkMenuItem *menuitem, gpointer data)
4556 {
4557     struct gui_data *inst = (struct gui_data *)data;
4558     struct sesslist sesslist;
4559     int i;
4560
4561     gtk_container_foreach(GTK_CONTAINER(inst->sessionsmenu),
4562                           (GtkCallback)gtk_widget_destroy, NULL);
4563
4564     get_sesslist(&sesslist, TRUE);
4565     /* skip sesslist.sessions[0] == Default Settings */
4566     for (i = 1; i < sesslist.nsessions; i++) {
4567         GtkWidget *menuitem =
4568             gtk_menu_item_new_with_label(sesslist.sessions[i]);
4569         gtk_container_add(GTK_CONTAINER(inst->sessionsmenu), menuitem);
4570         gtk_widget_show(menuitem);
4571         g_object_set_data(G_OBJECT(menuitem), "user-data",
4572                           dupstr(sesslist.sessions[i]));
4573         g_signal_connect(G_OBJECT(menuitem), "activate",
4574                          G_CALLBACK(saved_session_menuitem),
4575                          inst);
4576         g_signal_connect(G_OBJECT(menuitem), "destroy",
4577                          G_CALLBACK(saved_session_freedata),
4578                          inst);
4579     }
4580     if (sesslist.nsessions <= 1) {
4581         GtkWidget *menuitem =
4582             gtk_menu_item_new_with_label("(No sessions)");
4583         gtk_widget_set_sensitive(menuitem, FALSE);
4584         gtk_container_add(GTK_CONTAINER(inst->sessionsmenu), menuitem);
4585         gtk_widget_show(menuitem);
4586     }
4587     get_sesslist(&sesslist, FALSE); /* free up */
4588 }
4589
4590 void set_window_icon(GtkWidget *window, const char *const *const *icon,
4591                      int n_icon)
4592 {
4593 #if GTK_CHECK_VERSION(2,0,0)
4594     GList *iconlist;
4595     int n;
4596 #else
4597     GdkPixmap *iconpm;
4598     GdkBitmap *iconmask;
4599 #endif
4600
4601     if (!n_icon)
4602         return;
4603
4604     gtk_widget_realize(window);
4605 #if GTK_CHECK_VERSION(2,0,0)
4606     gtk_window_set_icon(GTK_WINDOW(window),
4607                         gdk_pixbuf_new_from_xpm_data((const gchar **)icon[0]));
4608 #else
4609     iconpm = gdk_pixmap_create_from_xpm_d(gtk_widget_get_window(window),
4610                                           &iconmask, NULL, (gchar **)icon[0]);
4611     gdk_window_set_icon(gtk_widget_get_window(window), NULL, iconpm, iconmask);
4612 #endif
4613
4614 #if GTK_CHECK_VERSION(2,0,0)
4615     iconlist = NULL;
4616     for (n = 0; n < n_icon; n++) {
4617         iconlist =
4618             g_list_append(iconlist,
4619                           gdk_pixbuf_new_from_xpm_data((const gchar **)
4620                                                        icon[n]));
4621     }
4622     gtk_window_set_icon_list(GTK_WINDOW(window), iconlist);
4623 #endif
4624 }
4625
4626 void update_specials_menu(void *frontend)
4627 {
4628     struct gui_data *inst = (struct gui_data *)frontend;
4629
4630     const struct telnet_special *specials;
4631
4632     if (inst->back)
4633         specials = inst->back->get_specials(inst->backhandle);
4634     else
4635         specials = NULL;
4636
4637     /* I believe this disposes of submenus too. */
4638     gtk_container_foreach(GTK_CONTAINER(inst->specialsmenu),
4639                           (GtkCallback)gtk_widget_destroy, NULL);
4640     if (specials) {
4641         int i;
4642         GtkWidget *menu = inst->specialsmenu;
4643         /* A lame "stack" for submenus that will do for now. */
4644         GtkWidget *saved_menu = NULL;
4645         int nesting = 1;
4646         for (i = 0; nesting > 0; i++) {
4647             GtkWidget *menuitem = NULL;
4648             switch (specials[i].code) {
4649               case TS_SUBMENU:
4650                 assert (nesting < 2);
4651                 saved_menu = menu; /* XXX lame stacking */
4652                 menu = gtk_menu_new();
4653                 menuitem = gtk_menu_item_new_with_label(specials[i].name);
4654                 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), menu);
4655                 gtk_container_add(GTK_CONTAINER(saved_menu), menuitem);
4656                 gtk_widget_show(menuitem);
4657                 menuitem = NULL;
4658                 nesting++;
4659                 break;
4660               case TS_EXITMENU:
4661                 nesting--;
4662                 if (nesting) {
4663                     menu = saved_menu; /* XXX lame stacking */
4664                     saved_menu = NULL;
4665                 }
4666                 break;
4667               case TS_SEP:
4668                 menuitem = gtk_menu_item_new();
4669                 break;
4670               default:
4671                 menuitem = gtk_menu_item_new_with_label(specials[i].name);
4672                 g_object_set_data(G_OBJECT(menuitem), "user-data",
4673                                   GINT_TO_POINTER(specials[i].code));
4674                 g_signal_connect(G_OBJECT(menuitem), "activate",
4675                                  G_CALLBACK(special_menuitem), inst);
4676                 break;
4677             }
4678             if (menuitem) {
4679                 gtk_container_add(GTK_CONTAINER(menu), menuitem);
4680                 gtk_widget_show(menuitem);
4681             }
4682         }
4683         gtk_widget_show(inst->specialsitem1);
4684         gtk_widget_show(inst->specialsitem2);
4685     } else {
4686         gtk_widget_hide(inst->specialsitem1);
4687         gtk_widget_hide(inst->specialsitem2);
4688     }
4689 }
4690
4691 static void start_backend(struct gui_data *inst)
4692 {
4693     extern Backend *select_backend(Conf *conf);
4694     char *realhost;
4695     const char *error;
4696     char *s;
4697
4698     inst->back = select_backend(inst->conf);
4699
4700     error = inst->back->init((void *)inst, &inst->backhandle,
4701                              inst->conf,
4702                              conf_get_str(inst->conf, CONF_host),
4703                              conf_get_int(inst->conf, CONF_port),
4704                              &realhost,
4705                              conf_get_int(inst->conf, CONF_tcp_nodelay),
4706                              conf_get_int(inst->conf, CONF_tcp_keepalives));
4707
4708     if (error) {
4709         char *msg = dupprintf("Unable to open connection to %s:\n%s",
4710                               conf_get_str(inst->conf, CONF_host), error);
4711         inst->exited = TRUE;
4712         fatal_message_box(inst->window, msg);
4713         sfree(msg);
4714         exit(0);
4715     }
4716
4717     s = conf_get_str(inst->conf, CONF_wintitle);
4718     if (s[0]) {
4719         set_title_and_icon(inst, s, s);
4720     } else {
4721         char *title = make_default_wintitle(realhost);
4722         set_title_and_icon(inst, title, title);
4723         sfree(title);
4724     }
4725     sfree(realhost);
4726
4727     inst->back->provide_logctx(inst->backhandle, inst->logctx);
4728
4729     term_provide_resize_fn(inst->term, inst->back->size, inst->backhandle);
4730
4731     inst->ldisc =
4732         ldisc_create(inst->conf, inst->term, inst->back, inst->backhandle,
4733                      inst);
4734
4735     gtk_widget_set_sensitive(inst->restartitem, FALSE);
4736 }
4737
4738 int pt_main(int argc, char **argv)
4739 {
4740     extern int cfgbox(Conf *conf);
4741     struct gui_data *inst;
4742
4743     setlocale(LC_CTYPE, "");
4744
4745     /*
4746      * Create an instance structure and initialise to zeroes
4747      */
4748     inst = snew(struct gui_data);
4749     memset(inst, 0, sizeof(*inst));
4750     inst->alt_keycode = -1;            /* this one needs _not_ to be zero */
4751     inst->busy_status = BUSY_NOT;
4752     inst->conf = conf_new();
4753     inst->wintitle = inst->icontitle = NULL;
4754     inst->quit_fn_scheduled = FALSE;
4755     inst->idle_fn_scheduled = FALSE;
4756     inst->drawtype = DRAWTYPE_DEFAULT;
4757
4758     /* defer any child exit handling until we're ready to deal with
4759      * it */
4760     block_signal(SIGCHLD, 1);
4761
4762     inst->progname = argv[0];
4763     /*
4764      * Copy the original argv before letting gtk_init fiddle with
4765      * it. It will be required later.
4766      */
4767     {
4768         int i, oldargc;
4769         inst->gtkargvstart = snewn(argc-1, char *);
4770         for (i = 1; i < argc; i++)
4771             inst->gtkargvstart[i-1] = dupstr(argv[i]);
4772         oldargc = argc;
4773         gtk_init(&argc, &argv);
4774         inst->ngtkargs = oldargc - argc;
4775     }
4776
4777     if (argc > 1 && !strncmp(argv[1], "---", 3)) {
4778         read_dupsession_data(inst, inst->conf, argv[1]);
4779         /* Splatter this argument so it doesn't clutter a ps listing */
4780         smemclr(argv[1], strlen(argv[1]));
4781     } else {
4782         /* By default, we bring up the config dialog, rather than launching
4783          * a session. This gets set to TRUE if something happens to change
4784          * that (e.g., a hostname is specified on the command-line). */
4785         int allow_launch = FALSE;
4786         if (do_cmdline(argc, argv, 0, &allow_launch, inst, inst->conf))
4787             exit(1);                   /* pre-defaults pass to get -class */
4788         do_defaults(NULL, inst->conf);
4789         if (do_cmdline(argc, argv, 1, &allow_launch, inst, inst->conf))
4790             exit(1);                   /* post-defaults, do everything */
4791
4792         cmdline_run_saved(inst->conf);
4793
4794         if (loaded_session)
4795             allow_launch = TRUE;
4796
4797         if ((!allow_launch || !conf_launchable(inst->conf)) &&
4798             !cfgbox(inst->conf))
4799             exit(0);                   /* config box hit Cancel */
4800     }
4801
4802     if (!compound_text_atom)
4803         compound_text_atom = gdk_atom_intern("COMPOUND_TEXT", FALSE);
4804     if (!utf8_string_atom)
4805         utf8_string_atom = gdk_atom_intern("UTF8_STRING", FALSE);
4806
4807     inst->area = gtk_drawing_area_new();
4808
4809 #if GTK_CHECK_VERSION(2,0,0)
4810     inst->imc = gtk_im_multicontext_new();
4811 #endif
4812
4813     {
4814         char *errmsg = setup_fonts_ucs(inst);
4815         if (errmsg) {
4816             fprintf(stderr, "%s: %s\n", appname, errmsg);
4817             exit(1);
4818         }
4819     }
4820     inst->window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
4821     {
4822         const char *winclass = conf_get_str(inst->conf, CONF_winclass);
4823         if (*winclass)
4824             gtk_window_set_wmclass(GTK_WINDOW(inst->window),
4825                                    winclass, winclass);
4826     }
4827
4828     /*
4829      * Set up the colour map.
4830      */
4831     palette_reset(inst);
4832
4833     inst->width = conf_get_int(inst->conf, CONF_width);
4834     inst->height = conf_get_int(inst->conf, CONF_height);
4835     cache_conf_values(inst);
4836
4837     init_clipboard(inst);
4838
4839     {
4840         int w = inst->font_width * inst->width + 2*inst->window_border;
4841         int h = inst->font_height * inst->height + 2*inst->window_border;
4842 #if GTK_CHECK_VERSION(2,0,0)
4843         gtk_widget_set_size_request(inst->area, w, h);
4844 #else
4845         gtk_drawing_area_size(GTK_DRAWING_AREA(inst->area), w, h);
4846 #endif
4847     }
4848     inst->sbar_adjust = GTK_ADJUSTMENT(gtk_adjustment_new(0,0,0,0,0,0));
4849     inst->sbar = gtk_vscrollbar_new(inst->sbar_adjust);
4850     inst->hbox = GTK_BOX(gtk_hbox_new(FALSE, 0));
4851     /*
4852      * We always create the scrollbar; it remains invisible if
4853      * unwanted, so we can pop it up quickly if it suddenly becomes
4854      * desirable.
4855      */
4856     if (conf_get_int(inst->conf, CONF_scrollbar_on_left))
4857         gtk_box_pack_start(inst->hbox, inst->sbar, FALSE, FALSE, 0);
4858     gtk_box_pack_start(inst->hbox, inst->area, TRUE, TRUE, 0);
4859     if (!conf_get_int(inst->conf, CONF_scrollbar_on_left))
4860         gtk_box_pack_start(inst->hbox, inst->sbar, FALSE, FALSE, 0);
4861
4862     gtk_container_add(GTK_CONTAINER(inst->window), GTK_WIDGET(inst->hbox));
4863
4864     set_geom_hints(inst);
4865
4866     gtk_widget_show(inst->area);
4867     if (conf_get_int(inst->conf, CONF_scrollbar))
4868         gtk_widget_show(inst->sbar);
4869     else
4870         gtk_widget_hide(inst->sbar);
4871     gtk_widget_show(GTK_WIDGET(inst->hbox));
4872
4873 #if GTK_CHECK_VERSION(2,0,0)
4874     if (inst->geometry) {
4875         gtk_window_parse_geometry(GTK_WINDOW(inst->window), inst->geometry);
4876     }
4877 #else
4878     if (inst->gotpos) {
4879         int x = inst->xpos, y = inst->ypos;
4880         GtkRequisition req;
4881         gtk_widget_size_request(GTK_WIDGET(inst->window), &req);
4882         if (inst->gravity & 1) x += gdk_screen_width() - req.width;
4883         if (inst->gravity & 2) y += gdk_screen_height() - req.height;
4884         gtk_window_set_position(GTK_WINDOW(inst->window), GTK_WIN_POS_NONE);
4885         gtk_widget_set_uposition(GTK_WIDGET(inst->window), x, y);
4886     }
4887 #endif
4888
4889     g_signal_connect(G_OBJECT(inst->window), "destroy",
4890                      G_CALLBACK(destroy), inst);
4891     g_signal_connect(G_OBJECT(inst->window), "delete_event",
4892                      G_CALLBACK(delete_window), inst);
4893     g_signal_connect(G_OBJECT(inst->window), "key_press_event",
4894                      G_CALLBACK(key_event), inst);
4895     g_signal_connect(G_OBJECT(inst->window), "key_release_event",
4896                      G_CALLBACK(key_event), inst);
4897     g_signal_connect(G_OBJECT(inst->window), "focus_in_event",
4898                      G_CALLBACK(focus_event), inst);
4899     g_signal_connect(G_OBJECT(inst->window), "focus_out_event",
4900                      G_CALLBACK(focus_event), inst);
4901     g_signal_connect(G_OBJECT(inst->area), "configure_event",
4902                      G_CALLBACK(configure_area), inst);
4903 #if GTK_CHECK_VERSION(3,0,0)
4904     g_signal_connect(G_OBJECT(inst->area), "draw",
4905                      G_CALLBACK(draw_area), inst);
4906 #else
4907     g_signal_connect(G_OBJECT(inst->area), "expose_event",
4908                      G_CALLBACK(expose_area), inst);
4909 #endif
4910     g_signal_connect(G_OBJECT(inst->area), "button_press_event",
4911                      G_CALLBACK(button_event), inst);
4912     g_signal_connect(G_OBJECT(inst->area), "button_release_event",
4913                      G_CALLBACK(button_event), inst);
4914 #if GTK_CHECK_VERSION(2,0,0)
4915     g_signal_connect(G_OBJECT(inst->area), "scroll_event",
4916                      G_CALLBACK(scroll_event), inst);
4917 #endif
4918     g_signal_connect(G_OBJECT(inst->area), "motion_notify_event",
4919                      G_CALLBACK(motion_event), inst);
4920 #if GTK_CHECK_VERSION(2,0,0)
4921     g_signal_connect(G_OBJECT(inst->imc), "commit",
4922                      G_CALLBACK(input_method_commit_event), inst);
4923 #endif
4924     if (conf_get_int(inst->conf, CONF_scrollbar))
4925         g_signal_connect(G_OBJECT(inst->sbar_adjust), "value_changed",
4926                          G_CALLBACK(scrollbar_moved), inst);
4927     gtk_widget_add_events(GTK_WIDGET(inst->area),
4928                           GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK |
4929                           GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK |
4930                           GDK_POINTER_MOTION_MASK | GDK_BUTTON_MOTION_MASK);
4931
4932     {
4933         extern const char *const *const main_icon[];
4934         extern const int n_main_icon;
4935         set_window_icon(inst->window, main_icon, n_main_icon);
4936     }
4937
4938     gtk_widget_show(inst->window);
4939
4940     set_window_background(inst);
4941
4942     /*
4943      * Set up the Ctrl+rightclick context menu.
4944      */
4945     {
4946         GtkWidget *menuitem;
4947         char *s;
4948         extern const int use_event_log, new_session, saved_sessions;
4949
4950         inst->menu = gtk_menu_new();
4951
4952 #define MKMENUITEM(title, func) do                                      \
4953         {                                                               \
4954             menuitem = gtk_menu_item_new_with_label(title);             \
4955             gtk_container_add(GTK_CONTAINER(inst->menu), menuitem);     \
4956             gtk_widget_show(menuitem);                                  \
4957             g_signal_connect(G_OBJECT(menuitem), "activate",            \
4958                              G_CALLBACK(func), inst);                   \
4959         } while (0)
4960
4961 #define MKSUBMENU(title) do                                             \
4962         {                                                               \
4963             menuitem = gtk_menu_item_new_with_label(title);             \
4964             gtk_container_add(GTK_CONTAINER(inst->menu), menuitem);     \
4965             gtk_widget_show(menuitem);                                  \
4966         } while (0)
4967
4968 #define MKSEP() do                                                      \
4969         {                                                               \
4970             menuitem = gtk_menu_item_new();                             \
4971             gtk_container_add(GTK_CONTAINER(inst->menu), menuitem);     \
4972             gtk_widget_show(menuitem);                                  \
4973         } while (0)
4974
4975         if (new_session)
4976             MKMENUITEM("New Session...", new_session_menuitem);
4977         MKMENUITEM("Restart Session", restart_session_menuitem);
4978         inst->restartitem = menuitem;
4979         gtk_widget_set_sensitive(inst->restartitem, FALSE);
4980         MKMENUITEM("Duplicate Session", dup_session_menuitem);
4981         if (saved_sessions) {
4982             inst->sessionsmenu = gtk_menu_new();
4983             /* sessionsmenu will be updated when it's invoked */
4984             /* XXX is this the right way to do dynamic menus in Gtk? */
4985             MKMENUITEM("Saved Sessions", update_savedsess_menu);
4986             gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem),
4987                                       inst->sessionsmenu);
4988         }
4989         MKSEP();
4990         MKMENUITEM("Change Settings...", change_settings_menuitem);
4991         MKSEP();
4992         if (use_event_log)
4993             MKMENUITEM("Event Log", event_log_menuitem);
4994         MKSUBMENU("Special Commands");
4995         inst->specialsmenu = gtk_menu_new();
4996         gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), inst->specialsmenu);
4997         inst->specialsitem1 = menuitem;
4998         MKSEP();
4999         inst->specialsitem2 = menuitem;
5000         gtk_widget_hide(inst->specialsitem1);
5001         gtk_widget_hide(inst->specialsitem2);
5002         MKMENUITEM("Clear Scrollback", clear_scrollback_menuitem);
5003         MKMENUITEM("Reset Terminal", reset_terminal_menuitem);
5004         MKMENUITEM("Copy All", copy_all_menuitem);
5005         MKSEP();
5006         s = dupcat("About ", appname, NULL);
5007         MKMENUITEM(s, about_menuitem);
5008         sfree(s);
5009 #undef MKMENUITEM
5010 #undef MKSUBMENU
5011 #undef MKSEP
5012     }
5013
5014     inst->textcursor = make_mouse_ptr(inst, GDK_XTERM);
5015     inst->rawcursor = make_mouse_ptr(inst, GDK_LEFT_PTR);
5016     inst->waitcursor = make_mouse_ptr(inst, GDK_WATCH);
5017     inst->blankcursor = make_mouse_ptr(inst, -1);
5018     inst->currcursor = inst->textcursor;
5019     show_mouseptr(inst, 1);
5020
5021     inst->eventlogstuff = eventlogstuff_new();
5022
5023     request_callback_notifications(notify_toplevel_callback, inst);
5024
5025     inst->term = term_init(inst->conf, &inst->ucsdata, inst);
5026     inst->logctx = log_init(inst, inst->conf);
5027     term_provide_logctx(inst->term, inst->logctx);
5028
5029     uxsel_init();
5030
5031     term_size(inst->term, inst->height, inst->width,
5032               conf_get_int(inst->conf, CONF_savelines));
5033
5034     start_backend(inst);
5035
5036     ldisc_echoedit_update(inst->ldisc);     /* cause ldisc to notice changes */
5037
5038     /* now we're reday to deal with the child exit handler being
5039      * called */
5040     block_signal(SIGCHLD, 0);
5041
5042     /*
5043      * Block SIGPIPE: if we attempt Duplicate Session or similar
5044      * and it falls over in some way, we certainly don't want
5045      * SIGPIPE terminating the main pterm/PuTTY. Note that we do
5046      * this _after_ (at least pterm) forks off its child process,
5047      * since the child wants SIGPIPE handled in the usual way.
5048      */
5049     block_signal(SIGPIPE, 1);
5050
5051     inst->exited = FALSE;
5052
5053     gtk_main();
5054
5055     return 0;
5056 }