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