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