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