]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - unix/gtkwin.c
Compile fix for GTK 3.18: avoid gtk_adjustment_changed().
[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 void request_resize(void *frontend, int w, int h)
2018 {
2019     struct gui_data *inst = (struct gui_data *)frontend;
2020
2021 #if !GTK_CHECK_VERSION(3,0,0)
2022
2023     int large_x, large_y;
2024     int offset_x, offset_y;
2025     int area_x, area_y;
2026     GtkRequisition inner, outer;
2027
2028     /*
2029      * This is a heinous hack dreamed up by the gnome-terminal
2030      * people to get around a limitation in gtk. The problem is
2031      * that in order to set the size correctly we really need to be
2032      * calling gtk_window_resize - but that needs to know the size
2033      * of the _whole window_, not the drawing area. So what we do
2034      * is to set an artificially huge size request on the drawing
2035      * area, recompute the resulting size request on the window,
2036      * and look at the difference between the two. That gives us
2037      * the x and y offsets we need to translate drawing area size
2038      * into window size for real, and then we call
2039      * gtk_window_resize.
2040      */
2041
2042     /*
2043      * We start by retrieving the current size of the whole window.
2044      * Adding a bit to _that_ will give us a value we can use as a
2045      * bogus size request which guarantees to be bigger than the
2046      * current size of the drawing area.
2047      */
2048     get_window_pixels(inst, &large_x, &large_y);
2049     large_x += 32;
2050     large_y += 32;
2051
2052     gtk_widget_set_size_request(inst->area, large_x, large_y);
2053     gtk_widget_size_request(inst->area, &inner);
2054     gtk_widget_size_request(inst->window, &outer);
2055
2056     offset_x = outer.width - inner.width;
2057     offset_y = outer.height - inner.height;
2058
2059     area_x = inst->font_width * w + 2*inst->window_border;
2060     area_y = inst->font_height * h + 2*inst->window_border;
2061
2062     /*
2063      * Now we must set the size request on the drawing area back to
2064      * something sensible before we commit the real resize. Best
2065      * way to do this, I think, is to set it to what the size is
2066      * really going to end up being.
2067      */
2068     gtk_widget_set_size_request(inst->area, area_x, area_y);
2069 #if GTK_CHECK_VERSION(2,0,0)
2070     gtk_window_resize(GTK_WINDOW(inst->window),
2071                       area_x + offset_x, area_y + offset_y);
2072 #else
2073     gtk_drawing_area_size(GTK_DRAWING_AREA(inst->area), area_x, area_y);
2074     /*
2075      * I can no longer remember what this call to
2076      * gtk_container_dequeue_resize_handler is for. It was
2077      * introduced in r3092 with no comment, and the commit log
2078      * message was uninformative. I'm _guessing_ its purpose is to
2079      * prevent gratuitous resize processing on the window given
2080      * that we're about to resize it anyway, but I have no idea
2081      * why that's so incredibly vital.
2082      * 
2083      * I've tried removing the call, and nothing seems to go
2084      * wrong. I've backtracked to r3092 and tried removing the
2085      * call there, and still nothing goes wrong. So I'm going to
2086      * adopt the working hypothesis that it's superfluous; I won't
2087      * actually remove it from the GTK 1.2 code, but I won't
2088      * attempt to replicate its functionality in the GTK 2 code
2089      * above.
2090      */
2091     gtk_container_dequeue_resize_handler(GTK_CONTAINER(inst->window));
2092     gdk_window_resize(gtk_widget_get_window(inst->window),
2093                       area_x + offset_x, area_y + offset_y);
2094 #endif
2095
2096 #else /* GTK_CHECK_VERSION(3,0,0) */
2097
2098     /*
2099      * In GTK3, we can do this by using gtk_window_resize_to_geometry,
2100      * which uses the fact that we've already set up the main window's
2101      * WM hints to reflect the terminal drawing area's resize
2102      * increment (i.e. character cell) and the fixed amount of stuff
2103      * round the edges.
2104      */
2105     gtk_window_resize_to_geometry(GTK_WINDOW(inst->window), w, h);
2106
2107 #endif
2108
2109 }
2110
2111 static void real_palette_set(struct gui_data *inst, int n, int r, int g, int b)
2112 {
2113     inst->cols[n].red = r * 0x0101;
2114     inst->cols[n].green = g * 0x0101;
2115     inst->cols[n].blue = b * 0x0101;
2116
2117 #if !GTK_CHECK_VERSION(3,0,0)
2118     {
2119         gboolean success[1];
2120         gdk_colormap_free_colors(inst->colmap, inst->cols + n, 1);
2121         gdk_colormap_alloc_colors(inst->colmap, inst->cols + n, 1,
2122                                   FALSE, TRUE, success);
2123         if (!success[0])
2124             g_error("%s: couldn't allocate colour %d (#%02x%02x%02x)\n",
2125                     appname, n, r, g, b);
2126     }
2127 #endif
2128 }
2129
2130 void set_gdk_window_background(GdkWindow *win, const GdkColor *col)
2131 {
2132 #if GTK_CHECK_VERSION(3,0,0)
2133     /* gdk_window_set_background is deprecated; work around its
2134      * absence. */
2135     GdkRGBA rgba;
2136     rgba.red = col->red / 65535.0;
2137     rgba.green = col->green / 65535.0;
2138     rgba.blue = col->blue / 65535.0;
2139     rgba.alpha = 1.0;
2140     gdk_window_set_background_rgba(win, &rgba);
2141 #else
2142     {
2143         /* For GTK1, which doesn't have a 'const' on
2144          * gdk_window_set_background's second parameter type. */
2145         GdkColor col_mutable = *col;
2146         gdk_window_set_background(win, &col_mutable);
2147     }
2148 #endif
2149 }
2150
2151 void set_window_background(struct gui_data *inst)
2152 {
2153     if (inst->area && gtk_widget_get_window(inst->area))
2154         set_gdk_window_background(gtk_widget_get_window(inst->area),
2155                                   &inst->cols[258]);
2156     if (inst->window && gtk_widget_get_window(inst->window))
2157         set_gdk_window_background(gtk_widget_get_window(inst->window),
2158                                   &inst->cols[258]);
2159 }
2160
2161 void palette_set(void *frontend, int n, int r, int g, int b)
2162 {
2163     struct gui_data *inst = (struct gui_data *)frontend;
2164     if (n >= 16)
2165         n += 256 - 16;
2166     if (n >= NALLCOLOURS)
2167         return;
2168     real_palette_set(inst, n, r, g, b);
2169     if (n == 258) {
2170         /* Default Background changed. Ensure space between text area and
2171          * window border is redrawn */
2172         set_window_background(inst);
2173         draw_backing_rect(inst);
2174         gtk_widget_queue_draw(inst->area);
2175     }
2176 }
2177
2178 void palette_reset(void *frontend)
2179 {
2180     struct gui_data *inst = (struct gui_data *)frontend;
2181     /* This maps colour indices in inst->conf to those used in inst->cols. */
2182     static const int ww[] = {
2183         256, 257, 258, 259, 260, 261,
2184         0, 8, 1, 9, 2, 10, 3, 11,
2185         4, 12, 5, 13, 6, 14, 7, 15
2186     };
2187     int i;
2188
2189     assert(lenof(ww) == NCFGCOLOURS);
2190
2191 #if !GTK_CHECK_VERSION(3,0,0)
2192     if (!inst->colmap) {
2193         inst->colmap = gdk_colormap_get_system();
2194     } else {
2195         gdk_colormap_free_colors(inst->colmap, inst->cols, NALLCOLOURS);
2196     }
2197 #endif
2198
2199     for (i = 0; i < NCFGCOLOURS; i++) {
2200         inst->cols[ww[i]].red =
2201             conf_get_int_int(inst->conf, CONF_colours, i*3+0) * 0x0101;
2202         inst->cols[ww[i]].green =
2203             conf_get_int_int(inst->conf, CONF_colours, i*3+1) * 0x0101;
2204         inst->cols[ww[i]].blue = 
2205             conf_get_int_int(inst->conf, CONF_colours, i*3+2) * 0x0101;
2206     }
2207
2208     for (i = 0; i < NEXTCOLOURS; i++) {
2209         if (i < 216) {
2210             int r = i / 36, g = (i / 6) % 6, b = i % 6;
2211             inst->cols[i+16].red = r ? r * 0x2828 + 0x3737 : 0;
2212             inst->cols[i+16].green = g ? g * 0x2828 + 0x3737 : 0;
2213             inst->cols[i+16].blue = b ? b * 0x2828 + 0x3737 : 0;
2214         } else {
2215             int shade = i - 216;
2216             shade = shade * 0x0a0a + 0x0808;
2217             inst->cols[i+16].red = inst->cols[i+16].green =
2218                 inst->cols[i+16].blue = shade;
2219         }
2220     }
2221
2222 #if !GTK_CHECK_VERSION(3,0,0)
2223     {
2224         gboolean success[NALLCOLOURS];
2225         gdk_colormap_alloc_colors(inst->colmap, inst->cols, NALLCOLOURS,
2226                                   FALSE, TRUE, success);
2227         for (i = 0; i < NALLCOLOURS; i++) {
2228             if (!success[i])
2229                 g_error("%s: couldn't allocate colour %d (#%02x%02x%02x)\n",
2230                         appname, i,
2231                         conf_get_int_int(inst->conf, CONF_colours, i*3+0),
2232                         conf_get_int_int(inst->conf, CONF_colours, i*3+1),
2233                         conf_get_int_int(inst->conf, CONF_colours, i*3+2));
2234         }
2235     }
2236 #endif
2237
2238     /* Since Default Background may have changed, ensure that space
2239      * between text area and window border is refreshed. */
2240     set_window_background(inst);
2241     if (inst->area && gtk_widget_get_window(inst->area)) {
2242         draw_backing_rect(inst);
2243         gtk_widget_queue_draw(inst->area);
2244     }
2245 }
2246
2247 #ifdef JUST_USE_GTK_CLIPBOARD_UTF8
2248
2249 /* ----------------------------------------------------------------------
2250  * Clipboard handling, using the high-level GtkClipboard interface in
2251  * as hands-off a way as possible. We write and read the clipboard as
2252  * UTF-8 text, and let GTK deal with converting to any other text
2253  * formats it feels like.
2254  */
2255
2256 void init_clipboard(struct gui_data *inst)
2257 {
2258     inst->clipboard = gtk_clipboard_get_for_display(gdk_display_get_default(),
2259                                                     DEFAULT_CLIPBOARD);
2260 }
2261
2262 /*
2263  * Because calling gtk_clipboard_set_with_data triggers a call to the
2264  * clipboard_clear function from the last time, we need to arrange a
2265  * way to distinguish a real call to clipboard_clear for the _new_
2266  * instance of the clipboard data from the leftover call for the
2267  * outgoing one. We do this by setting the user data field in our
2268  * gtk_clipboard_set_with_data() call, instead of the obvious pointer
2269  * to 'inst', to one of these.
2270  */
2271 struct clipboard_data_instance {
2272     struct gui_data *inst;
2273     char *pasteout_data_utf8;
2274     int pasteout_data_utf8_len;
2275 };
2276
2277 static void clipboard_provide_data(GtkClipboard *clipboard,
2278                                    GtkSelectionData *selection_data,
2279                                    guint info, gpointer data)
2280 {
2281     struct clipboard_data_instance *cdi =
2282         (struct clipboard_data_instance *)data;
2283     struct gui_data *inst = cdi->inst;
2284
2285     if (inst->current_cdi == cdi) {
2286         gtk_selection_data_set_text(selection_data, cdi->pasteout_data_utf8,
2287                                     cdi->pasteout_data_utf8_len);
2288     }
2289 }
2290
2291 static void clipboard_clear(GtkClipboard *clipboard, gpointer data)
2292 {
2293     struct clipboard_data_instance *cdi =
2294         (struct clipboard_data_instance *)data;
2295     struct gui_data *inst = cdi->inst;
2296
2297     if (inst->current_cdi == cdi) {
2298         term_deselect(inst->term);
2299         inst->current_cdi = NULL;
2300     }
2301     sfree(cdi->pasteout_data_utf8);
2302     sfree(cdi);
2303 }
2304
2305 void write_clip(void *frontend, wchar_t *data, int *attr, int len,
2306                 int must_deselect)
2307 {
2308     struct gui_data *inst = (struct gui_data *)frontend;
2309     struct clipboard_data_instance *cdi;
2310
2311     if (inst->direct_to_font) {
2312         /* In this clipboard mode, we just can't paste if we're in
2313          * direct-to-font mode. Fortunately, that shouldn't be
2314          * important, because we'll only use this clipboard handling
2315          * code on systems where that kind of font doesn't exist
2316          * anyway. */
2317         return;
2318     }
2319
2320     cdi = snew(struct clipboard_data_instance);
2321     cdi->inst = inst;
2322     inst->current_cdi = cdi;
2323     cdi->pasteout_data_utf8 = snewn(len*6, char);
2324     {
2325         const wchar_t *tmp = data;
2326         int tmplen = len;
2327         cdi->pasteout_data_utf8_len =
2328             charset_from_unicode(&tmp, &tmplen, cdi->pasteout_data_utf8,
2329                                  len*6, CS_UTF8, NULL, NULL, 0);
2330     }
2331
2332     /*
2333      * It would be nice to just call gtk_clipboard_set_text() in place
2334      * of all of the faffing below. Unfortunately, that won't give me
2335      * access to the clipboard-clear event, which we use to visually
2336      * deselect text in the terminal.
2337      */
2338     {
2339         GtkTargetList *targetlist;
2340         GtkTargetEntry *targettable;
2341         gint n_targets;
2342
2343         targetlist = gtk_target_list_new(NULL, 0);
2344         gtk_target_list_add_text_targets(targetlist, 0);
2345         targettable = gtk_target_table_new_from_list(targetlist, &n_targets);
2346         gtk_clipboard_set_with_data(inst->clipboard, targettable, n_targets,
2347                                     clipboard_provide_data, clipboard_clear,
2348                                     cdi);
2349         gtk_target_table_free(targettable, n_targets);
2350         gtk_target_list_unref(targetlist);
2351     }
2352 }
2353
2354 static void clipboard_text_received(GtkClipboard *clipboard,
2355                                     const gchar *text, gpointer data)
2356 {
2357     struct gui_data *inst = (struct gui_data *)data;
2358     int length;
2359
2360     if (!text)
2361         return;
2362
2363     length = strlen(text);
2364
2365     if (inst->pastein_data)
2366         sfree(inst->pastein_data);
2367
2368     inst->pastein_data = snewn(length, wchar_t);
2369     inst->pastein_data_len = mb_to_wc(CS_UTF8, 0, text, length,
2370                                       inst->pastein_data, length);
2371
2372     term_do_paste(inst->term);
2373 }
2374
2375 void request_paste(void *frontend)
2376 {
2377     struct gui_data *inst = (struct gui_data *)frontend;
2378     gtk_clipboard_request_text(inst->clipboard, clipboard_text_received, inst);
2379 }
2380
2381 #else /* JUST_USE_GTK_CLIPBOARD_UTF8 */
2382
2383 /* ----------------------------------------------------------------------
2384  * Clipboard handling for X, using the low-level gtk_selection_*
2385  * interface, handling conversions to fiddly things like compound text
2386  * ourselves, and storing in X cut buffers too.
2387  *
2388  * This version of the clipboard code has to be kept around for GTK1,
2389  * which doesn't have the higher-level GtkClipboard interface at all.
2390  * And since it works on GTK2 and GTK3 too and has had a good few
2391  * years of shakedown and bug fixing, we might as well keep using it
2392  * where it's applicable.
2393  *
2394  * It's _possible_ that we might be able to replicate all the
2395  * important wrinkles of this code in GtkClipboard. (In particular,
2396  * cut buffers or local analogue look as if they might be accessible
2397  * via gtk_clipboard_set_can_store(), and delivering text in
2398  * non-Unicode formats only in the direct-to-font case ought to be
2399  * possible if we can figure out the right set of things to put in the
2400  * GtkTargetList.) But that work can wait until there's a need for it!
2401  */
2402
2403 /* Store the data in a cut-buffer. */
2404 static void store_cutbuffer(char * ptr, int len)
2405 {
2406 #ifndef NOT_X_WINDOWS
2407     Display *disp = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
2408     /* ICCCM says we must rotate the buffers before storing to buffer 0. */
2409     XRotateBuffers(disp, 1);
2410     XStoreBytes(disp, ptr, len);
2411 #endif
2412 }
2413
2414 /* Retrieve data from a cut-buffer.
2415  * Returned data needs to be freed with XFree().
2416  */
2417 static char *retrieve_cutbuffer(int *nbytes)
2418 {
2419 #ifndef NOT_X_WINDOWS
2420     Display *disp = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
2421     char * ptr;
2422     ptr = XFetchBytes(disp, nbytes);
2423     if (*nbytes <= 0 && ptr != 0) {
2424         XFree(ptr);
2425         ptr = 0;
2426     }
2427     return ptr;
2428 #else
2429     return NULL;
2430 #endif
2431 }
2432
2433 void write_clip(void *frontend, wchar_t *data, int *attr, int len,
2434                 int must_deselect)
2435 {
2436     struct gui_data *inst = (struct gui_data *)frontend;
2437     if (inst->pasteout_data)
2438         sfree(inst->pasteout_data);
2439     if (inst->pasteout_data_ctext)
2440         sfree(inst->pasteout_data_ctext);
2441     if (inst->pasteout_data_utf8)
2442         sfree(inst->pasteout_data_utf8);
2443
2444     /*
2445      * Set up UTF-8 and compound text paste data. This only happens
2446      * if we aren't in direct-to-font mode using the D800 hack.
2447      */
2448     if (!inst->direct_to_font) {
2449         const wchar_t *tmp = data;
2450         int tmplen = len;
2451 #ifndef NOT_X_WINDOWS
2452         XTextProperty tp;
2453         char *list[1];
2454         Display *disp = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
2455 #endif
2456
2457         inst->pasteout_data_utf8 = snewn(len*6, char);
2458         inst->pasteout_data_utf8_len = len*6;
2459         inst->pasteout_data_utf8_len =
2460             charset_from_unicode(&tmp, &tmplen, inst->pasteout_data_utf8,
2461                                  inst->pasteout_data_utf8_len,
2462                                  CS_UTF8, NULL, NULL, 0);
2463         if (inst->pasteout_data_utf8_len == 0) {
2464             sfree(inst->pasteout_data_utf8);
2465             inst->pasteout_data_utf8 = NULL;
2466         } else {
2467             inst->pasteout_data_utf8 =
2468                 sresize(inst->pasteout_data_utf8,
2469                         inst->pasteout_data_utf8_len + 1, char);
2470             inst->pasteout_data_utf8[inst->pasteout_data_utf8_len] = '\0';
2471         }
2472
2473         /*
2474          * Now let Xlib convert our UTF-8 data into compound text.
2475          */
2476 #ifndef NOT_X_WINDOWS
2477         list[0] = inst->pasteout_data_utf8;
2478         if (Xutf8TextListToTextProperty(disp, list, 1,
2479                                         XCompoundTextStyle, &tp) == 0) {
2480             inst->pasteout_data_ctext = snewn(tp.nitems+1, char);
2481             memcpy(inst->pasteout_data_ctext, tp.value, tp.nitems);
2482             inst->pasteout_data_ctext_len = tp.nitems;
2483             XFree(tp.value);
2484         } else
2485 #endif
2486         {
2487             inst->pasteout_data_ctext = NULL;
2488             inst->pasteout_data_ctext_len = 0;
2489         }
2490     } else {
2491         inst->pasteout_data_utf8 = NULL;
2492         inst->pasteout_data_utf8_len = 0;
2493         inst->pasteout_data_ctext = NULL;
2494         inst->pasteout_data_ctext_len = 0;
2495     }
2496
2497     inst->pasteout_data = snewn(len*6, char);
2498     inst->pasteout_data_len = len*6;
2499     inst->pasteout_data_len = wc_to_mb(inst->ucsdata.line_codepage, 0,
2500                                        data, len, inst->pasteout_data,
2501                                        inst->pasteout_data_len,
2502                                        NULL, NULL, NULL);
2503     if (inst->pasteout_data_len == 0) {
2504         sfree(inst->pasteout_data);
2505         inst->pasteout_data = NULL;
2506     } else {
2507         inst->pasteout_data =
2508             sresize(inst->pasteout_data, inst->pasteout_data_len, char);
2509     }
2510
2511     store_cutbuffer(inst->pasteout_data, inst->pasteout_data_len);
2512
2513     if (gtk_selection_owner_set(inst->area, GDK_SELECTION_PRIMARY,
2514                                 inst->input_event_time)) {
2515 #if GTK_CHECK_VERSION(2,0,0)
2516         gtk_selection_clear_targets(inst->area, GDK_SELECTION_PRIMARY);
2517 #endif
2518         gtk_selection_add_target(inst->area, GDK_SELECTION_PRIMARY,
2519                                  GDK_SELECTION_TYPE_STRING, 1);
2520         if (inst->pasteout_data_ctext)
2521             gtk_selection_add_target(inst->area, GDK_SELECTION_PRIMARY,
2522                                      compound_text_atom, 1);
2523         if (inst->pasteout_data_utf8)
2524             gtk_selection_add_target(inst->area, GDK_SELECTION_PRIMARY,
2525                                      utf8_string_atom, 1);
2526     }
2527
2528     if (must_deselect)
2529         term_deselect(inst->term);
2530 }
2531
2532 static void selection_get(GtkWidget *widget, GtkSelectionData *seldata,
2533                           guint info, guint time_stamp, gpointer data)
2534 {
2535     struct gui_data *inst = (struct gui_data *)data;
2536     GdkAtom target = gtk_selection_data_get_target(seldata);
2537     if (target == utf8_string_atom)
2538         gtk_selection_data_set(seldata, target, 8,
2539                                (unsigned char *)inst->pasteout_data_utf8,
2540                                inst->pasteout_data_utf8_len);
2541     else if (target == compound_text_atom)
2542         gtk_selection_data_set(seldata, target, 8,
2543                                (unsigned char *)inst->pasteout_data_ctext,
2544                                inst->pasteout_data_ctext_len);
2545     else
2546         gtk_selection_data_set(seldata, target, 8,
2547                                (unsigned char *)inst->pasteout_data,
2548                                inst->pasteout_data_len);
2549 }
2550
2551 static gint selection_clear(GtkWidget *widget, GdkEventSelection *seldata,
2552                             gpointer data)
2553 {
2554     struct gui_data *inst = (struct gui_data *)data;
2555
2556     term_deselect(inst->term);
2557     if (inst->pasteout_data)
2558         sfree(inst->pasteout_data);
2559     if (inst->pasteout_data_ctext)
2560         sfree(inst->pasteout_data_ctext);
2561     if (inst->pasteout_data_utf8)
2562         sfree(inst->pasteout_data_utf8);
2563     inst->pasteout_data = NULL;
2564     inst->pasteout_data_len = 0;
2565     inst->pasteout_data_ctext = NULL;
2566     inst->pasteout_data_ctext_len = 0;
2567     inst->pasteout_data_utf8 = NULL;
2568     inst->pasteout_data_utf8_len = 0;
2569     return TRUE;
2570 }
2571
2572 void request_paste(void *frontend)
2573 {
2574     struct gui_data *inst = (struct gui_data *)frontend;
2575     /*
2576      * In Unix, pasting is asynchronous: all we can do at the
2577      * moment is to call gtk_selection_convert(), and when the data
2578      * comes back _then_ we can call term_do_paste().
2579      */
2580
2581     if (!inst->direct_to_font) {
2582         /*
2583          * First we attempt to retrieve the selection as a UTF-8
2584          * string (which we will convert to the correct code page
2585          * before sending to the session, of course). If that
2586          * fails, selection_received() will be informed and will
2587          * fall back to an ordinary string.
2588          */
2589         gtk_selection_convert(inst->area, GDK_SELECTION_PRIMARY,
2590                               utf8_string_atom,
2591                               inst->input_event_time);
2592     } else {
2593         /*
2594          * If we're in direct-to-font mode, we disable UTF-8
2595          * pasting, and go straight to ordinary string data.
2596          */
2597         gtk_selection_convert(inst->area, GDK_SELECTION_PRIMARY,
2598                               GDK_SELECTION_TYPE_STRING,
2599                               inst->input_event_time);
2600     }
2601 }
2602
2603 static void selection_received(GtkWidget *widget, GtkSelectionData *seldata,
2604                                guint time, gpointer data)
2605 {
2606     struct gui_data *inst = (struct gui_data *)data;
2607     char *text;
2608     int length;
2609 #ifndef NOT_X_WINDOWS
2610     char **list;
2611     int free_list_required = 0;
2612     int free_required = 0;
2613 #endif
2614     int charset;
2615     GdkAtom seldata_target = gtk_selection_data_get_target(seldata);
2616     GdkAtom seldata_type = gtk_selection_data_get_data_type(seldata);
2617     const guchar *seldata_data = gtk_selection_data_get_data(seldata);
2618     gint seldata_length = gtk_selection_data_get_length(seldata);
2619
2620     if (seldata_target == utf8_string_atom && seldata_length <= 0) {
2621         /*
2622          * Failed to get a UTF-8 selection string. Try compound
2623          * text next.
2624          */
2625         gtk_selection_convert(inst->area, GDK_SELECTION_PRIMARY,
2626                               compound_text_atom,
2627                               inst->input_event_time);
2628         return;
2629     }
2630
2631     if (seldata_target == compound_text_atom && seldata_length <= 0) {
2632         /*
2633          * Failed to get UTF-8 or compound text. Try an ordinary
2634          * string.
2635          */
2636         gtk_selection_convert(inst->area, GDK_SELECTION_PRIMARY,
2637                               GDK_SELECTION_TYPE_STRING,
2638                               inst->input_event_time);
2639         return;
2640     }
2641
2642     /*
2643      * If we have data, but it's not of a type we can deal with,
2644      * we have to ignore the data.
2645      */
2646     if (seldata_length > 0 &&
2647         seldata_type != GDK_SELECTION_TYPE_STRING &&
2648         seldata_type != compound_text_atom &&
2649         seldata_type != utf8_string_atom)
2650         return;
2651
2652     /*
2653      * If we have no data, try looking in a cut buffer.
2654      */
2655     if (seldata_length <= 0) {
2656 #ifndef NOT_X_WINDOWS
2657         text = retrieve_cutbuffer(&length);
2658         if (length == 0)
2659             return;
2660         /* Xterm is rumoured to expect Latin-1, though I havn't checked the
2661          * source, so use that as a de-facto standard. */
2662         charset = CS_ISO8859_1;
2663         free_required = 1;
2664 #else
2665         return;
2666 #endif
2667     } else {
2668         /*
2669          * Convert COMPOUND_TEXT into UTF-8.
2670          */
2671         if (seldata_type == compound_text_atom) {
2672 #ifndef NOT_X_WINDOWS
2673             XTextProperty tp;
2674             int ret, count;
2675             Display *disp = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
2676
2677             tp.value = (unsigned char *)seldata_data;
2678             tp.encoding = (Atom) seldata_type;
2679             tp.format = gtk_selection_data_get_format(seldata);
2680             tp.nitems = seldata_length;
2681             ret = Xutf8TextPropertyToTextList(disp, &tp, &list, &count);
2682             if (ret == 0 && count == 1) {
2683                 text = list[0];
2684                 length = strlen(list[0]);
2685                 charset = CS_UTF8;
2686                 free_list_required = 1;
2687             } else
2688 #endif
2689             {
2690                 /*
2691                  * Compound text failed; fall back to STRING.
2692                  */
2693                 gtk_selection_convert(inst->area, GDK_SELECTION_PRIMARY,
2694                                       GDK_SELECTION_TYPE_STRING,
2695                                       inst->input_event_time);
2696                 return;
2697             }
2698         } else {
2699             text = (char *)seldata_data;
2700             length = seldata_length;
2701             charset = (seldata_type == utf8_string_atom ?
2702                        CS_UTF8 : inst->ucsdata.line_codepage);
2703         }
2704     }
2705
2706     if (inst->pastein_data)
2707         sfree(inst->pastein_data);
2708
2709     inst->pastein_data = snewn(length, wchar_t);
2710     inst->pastein_data_len = length;
2711     inst->pastein_data_len =
2712         mb_to_wc(charset, 0, text, length,
2713                  inst->pastein_data, inst->pastein_data_len);
2714
2715     term_do_paste(inst->term);
2716
2717 #ifndef NOT_X_WINDOWS
2718     if (free_list_required)
2719         XFreeStringList(list);
2720     if (free_required)
2721         XFree(text);
2722 #endif
2723 }
2724
2725 void init_clipboard(struct gui_data *inst)
2726 {
2727 #ifndef NOT_X_WINDOWS
2728     /*
2729      * Ensure that all the cut buffers exist - according to the ICCCM,
2730      * we must do this before we start using cut buffers.
2731      */
2732     unsigned char empty[] = "";
2733     Display *disp = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
2734     x11_ignore_error(disp, BadMatch);
2735     XChangeProperty(disp, GDK_ROOT_WINDOW(),
2736                     XA_CUT_BUFFER0, XA_STRING, 8, PropModeAppend, empty, 0);
2737     x11_ignore_error(disp, BadMatch);
2738     XChangeProperty(disp, GDK_ROOT_WINDOW(),
2739                     XA_CUT_BUFFER1, XA_STRING, 8, PropModeAppend, empty, 0);
2740     x11_ignore_error(disp, BadMatch);
2741     XChangeProperty(disp, GDK_ROOT_WINDOW(),
2742                     XA_CUT_BUFFER2, XA_STRING, 8, PropModeAppend, empty, 0);
2743     x11_ignore_error(disp, BadMatch);
2744     XChangeProperty(disp, GDK_ROOT_WINDOW(),
2745                     XA_CUT_BUFFER3, XA_STRING, 8, PropModeAppend, empty, 0);
2746     x11_ignore_error(disp, BadMatch);
2747     XChangeProperty(disp, GDK_ROOT_WINDOW(),
2748                     XA_CUT_BUFFER4, XA_STRING, 8, PropModeAppend, empty, 0);
2749     x11_ignore_error(disp, BadMatch);
2750     XChangeProperty(disp, GDK_ROOT_WINDOW(),
2751                     XA_CUT_BUFFER5, XA_STRING, 8, PropModeAppend, empty, 0);
2752     x11_ignore_error(disp, BadMatch);
2753     XChangeProperty(disp, GDK_ROOT_WINDOW(),
2754                     XA_CUT_BUFFER6, XA_STRING, 8, PropModeAppend, empty, 0);
2755     x11_ignore_error(disp, BadMatch);
2756     XChangeProperty(disp, GDK_ROOT_WINDOW(),
2757                     XA_CUT_BUFFER7, XA_STRING, 8, PropModeAppend, empty, 0);
2758 #endif
2759
2760     g_signal_connect(G_OBJECT(inst->area), "selection_received",
2761                      G_CALLBACK(selection_received), inst);
2762     g_signal_connect(G_OBJECT(inst->area), "selection_get",
2763                      G_CALLBACK(selection_get), inst);
2764     g_signal_connect(G_OBJECT(inst->area), "selection_clear_event",
2765                      G_CALLBACK(selection_clear), inst);
2766 }
2767
2768 /*
2769  * End of selection/clipboard handling.
2770  * ----------------------------------------------------------------------
2771  */
2772
2773 #endif /* JUST_USE_GTK_CLIPBOARD_UTF8 */
2774
2775 void get_clip(void *frontend, wchar_t ** p, int *len)
2776 {
2777     struct gui_data *inst = (struct gui_data *)frontend;
2778
2779     if (p) {
2780         *p = inst->pastein_data;
2781         *len = inst->pastein_data_len;
2782     }
2783 }
2784
2785 static void set_window_titles(struct gui_data *inst)
2786 {
2787     /*
2788      * We must always call set_icon_name after calling set_title,
2789      * since set_title will write both names. Irritating, but such
2790      * is life.
2791      */
2792     gtk_window_set_title(GTK_WINDOW(inst->window), inst->wintitle);
2793     if (!conf_get_int(inst->conf, CONF_win_name_always))
2794         gdk_window_set_icon_name(gtk_widget_get_window(inst->window),
2795                                  inst->icontitle);
2796 }
2797
2798 void set_title(void *frontend, char *title)
2799 {
2800     struct gui_data *inst = (struct gui_data *)frontend;
2801     sfree(inst->wintitle);
2802     inst->wintitle = dupstr(title);
2803     set_window_titles(inst);
2804 }
2805
2806 void set_icon(void *frontend, char *title)
2807 {
2808     struct gui_data *inst = (struct gui_data *)frontend;
2809     sfree(inst->icontitle);
2810     inst->icontitle = dupstr(title);
2811     set_window_titles(inst);
2812 }
2813
2814 void set_title_and_icon(void *frontend, char *title, char *icon)
2815 {
2816     struct gui_data *inst = (struct gui_data *)frontend;
2817     sfree(inst->wintitle);
2818     inst->wintitle = dupstr(title);
2819     sfree(inst->icontitle);
2820     inst->icontitle = dupstr(icon);
2821     set_window_titles(inst);
2822 }
2823
2824 void set_sbar(void *frontend, int total, int start, int page)
2825 {
2826     struct gui_data *inst = (struct gui_data *)frontend;
2827     if (!conf_get_int(inst->conf, CONF_scrollbar))
2828         return;
2829     gtk_adjustment_set_lower(inst->sbar_adjust, 0);
2830     gtk_adjustment_set_upper(inst->sbar_adjust, total);
2831     gtk_adjustment_set_value(inst->sbar_adjust, start);
2832     gtk_adjustment_set_page_size(inst->sbar_adjust, page);
2833     gtk_adjustment_set_step_increment(inst->sbar_adjust, 1);
2834     gtk_adjustment_set_page_increment(inst->sbar_adjust, page/2);
2835     inst->ignore_sbar = TRUE;
2836 #if !GTK_CHECK_VERSION(3,18,0)
2837     gtk_adjustment_changed(inst->sbar_adjust);
2838 #endif
2839     inst->ignore_sbar = FALSE;
2840 }
2841
2842 void scrollbar_moved(GtkAdjustment *adj, gpointer data)
2843 {
2844     struct gui_data *inst = (struct gui_data *)data;
2845
2846     if (!conf_get_int(inst->conf, CONF_scrollbar))
2847         return;
2848     if (!inst->ignore_sbar)
2849         term_scroll(inst->term, 1, (int)gtk_adjustment_get_value(adj));
2850 }
2851
2852 static void show_scrollbar(struct gui_data *inst, gboolean visible)
2853 {
2854     inst->sbar_visible = visible;
2855     if (visible)
2856         gtk_widget_show(inst->sbar);
2857     else
2858         gtk_widget_hide(inst->sbar);
2859 }
2860
2861 void sys_cursor(void *frontend, int x, int y)
2862 {
2863     /*
2864      * This is meaningless under X.
2865      */
2866 }
2867
2868 /*
2869  * This is still called when mode==BELL_VISUAL, even though the
2870  * visual bell is handled entirely within terminal.c, because we
2871  * may want to perform additional actions on any kind of bell (for
2872  * example, taskbar flashing in Windows).
2873  */
2874 void do_beep(void *frontend, int mode)
2875 {
2876     if (mode == BELL_DEFAULT)
2877         gdk_beep();
2878 }
2879
2880 int char_width(Context ctx, int uc)
2881 {
2882     /*
2883      * In this front end, double-width characters are handled using a
2884      * separate font, so this can safely just return 1 always.
2885      */
2886     return 1;
2887 }
2888
2889 Context get_ctx(void *frontend)
2890 {
2891     struct gui_data *inst = (struct gui_data *)frontend;
2892     struct draw_ctx *dctx;
2893
2894     if (!gtk_widget_get_window(inst->area))
2895         return NULL;
2896
2897     dctx = snew(struct draw_ctx);
2898     dctx->inst = inst;
2899     dctx->uctx.type = inst->drawtype;
2900 #ifdef DRAW_TEXT_GDK
2901     if (dctx->uctx.type == DRAWTYPE_GDK) {
2902         /* If we're doing GDK-based drawing, then we also expect
2903          * inst->pixmap to exist. */
2904         dctx->uctx.u.gdk.target = inst->pixmap;
2905         dctx->uctx.u.gdk.gc = gdk_gc_new(gtk_widget_get_window(inst->area));
2906     }
2907 #endif
2908 #ifdef DRAW_TEXT_CAIRO
2909     if (dctx->uctx.type == DRAWTYPE_CAIRO) {
2910         dctx->uctx.u.cairo.widget = GTK_WIDGET(inst->area);
2911         /* If we're doing Cairo drawing, we expect inst->surface to
2912          * exist, and we draw to that first, regardless of whether we
2913          * subsequently copy the results to inst->pixmap. */
2914         dctx->uctx.u.cairo.cr = cairo_create(inst->surface);
2915         cairo_setup_dctx(dctx);
2916     }
2917 #endif
2918     return dctx;
2919 }
2920
2921 void free_ctx(Context ctx)
2922 {
2923     struct draw_ctx *dctx = (struct draw_ctx *)ctx;
2924     /* struct gui_data *inst = dctx->inst; */
2925 #ifdef DRAW_TEXT_GDK
2926     if (dctx->uctx.type == DRAWTYPE_GDK) {
2927         gdk_gc_unref(dctx->uctx.u.gdk.gc);
2928     }
2929 #endif
2930 #ifdef DRAW_TEXT_CAIRO
2931     if (dctx->uctx.type == DRAWTYPE_CAIRO) {
2932         cairo_destroy(dctx->uctx.u.cairo.cr);
2933     }
2934 #endif
2935     sfree(dctx);
2936 }
2937
2938
2939 static void draw_update(struct draw_ctx *dctx, int x, int y, int w, int h)
2940 {
2941 #if defined DRAW_TEXT_CAIRO && !defined NO_BACKING_PIXMAPS
2942     if (dctx->uctx.type == DRAWTYPE_CAIRO) {
2943         /*
2944          * If inst->surface and inst->pixmap both exist, then we've
2945          * just drawn new content to the former which we must copy to
2946          * the latter.
2947          */
2948         cairo_t *cr = gdk_cairo_create(dctx->inst->pixmap);
2949         cairo_set_source_surface(cr, dctx->inst->surface, 0, 0);
2950         cairo_rectangle(cr, x, y, w, h);
2951         cairo_fill(cr);
2952         cairo_destroy(cr);
2953     }
2954 #endif
2955
2956     /*
2957      * Now we just queue a window redraw, which will cause
2958      * inst->surface or inst->pixmap (whichever is appropriate for our
2959      * compile mode) to be copied to the real window when we receive
2960      * the resulting "expose" or "draw" event.
2961      *
2962      * Amazingly, this one API call is actually valid in all versions
2963      * of GTK :-)
2964      */
2965     gtk_widget_queue_draw_area(dctx->inst->area, x, y, w, h);
2966 }
2967
2968 static void draw_set_colour(struct draw_ctx *dctx, int col)
2969 {
2970 #ifdef DRAW_TEXT_GDK
2971     if (dctx->uctx.type == DRAWTYPE_GDK) {
2972         gdk_gc_set_foreground(dctx->uctx.u.gdk.gc, &dctx->inst->cols[col]);
2973     }
2974 #endif
2975 #ifdef DRAW_TEXT_CAIRO
2976     if (dctx->uctx.type == DRAWTYPE_CAIRO) {
2977         cairo_set_source_rgb(dctx->uctx.u.cairo.cr,
2978                              dctx->inst->cols[col].red / 65535.0,
2979                              dctx->inst->cols[col].green / 65535.0,
2980                              dctx->inst->cols[col].blue / 65535.0);
2981     }
2982 #endif
2983 }
2984
2985 static void draw_rectangle(struct draw_ctx *dctx, int filled,
2986                            int x, int y, int w, int h)
2987 {
2988 #ifdef DRAW_TEXT_GDK
2989     if (dctx->uctx.type == DRAWTYPE_GDK) {
2990         gdk_draw_rectangle(dctx->uctx.u.gdk.target, dctx->uctx.u.gdk.gc,
2991                            filled, x, y, w, h);
2992     }
2993 #endif
2994 #ifdef DRAW_TEXT_CAIRO
2995     if (dctx->uctx.type == DRAWTYPE_CAIRO) {
2996         cairo_new_path(dctx->uctx.u.cairo.cr);
2997         if (filled) {
2998             cairo_rectangle(dctx->uctx.u.cairo.cr, x, y, w, h);
2999             cairo_fill(dctx->uctx.u.cairo.cr);
3000         } else {
3001             cairo_rectangle(dctx->uctx.u.cairo.cr,
3002                             x + 0.5, y + 0.5, w, h);
3003             cairo_close_path(dctx->uctx.u.cairo.cr);
3004             cairo_stroke(dctx->uctx.u.cairo.cr);
3005         }
3006     }
3007 #endif
3008 }
3009
3010 static void draw_clip(struct draw_ctx *dctx, int x, int y, int w, int h)
3011 {
3012 #ifdef DRAW_TEXT_GDK
3013     if (dctx->uctx.type == DRAWTYPE_GDK) {
3014         GdkRectangle r;
3015
3016         r.x = x;
3017         r.y = y;
3018         r.width = w;
3019         r.height = h;
3020
3021         gdk_gc_set_clip_rectangle(dctx->uctx.u.gdk.gc, &r);
3022     }
3023 #endif
3024 #ifdef DRAW_TEXT_CAIRO
3025     if (dctx->uctx.type == DRAWTYPE_CAIRO) {
3026         cairo_reset_clip(dctx->uctx.u.cairo.cr);
3027         cairo_new_path(dctx->uctx.u.cairo.cr);
3028         cairo_rectangle(dctx->uctx.u.cairo.cr, x, y, w, h);
3029         cairo_clip(dctx->uctx.u.cairo.cr);
3030     }
3031 #endif
3032 }
3033
3034 static void draw_point(struct draw_ctx *dctx, int x, int y)
3035 {
3036 #ifdef DRAW_TEXT_GDK
3037     if (dctx->uctx.type == DRAWTYPE_GDK) {
3038         gdk_draw_point(dctx->uctx.u.gdk.target, dctx->uctx.u.gdk.gc, x, y);
3039     }
3040 #endif
3041 #ifdef DRAW_TEXT_CAIRO
3042     if (dctx->uctx.type == DRAWTYPE_CAIRO) {
3043         cairo_new_path(dctx->uctx.u.cairo.cr);
3044         cairo_rectangle(dctx->uctx.u.cairo.cr, x, y, 1, 1);
3045         cairo_fill(dctx->uctx.u.cairo.cr);
3046     }
3047 #endif
3048 }
3049
3050 static void draw_line(struct draw_ctx *dctx, int x0, int y0, int x1, int y1)
3051 {
3052 #ifdef DRAW_TEXT_GDK
3053     if (dctx->uctx.type == DRAWTYPE_GDK) {
3054         gdk_draw_line(dctx->uctx.u.gdk.target, dctx->uctx.u.gdk.gc,
3055                       x0, y0, x1, y1);
3056     }
3057 #endif
3058 #ifdef DRAW_TEXT_CAIRO
3059     if (dctx->uctx.type == DRAWTYPE_CAIRO) {
3060         cairo_new_path(dctx->uctx.u.cairo.cr);
3061         cairo_move_to(dctx->uctx.u.cairo.cr, x0 + 0.5, y0 + 0.5);
3062         cairo_line_to(dctx->uctx.u.cairo.cr, x1 + 0.5, y1 + 0.5);
3063         cairo_stroke(dctx->uctx.u.cairo.cr);
3064     }
3065 #endif
3066 }
3067
3068 static void draw_stretch_before(struct draw_ctx *dctx, int x, int y,
3069                                 int w, int wdouble,
3070                                 int h, int hdouble, int hbothalf)
3071 {
3072 #ifdef DRAW_TEXT_CAIRO
3073     if (dctx->uctx.type == DRAWTYPE_CAIRO) {
3074         cairo_matrix_t matrix;
3075
3076         matrix.xy = 0;
3077         matrix.yx = 0;
3078
3079         if (wdouble) {
3080             matrix.xx = 2;
3081             matrix.x0 = -x;
3082         } else {
3083             matrix.xx = 1;
3084             matrix.x0 = 0;
3085         }
3086
3087         if (hdouble) {
3088             matrix.yy = 2;
3089             if (hbothalf) {
3090                 matrix.y0 = -(y+h);
3091             } else {
3092                 matrix.y0 = -y;
3093             }
3094         } else {
3095             matrix.yy = 1;
3096             matrix.y0 = 0;
3097         }
3098         cairo_transform(dctx->uctx.u.cairo.cr, &matrix);
3099     }
3100 #endif
3101 }
3102
3103 static void draw_stretch_after(struct draw_ctx *dctx, int x, int y,
3104                                int w, int wdouble,
3105                                int h, int hdouble, int hbothalf)
3106 {
3107 #ifdef DRAW_TEXT_GDK
3108 #ifndef NO_BACKING_PIXMAPS
3109     if (dctx->uctx.type == DRAWTYPE_GDK) {
3110         /*
3111          * I can't find any plausible StretchBlt equivalent in the X
3112          * server, so I'm going to do this the slow and painful way.
3113          * This will involve repeated calls to gdk_draw_pixmap() to
3114          * stretch the text horizontally. It's O(N^2) in time and O(N)
3115          * in network bandwidth, but you try thinking of a better way.
3116          * :-(
3117          */
3118         int i;
3119         if (wdouble) {
3120             for (i = 0; i < w; i++) {
3121                 gdk_draw_pixmap(dctx->uctx.u.gdk.target,
3122                                 dctx->uctx.u.gdk.gc,
3123                                 dctx->uctx.u.gdk.target,
3124                                 x + 2*i, y,
3125                                 x + 2*i+1, y,
3126                                 w - i, h);
3127             }
3128             w *= 2;
3129         }
3130
3131         if (hdouble) {
3132             int dt, db;
3133             /* Now stretch vertically, in the same way. */
3134             if (hbothalf)
3135                 dt = 0, db = 1;
3136             else
3137                 dt = 1, db = 0;
3138             for (i = 0; i < h; i += 2) {
3139                 gdk_draw_pixmap(dctx->uctx.u.gdk.target,
3140                                 dctx->uctx.u.gdk.gc,
3141                                 dctx->uctx.u.gdk.target,
3142                                 x, y + dt*i + db,
3143                                 x, y + dt*(i+1),
3144                                 w, h-i-1);
3145             }
3146         }
3147     }
3148 #else
3149 #error No way to implement stretching in GDK without a reliable backing pixmap
3150 #endif
3151 #endif /* DRAW_TEXT_GDK */
3152 #ifdef DRAW_TEXT_CAIRO
3153     if (dctx->uctx.type == DRAWTYPE_CAIRO) {
3154         cairo_set_matrix(dctx->uctx.u.cairo.cr,
3155                          &dctx->uctx.u.cairo.origmatrix);
3156     }
3157 #endif
3158 }
3159
3160 static void draw_backing_rect(struct gui_data *inst)
3161 {
3162     struct draw_ctx *dctx = get_ctx(inst);
3163     int w = inst->width * inst->font_width + 2*inst->window_border;
3164     int h = inst->height * inst->font_height + 2*inst->window_border;
3165     draw_set_colour(dctx, 258);
3166     draw_rectangle(dctx, 1, 0, 0, w, h);
3167     draw_update(dctx, 0, 0, w, h);
3168     free_ctx(dctx);
3169 }
3170
3171 /*
3172  * Draw a line of text in the window, at given character
3173  * coordinates, in given attributes.
3174  *
3175  * We are allowed to fiddle with the contents of `text'.
3176  */
3177 void do_text_internal(Context ctx, int x, int y, wchar_t *text, int len,
3178                       unsigned long attr, int lattr)
3179 {
3180     struct draw_ctx *dctx = (struct draw_ctx *)ctx;
3181     struct gui_data *inst = dctx->inst;
3182     int ncombining;
3183     int nfg, nbg, t, fontid, shadow, rlen, widefactor, bold;
3184     int monochrome =
3185         gdk_visual_get_depth(gtk_widget_get_visual(inst->area)) == 1;
3186
3187     if (attr & TATTR_COMBINING) {
3188         ncombining = len;
3189         len = 1;
3190     } else
3191         ncombining = 1;
3192
3193     nfg = ((monochrome ? ATTR_DEFFG : (attr & ATTR_FGMASK)) >> ATTR_FGSHIFT);
3194     nbg = ((monochrome ? ATTR_DEFBG : (attr & ATTR_BGMASK)) >> ATTR_BGSHIFT);
3195     if (!!(attr & ATTR_REVERSE) ^ (monochrome && (attr & TATTR_ACTCURS))) {
3196         t = nfg;
3197         nfg = nbg;
3198         nbg = t;
3199     }
3200     if ((inst->bold_style & 2) && (attr & ATTR_BOLD)) {
3201         if (nfg < 16) nfg |= 8;
3202         else if (nfg >= 256) nfg |= 1;
3203     }
3204     if ((inst->bold_style & 2) && (attr & ATTR_BLINK)) {
3205         if (nbg < 16) nbg |= 8;
3206         else if (nbg >= 256) nbg |= 1;
3207     }
3208     if ((attr & TATTR_ACTCURS) && !monochrome) {
3209         nfg = 260;
3210         nbg = 261;
3211     }
3212
3213     fontid = shadow = 0;
3214
3215     if (attr & ATTR_WIDE) {
3216         widefactor = 2;
3217         fontid |= 2;
3218     } else {
3219         widefactor = 1;
3220     }
3221
3222     if ((attr & ATTR_BOLD) && (inst->bold_style & 1)) {
3223         bold = 1;
3224         fontid |= 1;
3225     } else {
3226         bold = 0;
3227     }
3228
3229     if (!inst->fonts[fontid]) {
3230         int i;
3231         /*
3232          * Fall back through font ids with subsets of this one's
3233          * set bits, in order.
3234          */
3235         for (i = fontid; i-- > 0 ;) {
3236             if (i & ~fontid)
3237                 continue;              /* some other bit is set */
3238             if (inst->fonts[i]) {
3239                 fontid = i;
3240                 break;
3241             }
3242         }
3243         assert(inst->fonts[fontid]);   /* we should at least have hit zero */
3244     }
3245
3246     if ((lattr & LATTR_MODE) != LATTR_NORM) {
3247         x *= 2;
3248         if (x >= inst->term->cols)
3249             return;
3250         if (x + len*2*widefactor > inst->term->cols)
3251             len = (inst->term->cols-x)/2/widefactor;/* trim to LH half */
3252         rlen = len * 2;
3253     } else
3254         rlen = len;
3255
3256     draw_clip(dctx,
3257               x*inst->font_width+inst->window_border,
3258               y*inst->font_height+inst->window_border,
3259               rlen*widefactor*inst->font_width,
3260               inst->font_height);
3261
3262     if ((lattr & LATTR_MODE) != LATTR_NORM) {
3263         draw_stretch_before(dctx,
3264                             x*inst->font_width+inst->window_border,
3265                             y*inst->font_height+inst->window_border,
3266                             rlen*widefactor*inst->font_width, TRUE,
3267                             inst->font_height,
3268                             ((lattr & LATTR_MODE) != LATTR_WIDE),
3269                             ((lattr & LATTR_MODE) == LATTR_BOT));
3270     }
3271
3272     draw_set_colour(dctx, nbg);
3273     draw_rectangle(dctx, TRUE,
3274                    x*inst->font_width+inst->window_border,
3275                    y*inst->font_height+inst->window_border,
3276                    rlen*widefactor*inst->font_width, inst->font_height);
3277
3278     draw_set_colour(dctx, nfg);
3279     if (ncombining > 1) {
3280         assert(len == 1);
3281         unifont_draw_combining(&dctx->uctx, inst->fonts[fontid],
3282                                x*inst->font_width+inst->window_border,
3283                                (y*inst->font_height+inst->window_border+
3284                                 inst->fonts[0]->ascent),
3285                                text, ncombining, widefactor > 1,
3286                                bold, inst->font_width);
3287     } else {
3288         unifont_draw_text(&dctx->uctx, inst->fonts[fontid],
3289                           x*inst->font_width+inst->window_border,
3290                           (y*inst->font_height+inst->window_border+
3291                            inst->fonts[0]->ascent),
3292                           text, len, widefactor > 1,
3293                           bold, inst->font_width);
3294     }
3295
3296     if (attr & ATTR_UNDER) {
3297         int uheight = inst->fonts[0]->ascent + 1;
3298         if (uheight >= inst->font_height)
3299             uheight = inst->font_height - 1;
3300         draw_line(dctx, x*inst->font_width+inst->window_border,
3301                   y*inst->font_height + uheight + inst->window_border,
3302                   (x+len)*widefactor*inst->font_width-1+inst->window_border,
3303                   y*inst->font_height + uheight + inst->window_border);
3304     }
3305
3306     if ((lattr & LATTR_MODE) != LATTR_NORM) {
3307         draw_stretch_after(dctx,
3308                            x*inst->font_width+inst->window_border,
3309                            y*inst->font_height+inst->window_border,
3310                            rlen*widefactor*inst->font_width, TRUE,
3311                            inst->font_height,
3312                            ((lattr & LATTR_MODE) != LATTR_WIDE),
3313                            ((lattr & LATTR_MODE) == LATTR_BOT));
3314     }
3315 }
3316
3317 void do_text(Context ctx, int x, int y, wchar_t *text, int len,
3318              unsigned long attr, int lattr)
3319 {
3320     struct draw_ctx *dctx = (struct draw_ctx *)ctx;
3321     struct gui_data *inst = dctx->inst;
3322     int widefactor;
3323
3324     do_text_internal(ctx, x, y, text, len, attr, lattr);
3325
3326     if (attr & ATTR_WIDE) {
3327         widefactor = 2;
3328     } else {
3329         widefactor = 1;
3330     }
3331
3332     if ((lattr & LATTR_MODE) != LATTR_NORM) {
3333         x *= 2;
3334         if (x >= inst->term->cols)
3335             return;
3336         if (x + len*2*widefactor > inst->term->cols)
3337             len = (inst->term->cols-x)/2/widefactor;/* trim to LH half */
3338         len *= 2;
3339     }
3340
3341     draw_update(dctx,
3342                 x*inst->font_width+inst->window_border,
3343                 y*inst->font_height+inst->window_border,
3344                 len*widefactor*inst->font_width, inst->font_height);
3345 }
3346
3347 void do_cursor(Context ctx, int x, int y, wchar_t *text, int len,
3348                unsigned long attr, int lattr)
3349 {
3350     struct draw_ctx *dctx = (struct draw_ctx *)ctx;
3351     struct gui_data *inst = dctx->inst;
3352
3353     int active, passive, widefactor;
3354
3355     if (attr & TATTR_PASCURS) {
3356         attr &= ~TATTR_PASCURS;
3357         passive = 1;
3358     } else
3359         passive = 0;
3360     if ((attr & TATTR_ACTCURS) && inst->cursor_type != 0) {
3361         attr &= ~TATTR_ACTCURS;
3362         active = 1;
3363     } else
3364         active = 0;
3365     do_text_internal(ctx, x, y, text, len, attr, lattr);
3366
3367     if (attr & TATTR_COMBINING)
3368         len = 1;
3369
3370     if (attr & ATTR_WIDE) {
3371         widefactor = 2;
3372     } else {
3373         widefactor = 1;
3374     }
3375
3376     if ((lattr & LATTR_MODE) != LATTR_NORM) {
3377         x *= 2;
3378         if (x >= inst->term->cols)
3379             return;
3380         if (x + len*2*widefactor > inst->term->cols)
3381             len = (inst->term->cols-x)/2/widefactor;/* trim to LH half */
3382         len *= 2;
3383     }
3384
3385     if (inst->cursor_type == 0) {
3386         /*
3387          * An active block cursor will already have been done by
3388          * the above do_text call, so we only need to do anything
3389          * if it's passive.
3390          */
3391         if (passive) {
3392             draw_set_colour(dctx, 261);
3393             draw_rectangle(dctx, FALSE,
3394                            x*inst->font_width+inst->window_border,
3395                            y*inst->font_height+inst->window_border,
3396                            len*widefactor*inst->font_width-1,
3397                            inst->font_height-1);
3398         }
3399     } else {
3400         int uheight;
3401         int startx, starty, dx, dy, length, i;
3402
3403         int char_width;
3404
3405         if ((attr & ATTR_WIDE) || (lattr & LATTR_MODE) != LATTR_NORM)
3406             char_width = 2*inst->font_width;
3407         else
3408             char_width = inst->font_width;
3409
3410         if (inst->cursor_type == 1) {
3411             uheight = inst->fonts[0]->ascent + 1;
3412             if (uheight >= inst->font_height)
3413                 uheight = inst->font_height - 1;
3414
3415             startx = x * inst->font_width + inst->window_border;
3416             starty = y * inst->font_height + inst->window_border + uheight;
3417             dx = 1;
3418             dy = 0;
3419             length = len * widefactor * char_width;
3420         } else {
3421             int xadjust = 0;
3422             if (attr & TATTR_RIGHTCURS)
3423                 xadjust = char_width - 1;
3424             startx = x * inst->font_width + inst->window_border + xadjust;
3425             starty = y * inst->font_height + inst->window_border;
3426             dx = 0;
3427             dy = 1;
3428             length = inst->font_height;
3429         }
3430
3431         draw_set_colour(dctx, 261);
3432         if (passive) {
3433             for (i = 0; i < length; i++) {
3434                 if (i % 2 == 0) {
3435                     draw_point(dctx, startx, starty);
3436                 }
3437                 startx += dx;
3438                 starty += dy;
3439             }
3440         } else if (active) {
3441             draw_line(dctx, startx, starty,
3442                       startx + (length-1) * dx, starty + (length-1) * dy);
3443         } /* else no cursor (e.g., blinked off) */
3444     }
3445
3446     draw_update(dctx,
3447                 x*inst->font_width+inst->window_border,
3448                 y*inst->font_height+inst->window_border,
3449                 len*widefactor*inst->font_width, inst->font_height);
3450
3451 #if GTK_CHECK_VERSION(2,0,0)
3452     {
3453         GdkRectangle cursorrect;
3454         cursorrect.x = x*inst->font_width+inst->window_border;
3455         cursorrect.y = y*inst->font_height+inst->window_border;
3456         cursorrect.width = len*widefactor*inst->font_width;
3457         cursorrect.height = inst->font_height;
3458         gtk_im_context_set_cursor_location(inst->imc, &cursorrect);
3459     }
3460 #endif
3461 }
3462
3463 GdkCursor *make_mouse_ptr(struct gui_data *inst, int cursor_val)
3464 {
3465     if (cursor_val == -1) {
3466 #if GTK_CHECK_VERSION(2,16,0)
3467         cursor_val = GDK_BLANK_CURSOR;
3468 #else
3469         /*
3470          * Work around absence of GDK_BLANK_CURSOR by inventing a
3471          * blank pixmap.
3472          */
3473         GdkCursor *ret;
3474         GdkColor bg = { 0, 0, 0, 0 };
3475         GdkPixmap *pm = gdk_pixmap_new(NULL, 1, 1, 1);
3476         GdkGC *gc = gdk_gc_new(pm);
3477         gdk_gc_set_foreground(gc, &bg);
3478         gdk_draw_rectangle(pm, gc, 1, 0, 0, 1, 1);
3479         gdk_gc_unref(gc);
3480         ret = gdk_cursor_new_from_pixmap(pm, pm, &bg, &bg, 1, 1);
3481         gdk_pixmap_unref(pm);
3482         return ret;
3483 #endif
3484     }
3485
3486     return gdk_cursor_new(cursor_val);
3487 }
3488
3489 void modalfatalbox(const char *p, ...)
3490 {
3491     va_list ap;
3492     fprintf(stderr, "FATAL ERROR: ");
3493     va_start(ap, p);
3494     vfprintf(stderr, p, ap);
3495     va_end(ap);
3496     fputc('\n', stderr);
3497     exit(1);
3498 }
3499
3500 void cmdline_error(const char *p, ...)
3501 {
3502     va_list ap;
3503     fprintf(stderr, "%s: ", appname);
3504     va_start(ap, p);
3505     vfprintf(stderr, p, ap);
3506     va_end(ap);
3507     fputc('\n', stderr);
3508     exit(1);
3509 }
3510
3511 const char *get_x_display(void *frontend)
3512 {
3513     return gdk_get_display();
3514 }
3515
3516 #ifndef NOT_X_WINDOWS
3517 long get_windowid(void *frontend)
3518 {
3519     struct gui_data *inst = (struct gui_data *)frontend;
3520     return (long)GDK_WINDOW_XID(gtk_widget_get_window(inst->area));
3521 }
3522 #endif
3523
3524 int frontend_is_utf8(void *frontend)
3525 {
3526     struct gui_data *inst = (struct gui_data *)frontend;
3527     return inst->ucsdata.line_codepage == CS_UTF8;
3528 }
3529
3530 char *setup_fonts_ucs(struct gui_data *inst)
3531 {
3532     int shadowbold = conf_get_int(inst->conf, CONF_shadowbold);
3533     int shadowboldoffset = conf_get_int(inst->conf, CONF_shadowboldoffset);
3534     FontSpec *fs;
3535     unifont *fonts[4];
3536     int i;
3537
3538     fs = conf_get_fontspec(inst->conf, CONF_font);
3539     fonts[0] = multifont_create(inst->area, fs->name, FALSE, FALSE,
3540                                 shadowboldoffset, shadowbold);
3541     if (!fonts[0]) {
3542         return dupprintf("unable to load font \"%s\"", fs->name);
3543     }
3544
3545     fs = conf_get_fontspec(inst->conf, CONF_boldfont);
3546     if (shadowbold || !fs->name[0]) {
3547         fonts[1] = NULL;
3548     } else {
3549         fonts[1] = multifont_create(inst->area, fs->name, FALSE, TRUE,
3550                                     shadowboldoffset, shadowbold);
3551         if (!fonts[1]) {
3552             if (fonts[0])
3553                 unifont_destroy(fonts[0]);
3554             return dupprintf("unable to load bold font \"%s\"", fs->name);
3555         }
3556     }
3557
3558     fs = conf_get_fontspec(inst->conf, CONF_widefont);
3559     if (fs->name[0]) {
3560         fonts[2] = multifont_create(inst->area, fs->name, TRUE, FALSE,
3561                                     shadowboldoffset, shadowbold);
3562         if (!fonts[2]) {
3563             for (i = 0; i < 2; i++)
3564                 if (fonts[i])
3565                     unifont_destroy(fonts[i]);
3566             return dupprintf("unable to load wide font \"%s\"", fs->name);
3567         }
3568     } else {
3569         fonts[2] = NULL;
3570     }
3571
3572     fs = conf_get_fontspec(inst->conf, CONF_wideboldfont);
3573     if (shadowbold || !fs->name[0]) {
3574         fonts[3] = NULL;
3575     } else {
3576         fonts[3] = multifont_create(inst->area, fs->name, TRUE, TRUE,
3577                                     shadowboldoffset, shadowbold);
3578         if (!fonts[3]) {
3579             for (i = 0; i < 3; i++)
3580                 if (fonts[i])
3581                     unifont_destroy(fonts[i]);
3582             return dupprintf("unable to load wide bold font \"%s\"", fs->name);
3583         }
3584     }
3585
3586     /*
3587      * Now we've got past all the possible error conditions, we can
3588      * actually update our state.
3589      */
3590
3591     for (i = 0; i < 4; i++) {
3592         if (inst->fonts[i])
3593             unifont_destroy(inst->fonts[i]);
3594         inst->fonts[i] = fonts[i];
3595     }
3596
3597     inst->font_width = inst->fonts[0]->width;
3598     inst->font_height = inst->fonts[0]->height;
3599
3600     inst->direct_to_font = init_ucs(&inst->ucsdata,
3601                                     conf_get_str(inst->conf, CONF_line_codepage),
3602                                     conf_get_int(inst->conf, CONF_utf8_override),
3603                                     inst->fonts[0]->public_charset,
3604                                     conf_get_int(inst->conf, CONF_vtmode));
3605
3606     inst->drawtype = inst->fonts[0]->preferred_drawtype;
3607
3608     return NULL;
3609 }
3610
3611 void set_geom_hints(struct gui_data *inst)
3612 {
3613     GdkGeometry geom;
3614     gint flags;
3615
3616     /*
3617      * Unused fields in geom.
3618      */
3619     geom.max_width = geom.max_height = -1;
3620     geom.min_aspect = geom.max_aspect = 0;
3621
3622     /*
3623      * Set up the geometry fields we care about, with reference to
3624      * just the drawing area. We'll correct for the scrollbar in a
3625      * moment.
3626      */
3627     flags = GDK_HINT_MIN_SIZE | GDK_HINT_BASE_SIZE | GDK_HINT_RESIZE_INC;
3628     geom.min_width = inst->font_width + 2*inst->window_border;
3629     geom.min_height = inst->font_height + 2*inst->window_border;
3630     geom.base_width = 2*inst->window_border;
3631     geom.base_height = 2*inst->window_border;
3632     geom.width_inc = inst->font_width;
3633     geom.height_inc = inst->font_height;
3634
3635     /*
3636      * If we've got a scrollbar visible, then we must include its
3637      * width as part of the base and min width, and also ensure that
3638      * our window's minimum height is at least the height required by
3639      * the scrollbar.
3640      *
3641      * In the latter case, we must also take care to arrange that
3642      * (geom.min_height - geom.base_height) is an integer multiple of
3643      * geom.height_inc, because if it's not, then some window managers
3644      * (we know of xfwm4) get confused, with the effect that they
3645      * resize our window to a height based on min_height instead of
3646      * base_height, which we then round down and the window ends up
3647      * too short.
3648      */
3649     if (inst->sbar_visible) {
3650         GtkRequisition req;
3651         int min_sb_height;
3652
3653 #if GTK_CHECK_VERSION(3,0,0)
3654         gtk_widget_get_preferred_size(inst->sbar, &req, NULL);
3655 #else
3656         gtk_widget_size_request(inst->sbar, &req);
3657 #endif
3658
3659         /* Compute rounded-up scrollbar height. */
3660         min_sb_height = req.height;
3661         min_sb_height += geom.height_inc - 1;
3662         min_sb_height -= ((min_sb_height - geom.base_height % geom.height_inc)
3663                           % geom.height_inc);
3664
3665         geom.min_width += req.width;
3666         geom.base_width += req.width;
3667         if (geom.min_height < min_sb_height)
3668             geom.min_height = min_sb_height;
3669     }
3670
3671     gtk_window_set_geometry_hints(GTK_WINDOW(inst->window),
3672                                   NULL, &geom, flags);
3673 }
3674
3675 void clear_scrollback_menuitem(GtkMenuItem *item, gpointer data)
3676 {
3677     struct gui_data *inst = (struct gui_data *)data;
3678     term_clrsb(inst->term);
3679 }
3680
3681 void reset_terminal_menuitem(GtkMenuItem *item, gpointer data)
3682 {
3683     struct gui_data *inst = (struct gui_data *)data;
3684     term_pwron(inst->term, TRUE);
3685     if (inst->ldisc)
3686         ldisc_echoedit_update(inst->ldisc);
3687 }
3688
3689 void copy_all_menuitem(GtkMenuItem *item, gpointer data)
3690 {
3691     struct gui_data *inst = (struct gui_data *)data;
3692     term_copyall(inst->term);
3693 }
3694
3695 void special_menuitem(GtkMenuItem *item, gpointer data)
3696 {
3697     struct gui_data *inst = (struct gui_data *)data;
3698     int code = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(item),
3699                                                  "user-data"));
3700
3701     if (inst->back)
3702         inst->back->special(inst->backhandle, code);
3703 }
3704
3705 void about_menuitem(GtkMenuItem *item, gpointer data)
3706 {
3707     struct gui_data *inst = (struct gui_data *)data;
3708     about_box(inst->window);
3709 }
3710
3711 void event_log_menuitem(GtkMenuItem *item, gpointer data)
3712 {
3713     struct gui_data *inst = (struct gui_data *)data;
3714     showeventlog(inst->eventlogstuff, inst->window);
3715 }
3716
3717 void change_settings_menuitem(GtkMenuItem *item, gpointer data)
3718 {
3719     /* This maps colour indices in inst->conf to those used in inst->cols. */
3720     static const int ww[] = {
3721         256, 257, 258, 259, 260, 261,
3722         0, 8, 1, 9, 2, 10, 3, 11,
3723         4, 12, 5, 13, 6, 14, 7, 15
3724     };
3725     struct gui_data *inst = (struct gui_data *)data;
3726     char *title;
3727     Conf *oldconf, *newconf;
3728     int i, j, need_size;
3729
3730     assert(lenof(ww) == NCFGCOLOURS);
3731
3732     if (inst->reconfiguring)
3733       return;
3734     else
3735       inst->reconfiguring = TRUE;
3736
3737     title = dupcat(appname, " Reconfiguration", NULL);
3738
3739     oldconf = inst->conf;
3740     newconf = conf_copy(inst->conf);
3741
3742     if (do_config_box(title, newconf, 1,
3743                       inst->back?inst->back->cfg_info(inst->backhandle):0)) {
3744         inst->conf = newconf;
3745
3746         /* Pass new config data to the logging module */
3747         log_reconfig(inst->logctx, inst->conf);
3748         /*
3749          * Flush the line discipline's edit buffer in the case
3750          * where local editing has just been disabled.
3751          */
3752         if (inst->ldisc) {
3753             ldisc_configure(inst->ldisc, inst->conf);
3754             ldisc_echoedit_update(inst->ldisc);
3755         }
3756         /* Pass new config data to the terminal */
3757         term_reconfig(inst->term, inst->conf);
3758         /* Pass new config data to the back end */
3759         if (inst->back)
3760             inst->back->reconfig(inst->backhandle, inst->conf);
3761
3762         cache_conf_values(inst);
3763
3764         /*
3765          * Just setting inst->conf is sufficient to cause colour
3766          * setting changes to appear on the next ESC]R palette
3767          * reset. But we should also check whether any colour
3768          * settings have been changed, and revert the ones that have
3769          * to the new default, on the assumption that the user is
3770          * most likely to want an immediate update.
3771          */
3772         for (i = 0; i < NCFGCOLOURS; i++) {
3773             for (j = 0; j < 3; j++)
3774                 if (conf_get_int_int(oldconf, CONF_colours, i*3+j) !=
3775                     conf_get_int_int(newconf, CONF_colours, i*3+j))
3776                     break;
3777             if (j < 3) {
3778                 real_palette_set(inst, ww[i],
3779                                  conf_get_int_int(newconf,CONF_colours,i*3+0),
3780                                  conf_get_int_int(newconf,CONF_colours,i*3+1),
3781                                  conf_get_int_int(newconf,CONF_colours,i*3+2));
3782
3783                 /*
3784                  * If the default background has changed, we must
3785                  * repaint the space in between the window border
3786                  * and the text area.
3787                  */
3788                 if (ww[i] == 258) {
3789                     set_window_background(inst);
3790                     draw_backing_rect(inst);
3791                 }
3792             }
3793         }
3794
3795         need_size = FALSE;
3796
3797         /*
3798          * If the scrollbar needs to be shown, hidden, or moved
3799          * from one end to the other of the window, do so now.
3800          */
3801         if (conf_get_int(oldconf, CONF_scrollbar) !=
3802             conf_get_int(newconf, CONF_scrollbar)) {
3803             show_scrollbar(inst, conf_get_int(newconf, CONF_scrollbar));
3804             need_size = TRUE;
3805         }
3806         if (conf_get_int(oldconf, CONF_scrollbar_on_left) !=
3807             conf_get_int(newconf, CONF_scrollbar_on_left)) {
3808             gtk_box_reorder_child(inst->hbox, inst->sbar,
3809                                   conf_get_int(newconf, CONF_scrollbar_on_left)
3810                                   ? 0 : 1);
3811         }
3812
3813         /*
3814          * Change the window title, if required.
3815          */
3816         if (strcmp(conf_get_str(oldconf, CONF_wintitle),
3817                    conf_get_str(newconf, CONF_wintitle)))
3818             set_title(inst, conf_get_str(newconf, CONF_wintitle));
3819         set_window_titles(inst);
3820
3821         /*
3822          * Redo the whole tangled fonts and Unicode mess if
3823          * necessary.
3824          */
3825         if (strcmp(conf_get_fontspec(oldconf, CONF_font)->name,
3826                    conf_get_fontspec(newconf, CONF_font)->name) ||
3827             strcmp(conf_get_fontspec(oldconf, CONF_boldfont)->name,
3828                    conf_get_fontspec(newconf, CONF_boldfont)->name) ||
3829             strcmp(conf_get_fontspec(oldconf, CONF_widefont)->name,
3830                    conf_get_fontspec(newconf, CONF_widefont)->name) ||
3831             strcmp(conf_get_fontspec(oldconf, CONF_wideboldfont)->name,
3832                    conf_get_fontspec(newconf, CONF_wideboldfont)->name) ||
3833             strcmp(conf_get_str(oldconf, CONF_line_codepage),
3834                    conf_get_str(newconf, CONF_line_codepage)) ||
3835             conf_get_int(oldconf, CONF_utf8_override) !=
3836             conf_get_int(newconf, CONF_utf8_override) ||
3837             conf_get_int(oldconf, CONF_vtmode) !=
3838             conf_get_int(newconf, CONF_vtmode) ||
3839             conf_get_int(oldconf, CONF_shadowbold) !=
3840             conf_get_int(newconf, CONF_shadowbold) ||
3841             conf_get_int(oldconf, CONF_shadowboldoffset) !=
3842             conf_get_int(newconf, CONF_shadowboldoffset)) {
3843             char *errmsg = setup_fonts_ucs(inst);
3844             if (errmsg) {
3845                 char *msgboxtext =
3846                     dupprintf("Could not change fonts in terminal window: %s\n",
3847                               errmsg);
3848                 messagebox(inst->window, "Font setup error", msgboxtext,
3849                            string_width("Could not change fonts in terminal window:"),
3850                            FALSE, "OK", 'o', +1, 1,
3851                            NULL);
3852                 sfree(msgboxtext);
3853                 sfree(errmsg);
3854             } else {
3855                 need_size = TRUE;
3856             }
3857         }
3858
3859         /*
3860          * Resize the window.
3861          */
3862         if (conf_get_int(oldconf, CONF_width) !=
3863             conf_get_int(newconf, CONF_width) ||
3864             conf_get_int(oldconf, CONF_height) !=
3865             conf_get_int(newconf, CONF_height) ||
3866             conf_get_int(oldconf, CONF_window_border) !=
3867             conf_get_int(newconf, CONF_window_border) ||
3868             need_size) {
3869             set_geom_hints(inst);
3870             request_resize(inst, conf_get_int(newconf, CONF_width),
3871                            conf_get_int(newconf, CONF_height));
3872         } else {
3873             /*
3874              * The above will have caused a call to term_size() for
3875              * us if it happened. If the user has fiddled with only
3876              * the scrollback size, the above will not have
3877              * happened and we will need an explicit term_size()
3878              * here.
3879              */
3880             if (conf_get_int(oldconf, CONF_savelines) !=
3881                 conf_get_int(newconf, CONF_savelines))
3882                 term_size(inst->term, inst->term->rows, inst->term->cols,
3883                           conf_get_int(newconf, CONF_savelines));
3884         }
3885
3886         term_invalidate(inst->term);
3887
3888         /*
3889          * We do an explicit full redraw here to ensure the window
3890          * border has been redrawn as well as the text area.
3891          */
3892         gtk_widget_queue_draw(inst->area);
3893
3894         conf_free(oldconf);
3895     } else {
3896         conf_free(newconf);
3897     }
3898     sfree(title);
3899     inst->reconfiguring = FALSE;
3900 }
3901
3902 void dup_session_menuitem(GtkMenuItem *item, gpointer gdata)
3903 {
3904     struct gui_data *inst = (struct gui_data *)gdata;
3905
3906     launch_duplicate_session(inst->conf);
3907 }
3908
3909 void new_session_menuitem(GtkMenuItem *item, gpointer data)
3910 {
3911     launch_new_session();
3912 }
3913
3914 void restart_session_menuitem(GtkMenuItem *item, gpointer data)
3915 {
3916     struct gui_data *inst = (struct gui_data *)data;
3917
3918     if (!inst->back) {
3919         logevent(inst, "----- Session restarted -----");
3920         term_pwron(inst->term, FALSE);
3921         start_backend(inst);
3922         inst->exited = FALSE;
3923     }
3924 }
3925
3926 void saved_session_menuitem(GtkMenuItem *item, gpointer data)
3927 {
3928     char *str = (char *)g_object_get_data(G_OBJECT(item), "user-data");
3929
3930     launch_saved_session(str);
3931 }
3932
3933 void saved_session_freedata(GtkMenuItem *item, gpointer data)
3934 {
3935     char *str = (char *)g_object_get_data(G_OBJECT(item), "user-data");
3936
3937     sfree(str);
3938 }
3939
3940 static void update_savedsess_menu(GtkMenuItem *menuitem, gpointer data)
3941 {
3942     struct gui_data *inst = (struct gui_data *)data;
3943     struct sesslist sesslist;
3944     int i;
3945
3946     gtk_container_foreach(GTK_CONTAINER(inst->sessionsmenu),
3947                           (GtkCallback)gtk_widget_destroy, NULL);
3948
3949     get_sesslist(&sesslist, TRUE);
3950     /* skip sesslist.sessions[0] == Default Settings */
3951     for (i = 1; i < sesslist.nsessions; i++) {
3952         GtkWidget *menuitem =
3953             gtk_menu_item_new_with_label(sesslist.sessions[i]);
3954         gtk_container_add(GTK_CONTAINER(inst->sessionsmenu), menuitem);
3955         gtk_widget_show(menuitem);
3956         g_object_set_data(G_OBJECT(menuitem), "user-data",
3957                           dupstr(sesslist.sessions[i]));
3958         g_signal_connect(G_OBJECT(menuitem), "activate",
3959                          G_CALLBACK(saved_session_menuitem),
3960                          inst);
3961         g_signal_connect(G_OBJECT(menuitem), "destroy",
3962                          G_CALLBACK(saved_session_freedata),
3963                          inst);
3964     }
3965     if (sesslist.nsessions <= 1) {
3966         GtkWidget *menuitem =
3967             gtk_menu_item_new_with_label("(No sessions)");
3968         gtk_widget_set_sensitive(menuitem, FALSE);
3969         gtk_container_add(GTK_CONTAINER(inst->sessionsmenu), menuitem);
3970         gtk_widget_show(menuitem);
3971     }
3972     get_sesslist(&sesslist, FALSE); /* free up */
3973 }
3974
3975 void set_window_icon(GtkWidget *window, const char *const *const *icon,
3976                      int n_icon)
3977 {
3978 #if GTK_CHECK_VERSION(2,0,0)
3979     GList *iconlist;
3980     int n;
3981 #else
3982     GdkPixmap *iconpm;
3983     GdkBitmap *iconmask;
3984 #endif
3985
3986     if (!n_icon)
3987         return;
3988
3989     gtk_widget_realize(window);
3990 #if GTK_CHECK_VERSION(2,0,0)
3991     gtk_window_set_icon(GTK_WINDOW(window),
3992                         gdk_pixbuf_new_from_xpm_data((const gchar **)icon[0]));
3993 #else
3994     iconpm = gdk_pixmap_create_from_xpm_d(gtk_widget_get_window(window),
3995                                           &iconmask, NULL, (gchar **)icon[0]);
3996     gdk_window_set_icon(gtk_widget_get_window(window), NULL, iconpm, iconmask);
3997 #endif
3998
3999 #if GTK_CHECK_VERSION(2,0,0)
4000     iconlist = NULL;
4001     for (n = 0; n < n_icon; n++) {
4002         iconlist =
4003             g_list_append(iconlist,
4004                           gdk_pixbuf_new_from_xpm_data((const gchar **)
4005                                                        icon[n]));
4006     }
4007     gtk_window_set_icon_list(GTK_WINDOW(window), iconlist);
4008 #endif
4009 }
4010
4011 void update_specials_menu(void *frontend)
4012 {
4013     struct gui_data *inst = (struct gui_data *)frontend;
4014
4015     const struct telnet_special *specials;
4016
4017     if (inst->back)
4018         specials = inst->back->get_specials(inst->backhandle);
4019     else
4020         specials = NULL;
4021
4022     /* I believe this disposes of submenus too. */
4023     gtk_container_foreach(GTK_CONTAINER(inst->specialsmenu),
4024                           (GtkCallback)gtk_widget_destroy, NULL);
4025     if (specials) {
4026         int i;
4027         GtkWidget *menu = inst->specialsmenu;
4028         /* A lame "stack" for submenus that will do for now. */
4029         GtkWidget *saved_menu = NULL;
4030         int nesting = 1;
4031         for (i = 0; nesting > 0; i++) {
4032             GtkWidget *menuitem = NULL;
4033             switch (specials[i].code) {
4034               case TS_SUBMENU:
4035                 assert (nesting < 2);
4036                 saved_menu = menu; /* XXX lame stacking */
4037                 menu = gtk_menu_new();
4038                 menuitem = gtk_menu_item_new_with_label(specials[i].name);
4039                 gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), menu);
4040                 gtk_container_add(GTK_CONTAINER(saved_menu), menuitem);
4041                 gtk_widget_show(menuitem);
4042                 menuitem = NULL;
4043                 nesting++;
4044                 break;
4045               case TS_EXITMENU:
4046                 nesting--;
4047                 if (nesting) {
4048                     menu = saved_menu; /* XXX lame stacking */
4049                     saved_menu = NULL;
4050                 }
4051                 break;
4052               case TS_SEP:
4053                 menuitem = gtk_menu_item_new();
4054                 break;
4055               default:
4056                 menuitem = gtk_menu_item_new_with_label(specials[i].name);
4057                 g_object_set_data(G_OBJECT(menuitem), "user-data",
4058                                   GINT_TO_POINTER(specials[i].code));
4059                 g_signal_connect(G_OBJECT(menuitem), "activate",
4060                                  G_CALLBACK(special_menuitem), inst);
4061                 break;
4062             }
4063             if (menuitem) {
4064                 gtk_container_add(GTK_CONTAINER(menu), menuitem);
4065                 gtk_widget_show(menuitem);
4066             }
4067         }
4068         gtk_widget_show(inst->specialsitem1);
4069         gtk_widget_show(inst->specialsitem2);
4070     } else {
4071         gtk_widget_hide(inst->specialsitem1);
4072         gtk_widget_hide(inst->specialsitem2);
4073     }
4074 }
4075
4076 static void start_backend(struct gui_data *inst)
4077 {
4078     extern Backend *select_backend(Conf *conf);
4079     char *realhost;
4080     const char *error;
4081     char *s;
4082
4083     inst->back = select_backend(inst->conf);
4084
4085     error = inst->back->init((void *)inst, &inst->backhandle,
4086                              inst->conf,
4087                              conf_get_str(inst->conf, CONF_host),
4088                              conf_get_int(inst->conf, CONF_port),
4089                              &realhost,
4090                              conf_get_int(inst->conf, CONF_tcp_nodelay),
4091                              conf_get_int(inst->conf, CONF_tcp_keepalives));
4092
4093     if (error) {
4094         char *msg = dupprintf("Unable to open connection to %s:\n%s",
4095                               conf_get_str(inst->conf, CONF_host), error);
4096         inst->exited = TRUE;
4097         fatal_message_box(inst->window, msg);
4098         sfree(msg);
4099         exit(0);
4100     }
4101
4102     s = conf_get_str(inst->conf, CONF_wintitle);
4103     if (s[0]) {
4104         set_title_and_icon(inst, s, s);
4105     } else {
4106         char *title = make_default_wintitle(realhost);
4107         set_title_and_icon(inst, title, title);
4108         sfree(title);
4109     }
4110     sfree(realhost);
4111
4112     inst->back->provide_logctx(inst->backhandle, inst->logctx);
4113
4114     term_provide_resize_fn(inst->term, inst->back->size, inst->backhandle);
4115
4116     inst->ldisc =
4117         ldisc_create(inst->conf, inst->term, inst->back, inst->backhandle,
4118                      inst);
4119
4120     gtk_widget_set_sensitive(inst->restartitem, FALSE);
4121 }
4122
4123 struct gui_data *new_session_window(Conf *conf, const char *geometry_string)
4124 {
4125     struct gui_data *inst;
4126
4127     /*
4128      * Create an instance structure and initialise to zeroes
4129      */
4130     inst = snew(struct gui_data);
4131     memset(inst, 0, sizeof(*inst));
4132     inst->alt_keycode = -1;            /* this one needs _not_ to be zero */
4133     inst->busy_status = BUSY_NOT;
4134     inst->conf = conf;
4135     inst->wintitle = inst->icontitle = NULL;
4136     inst->drawtype = DRAWTYPE_DEFAULT;
4137 #if GTK_CHECK_VERSION(3,4,0)
4138     inst->cumulative_scroll = 0.0;
4139 #endif
4140
4141     if (geometry_string) {
4142 #if GTK_CHECK_VERSION(2,0,0)
4143         inst->geometry = geometry_string;
4144 #else
4145         /* On GTK 1, we have to do this using raw Xlib */
4146         int flags, x, y;
4147         unsigned int w, h;
4148         flags = XParseGeometry(geometry_string, &x, &y, &w, &h);
4149         if (flags & WidthValue)
4150             conf_set_int(conf, CONF_width, w);
4151         if (flags & HeightValue)
4152             conf_set_int(conf, CONF_height, h);
4153
4154         if (flags & (XValue | YValue)) {
4155             inst->xpos = x;
4156             inst->ypos = y;
4157             inst->gotpos = TRUE;
4158             inst->gravity = ((flags & XNegative ? 1 : 0) |
4159                              (flags & YNegative ? 2 : 0));
4160         }
4161 #endif
4162     }
4163
4164     if (!compound_text_atom)
4165         compound_text_atom = gdk_atom_intern("COMPOUND_TEXT", FALSE);
4166     if (!utf8_string_atom)
4167         utf8_string_atom = gdk_atom_intern("UTF8_STRING", FALSE);
4168
4169     inst->area = gtk_drawing_area_new();
4170
4171 #if GTK_CHECK_VERSION(2,0,0)
4172     inst->imc = gtk_im_multicontext_new();
4173 #endif
4174
4175     {
4176         char *errmsg = setup_fonts_ucs(inst);
4177         if (errmsg) {
4178             fprintf(stderr, "%s: %s\n", appname, errmsg);
4179             exit(1);
4180         }
4181     }
4182     inst->window = make_gtk_toplevel_window(inst);
4183     {
4184         const char *winclass = conf_get_str(inst->conf, CONF_winclass);
4185         if (*winclass)
4186             gtk_window_set_wmclass(GTK_WINDOW(inst->window),
4187                                    winclass, winclass);
4188     }
4189
4190     /*
4191      * Set up the colour map.
4192      */
4193     palette_reset(inst);
4194
4195     inst->width = conf_get_int(inst->conf, CONF_width);
4196     inst->height = conf_get_int(inst->conf, CONF_height);
4197     cache_conf_values(inst);
4198
4199     init_clipboard(inst);
4200
4201     inst->sbar_adjust = GTK_ADJUSTMENT(gtk_adjustment_new(0,0,0,0,0,0));
4202     inst->sbar = gtk_vscrollbar_new(inst->sbar_adjust);
4203     inst->hbox = GTK_BOX(gtk_hbox_new(FALSE, 0));
4204     /*
4205      * We always create the scrollbar; it remains invisible if
4206      * unwanted, so we can pop it up quickly if it suddenly becomes
4207      * desirable.
4208      */
4209     if (conf_get_int(inst->conf, CONF_scrollbar_on_left))
4210         gtk_box_pack_start(inst->hbox, inst->sbar, FALSE, FALSE, 0);
4211     gtk_box_pack_start(inst->hbox, inst->area, TRUE, TRUE, 0);
4212     if (!conf_get_int(inst->conf, CONF_scrollbar_on_left))
4213         gtk_box_pack_start(inst->hbox, inst->sbar, FALSE, FALSE, 0);
4214
4215     gtk_container_add(GTK_CONTAINER(inst->window), GTK_WIDGET(inst->hbox));
4216
4217     gtk_widget_show(inst->area);
4218     show_scrollbar(inst, conf_get_int(inst->conf, CONF_scrollbar));
4219     gtk_widget_show(GTK_WIDGET(inst->hbox));
4220
4221     set_geom_hints(inst);
4222
4223 #if GTK_CHECK_VERSION(3,0,0)
4224     gtk_window_set_default_geometry(GTK_WINDOW(inst->window),
4225                                     inst->width, inst->height);
4226 #else
4227     {
4228         int w = inst->font_width * inst->width + 2*inst->window_border;
4229         int h = inst->font_height * inst->height + 2*inst->window_border;
4230 #if GTK_CHECK_VERSION(2,0,0)
4231         gtk_widget_set_size_request(inst->area, w, h);
4232 #else
4233         gtk_drawing_area_size(GTK_DRAWING_AREA(inst->area), w, h);
4234 #endif
4235     }
4236 #endif
4237
4238 #if GTK_CHECK_VERSION(2,0,0)
4239     if (inst->geometry) {
4240         gtk_window_parse_geometry(GTK_WINDOW(inst->window), inst->geometry);
4241     }
4242 #else
4243     if (inst->gotpos) {
4244         int x = inst->xpos, y = inst->ypos;
4245         GtkRequisition req;
4246         gtk_widget_size_request(GTK_WIDGET(inst->window), &req);
4247         if (inst->gravity & 1) x += gdk_screen_width() - req.width;
4248         if (inst->gravity & 2) y += gdk_screen_height() - req.height;
4249         gtk_window_set_position(GTK_WINDOW(inst->window), GTK_WIN_POS_NONE);
4250         gtk_widget_set_uposition(GTK_WIDGET(inst->window), x, y);
4251     }
4252 #endif
4253
4254     g_signal_connect(G_OBJECT(inst->window), "destroy",
4255                      G_CALLBACK(destroy), inst);
4256     g_signal_connect(G_OBJECT(inst->window), "delete_event",
4257                      G_CALLBACK(delete_window), inst);
4258     g_signal_connect(G_OBJECT(inst->window), "key_press_event",
4259                      G_CALLBACK(key_event), inst);
4260     g_signal_connect(G_OBJECT(inst->window), "key_release_event",
4261                      G_CALLBACK(key_event), inst);
4262     g_signal_connect(G_OBJECT(inst->window), "focus_in_event",
4263                      G_CALLBACK(focus_event), inst);
4264     g_signal_connect(G_OBJECT(inst->window), "focus_out_event",
4265                      G_CALLBACK(focus_event), inst);
4266     g_signal_connect(G_OBJECT(inst->area), "configure_event",
4267                      G_CALLBACK(configure_area), inst);
4268 #if GTK_CHECK_VERSION(3,0,0)
4269     g_signal_connect(G_OBJECT(inst->area), "draw",
4270                      G_CALLBACK(draw_area), inst);
4271 #else
4272     g_signal_connect(G_OBJECT(inst->area), "expose_event",
4273                      G_CALLBACK(expose_area), inst);
4274 #endif
4275     g_signal_connect(G_OBJECT(inst->area), "button_press_event",
4276                      G_CALLBACK(button_event), inst);
4277     g_signal_connect(G_OBJECT(inst->area), "button_release_event",
4278                      G_CALLBACK(button_event), inst);
4279 #if GTK_CHECK_VERSION(2,0,0)
4280     g_signal_connect(G_OBJECT(inst->area), "scroll_event",
4281                      G_CALLBACK(scroll_event), inst);
4282 #endif
4283     g_signal_connect(G_OBJECT(inst->area), "motion_notify_event",
4284                      G_CALLBACK(motion_event), inst);
4285 #if GTK_CHECK_VERSION(2,0,0)
4286     g_signal_connect(G_OBJECT(inst->imc), "commit",
4287                      G_CALLBACK(input_method_commit_event), inst);
4288 #endif
4289     if (conf_get_int(inst->conf, CONF_scrollbar))
4290         g_signal_connect(G_OBJECT(inst->sbar_adjust), "value_changed",
4291                          G_CALLBACK(scrollbar_moved), inst);
4292     gtk_widget_add_events(GTK_WIDGET(inst->area),
4293                           GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK |
4294                           GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK |
4295                           GDK_POINTER_MOTION_MASK | GDK_BUTTON_MOTION_MASK
4296 #if GTK_CHECK_VERSION(3,4,0)
4297                           | GDK_SMOOTH_SCROLL_MASK
4298 #endif
4299         );
4300
4301     {
4302         extern const char *const *const main_icon[];
4303         extern const int n_main_icon;
4304         set_window_icon(inst->window, main_icon, n_main_icon);
4305     }
4306
4307     gtk_widget_show(inst->window);
4308
4309     set_window_background(inst);
4310
4311     /*
4312      * Set up the Ctrl+rightclick context menu.
4313      */
4314     {
4315         GtkWidget *menuitem;
4316         char *s;
4317         extern const int use_event_log, new_session, saved_sessions;
4318
4319         inst->menu = gtk_menu_new();
4320
4321 #define MKMENUITEM(title, func) do                                      \
4322         {                                                               \
4323             menuitem = gtk_menu_item_new_with_label(title);             \
4324             gtk_container_add(GTK_CONTAINER(inst->menu), menuitem);     \
4325             gtk_widget_show(menuitem);                                  \
4326             g_signal_connect(G_OBJECT(menuitem), "activate",            \
4327                              G_CALLBACK(func), inst);                   \
4328         } while (0)
4329
4330 #define MKSUBMENU(title) do                                             \
4331         {                                                               \
4332             menuitem = gtk_menu_item_new_with_label(title);             \
4333             gtk_container_add(GTK_CONTAINER(inst->menu), menuitem);     \
4334             gtk_widget_show(menuitem);                                  \
4335         } while (0)
4336
4337 #define MKSEP() do                                                      \
4338         {                                                               \
4339             menuitem = gtk_menu_item_new();                             \
4340             gtk_container_add(GTK_CONTAINER(inst->menu), menuitem);     \
4341             gtk_widget_show(menuitem);                                  \
4342         } while (0)
4343
4344         if (new_session)
4345             MKMENUITEM("New Session...", new_session_menuitem);
4346         MKMENUITEM("Restart Session", restart_session_menuitem);
4347         inst->restartitem = menuitem;
4348         gtk_widget_set_sensitive(inst->restartitem, FALSE);
4349         MKMENUITEM("Duplicate Session", dup_session_menuitem);
4350         if (saved_sessions) {
4351             inst->sessionsmenu = gtk_menu_new();
4352             /* sessionsmenu will be updated when it's invoked */
4353             /* XXX is this the right way to do dynamic menus in Gtk? */
4354             MKMENUITEM("Saved Sessions", update_savedsess_menu);
4355             gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem),
4356                                       inst->sessionsmenu);
4357         }
4358         MKSEP();
4359         MKMENUITEM("Change Settings...", change_settings_menuitem);
4360         MKSEP();
4361         if (use_event_log)
4362             MKMENUITEM("Event Log", event_log_menuitem);
4363         MKSUBMENU("Special Commands");
4364         inst->specialsmenu = gtk_menu_new();
4365         gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), inst->specialsmenu);
4366         inst->specialsitem1 = menuitem;
4367         MKSEP();
4368         inst->specialsitem2 = menuitem;
4369         gtk_widget_hide(inst->specialsitem1);
4370         gtk_widget_hide(inst->specialsitem2);
4371         MKMENUITEM("Clear Scrollback", clear_scrollback_menuitem);
4372         MKMENUITEM("Reset Terminal", reset_terminal_menuitem);
4373         MKMENUITEM("Copy All", copy_all_menuitem);
4374         MKSEP();
4375         s = dupcat("About ", appname, NULL);
4376         MKMENUITEM(s, about_menuitem);
4377         sfree(s);
4378 #undef MKMENUITEM
4379 #undef MKSUBMENU
4380 #undef MKSEP
4381     }
4382
4383     inst->textcursor = make_mouse_ptr(inst, GDK_XTERM);
4384     inst->rawcursor = make_mouse_ptr(inst, GDK_LEFT_PTR);
4385     inst->waitcursor = make_mouse_ptr(inst, GDK_WATCH);
4386     inst->blankcursor = make_mouse_ptr(inst, -1);
4387     inst->currcursor = inst->textcursor;
4388     show_mouseptr(inst, 1);
4389
4390     inst->eventlogstuff = eventlogstuff_new();
4391
4392     inst->term = term_init(inst->conf, &inst->ucsdata, inst);
4393     inst->logctx = log_init(inst, inst->conf);
4394     term_provide_logctx(inst->term, inst->logctx);
4395
4396     term_size(inst->term, inst->height, inst->width,
4397               conf_get_int(inst->conf, CONF_savelines));
4398
4399     start_backend(inst);
4400
4401     ldisc_echoedit_update(inst->ldisc);     /* cause ldisc to notice changes */
4402
4403     inst->exited = FALSE;
4404
4405     return inst;
4406 }