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