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