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