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