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