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