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