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