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