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