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