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