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