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