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