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