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