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