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