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