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