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