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