]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - unix/gtkdlg.c
Fix the config box treeview width in GTK3.
[PuTTY.git] / unix / gtkdlg.c
1 /*
2  * gtkdlg.c - GTK implementation of the PuTTY configuration box.
3  */
4
5 #include <assert.h>
6 #include <stdarg.h>
7 #include <ctype.h>
8 #include <time.h>
9 #include <gtk/gtk.h>
10 #if !GTK_CHECK_VERSION(3,0,0)
11 #include <gdk/gdkkeysyms.h>
12 #endif
13 #ifndef NOT_X_WINDOWS
14 #include <gdk/gdkx.h>
15 #include <X11/Xlib.h>
16 #include <X11/Xutil.h>
17 #endif
18
19 #include "gtkcompat.h"
20
21 #include "gtkcols.h"
22 #include "gtkfont.h"
23
24 #ifdef TESTMODE
25 #define PUTTY_DO_GLOBALS               /* actually _define_ globals */
26 #endif
27
28 #include "putty.h"
29 #include "storage.h"
30 #include "dialog.h"
31 #include "tree234.h"
32
33 #if GTK_CHECK_VERSION(2,0,0)
34 /* Decide which of GtkFileChooserDialog and GtkFileSelection to use */
35 #define USE_GTK_FILE_CHOOSER_DIALOG
36 #endif
37
38 struct Shortcut {
39     GtkWidget *widget;
40     struct uctrl *uc;
41     int action;
42 };
43
44 struct Shortcuts {
45     struct Shortcut sc[128];
46 };
47
48 struct uctrl {
49     union control *ctrl;
50     GtkWidget *toplevel;
51     GtkWidget **buttons; int nbuttons; /* for radio buttons */
52     GtkWidget *entry;         /* for editbox, filesel, fontsel */
53     GtkWidget *button;        /* for filesel, fontsel */
54 #if !GTK_CHECK_VERSION(2,4,0)
55     GtkWidget *list;          /* for listbox (in GTK1), combobox (<=GTK2.3) */
56     GtkWidget *menu;          /* for optionmenu (==droplist) */
57     GtkWidget *optmenu;       /* also for optionmenu */
58 #else
59     GtkWidget *combo;         /* for combo box (either editable or not) */
60 #endif
61 #if GTK_CHECK_VERSION(2,0,0)
62     GtkWidget *treeview;      /* for listbox (GTK2), droplist+combo (>=2.4) */
63     GtkListStore *listmodel;  /* for all types of list box */
64 #endif
65     GtkWidget *text;          /* for text */
66     GtkWidget *label;         /* for dlg_label_change */
67     GtkAdjustment *adj;       /* for the scrollbar in a list box */
68     guint entrysig;
69     guint textsig;
70     int nclicks;
71 };
72
73 struct dlgparam {
74     tree234 *byctrl, *bywidget;
75     void *data;
76     struct { unsigned char r, g, b, ok; } coloursel_result;   /* 0-255 */
77     /* `flags' are set to indicate when a GTK signal handler is being called
78      * due to automatic processing and should not flag a user event. */
79     int flags;
80     struct Shortcuts *shortcuts;
81     GtkWidget *window, *cancelbutton;
82     union control *currfocus, *lastfocus;
83 #if !GTK_CHECK_VERSION(2,0,0)
84     GtkWidget *currtreeitem, **treeitems;
85     int ntreeitems;
86 #else
87     int nselparams;
88     struct selparam *selparams;
89 #endif
90     int retval;
91 };
92 #define FLAG_UPDATING_COMBO_LIST 1
93 #define FLAG_UPDATING_LISTBOX    2
94
95 enum {                                 /* values for Shortcut.action */
96     SHORTCUT_EMPTY,                    /* no shortcut on this key */
97     SHORTCUT_TREE,                     /* focus a tree item */
98     SHORTCUT_FOCUS,                    /* focus the supplied widget */
99     SHORTCUT_UCTRL,                    /* do something sane with uctrl */
100     SHORTCUT_UCTRL_UP,                 /* uctrl is a draglist, move Up */
101     SHORTCUT_UCTRL_DOWN,               /* uctrl is a draglist, move Down */
102 };
103
104 #if GTK_CHECK_VERSION(2,0,0)
105 enum {
106     TREESTORE_PATH,
107     TREESTORE_PARAMS,
108     TREESTORE_NUM
109 };
110 #endif
111
112 /*
113  * Forward references.
114  */
115 static gboolean widget_focus(GtkWidget *widget, GdkEventFocus *event,
116                              gpointer data);
117 static void shortcut_add(struct Shortcuts *scs, GtkWidget *labelw,
118                          int chr, int action, void *ptr);
119 static void shortcut_highlight(GtkWidget *label, int chr);
120 #if !GTK_CHECK_VERSION(2,0,0)
121 static gboolean listitem_single_key(GtkWidget *item, GdkEventKey *event,
122                                     gpointer data);
123 static gboolean listitem_multi_key(GtkWidget *item, GdkEventKey *event,
124                                    gpointer data);
125 static gboolean listitem_button_press(GtkWidget *item, GdkEventButton *event,
126                                       gpointer data);
127 static gboolean listitem_button_release(GtkWidget *item, GdkEventButton *event,
128                                         gpointer data);
129 #endif
130 #if !GTK_CHECK_VERSION(2,4,0)
131 static void menuitem_activate(GtkMenuItem *item, gpointer data);
132 #endif
133 #if GTK_CHECK_VERSION(3,0,0)
134 static void colourchoose_response(GtkDialog *dialog,
135                                   gint response_id, gpointer data);
136 #else
137 static void coloursel_ok(GtkButton *button, gpointer data);
138 static void coloursel_cancel(GtkButton *button, gpointer data);
139 #endif
140 static void window_destroy(GtkWidget *widget, gpointer data);
141 int get_listitemheight(GtkWidget *widget);
142
143 static int uctrl_cmp_byctrl(void *av, void *bv)
144 {
145     struct uctrl *a = (struct uctrl *)av;
146     struct uctrl *b = (struct uctrl *)bv;
147     if (a->ctrl < b->ctrl)
148         return -1;
149     else if (a->ctrl > b->ctrl)
150         return +1;
151     return 0;
152 }
153
154 static int uctrl_cmp_byctrl_find(void *av, void *bv)
155 {
156     union control *a = (union control *)av;
157     struct uctrl *b = (struct uctrl *)bv;
158     if (a < b->ctrl)
159         return -1;
160     else if (a > b->ctrl)
161         return +1;
162     return 0;
163 }
164
165 static int uctrl_cmp_bywidget(void *av, void *bv)
166 {
167     struct uctrl *a = (struct uctrl *)av;
168     struct uctrl *b = (struct uctrl *)bv;
169     if (a->toplevel < b->toplevel)
170         return -1;
171     else if (a->toplevel > b->toplevel)
172         return +1;
173     return 0;
174 }
175
176 static int uctrl_cmp_bywidget_find(void *av, void *bv)
177 {
178     GtkWidget *a = (GtkWidget *)av;
179     struct uctrl *b = (struct uctrl *)bv;
180     if (a < b->toplevel)
181         return -1;
182     else if (a > b->toplevel)
183         return +1;
184     return 0;
185 }
186
187 static void dlg_init(struct dlgparam *dp)
188 {
189     dp->byctrl = newtree234(uctrl_cmp_byctrl);
190     dp->bywidget = newtree234(uctrl_cmp_bywidget);
191     dp->coloursel_result.ok = FALSE;
192     dp->window = dp->cancelbutton = NULL;
193 #if !GTK_CHECK_VERSION(2,0,0)
194     dp->treeitems = NULL;
195     dp->currtreeitem = NULL;
196 #endif
197     dp->flags = 0;
198     dp->currfocus = NULL;
199 }
200
201 static void dlg_cleanup(struct dlgparam *dp)
202 {
203     struct uctrl *uc;
204
205     freetree234(dp->byctrl);           /* doesn't free the uctrls inside */
206     dp->byctrl = NULL;
207     while ( (uc = index234(dp->bywidget, 0)) != NULL) {
208         del234(dp->bywidget, uc);
209         sfree(uc->buttons);
210         sfree(uc);
211     }
212     freetree234(dp->bywidget);
213     dp->bywidget = NULL;
214 #if !GTK_CHECK_VERSION(2,0,0)
215     sfree(dp->treeitems);
216 #endif
217 }
218
219 static void dlg_add_uctrl(struct dlgparam *dp, struct uctrl *uc)
220 {
221     add234(dp->byctrl, uc);
222     add234(dp->bywidget, uc);
223 }
224
225 static struct uctrl *dlg_find_byctrl(struct dlgparam *dp, union control *ctrl)
226 {
227     if (!dp->byctrl)
228         return NULL;
229     return find234(dp->byctrl, ctrl, uctrl_cmp_byctrl_find);
230 }
231
232 static struct uctrl *dlg_find_bywidget(struct dlgparam *dp, GtkWidget *w)
233 {
234     struct uctrl *ret = NULL;
235     if (!dp->bywidget)
236         return NULL;
237     do {
238         ret = find234(dp->bywidget, w, uctrl_cmp_bywidget_find);
239         if (ret)
240             return ret;
241         w = gtk_widget_get_parent(w);
242     } while (w);
243     return ret;
244 }
245
246 union control *dlg_last_focused(union control *ctrl, void *dlg)
247 {
248     struct dlgparam *dp = (struct dlgparam *)dlg;
249     if (dp->currfocus != ctrl)
250         return dp->currfocus;
251     else
252         return dp->lastfocus;
253 }
254
255 void dlg_radiobutton_set(union control *ctrl, void *dlg, int which)
256 {
257     struct dlgparam *dp = (struct dlgparam *)dlg;
258     struct uctrl *uc = dlg_find_byctrl(dp, ctrl);
259     assert(uc->ctrl->generic.type == CTRL_RADIO);
260     assert(uc->buttons != NULL);
261     gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(uc->buttons[which]), TRUE);
262 }
263
264 int dlg_radiobutton_get(union control *ctrl, void *dlg)
265 {
266     struct dlgparam *dp = (struct dlgparam *)dlg;
267     struct uctrl *uc = dlg_find_byctrl(dp, ctrl);
268     int i;
269
270     assert(uc->ctrl->generic.type == CTRL_RADIO);
271     assert(uc->buttons != NULL);
272     for (i = 0; i < uc->nbuttons; i++)
273         if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(uc->buttons[i])))
274             return i;
275     return 0;                          /* got to return something */
276 }
277
278 void dlg_checkbox_set(union control *ctrl, void *dlg, int checked)
279 {
280     struct dlgparam *dp = (struct dlgparam *)dlg;
281     struct uctrl *uc = dlg_find_byctrl(dp, ctrl);
282     assert(uc->ctrl->generic.type == CTRL_CHECKBOX);
283     gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(uc->toplevel), checked);
284 }
285
286 int dlg_checkbox_get(union control *ctrl, void *dlg)
287 {
288     struct dlgparam *dp = (struct dlgparam *)dlg;
289     struct uctrl *uc = dlg_find_byctrl(dp, ctrl);
290     assert(uc->ctrl->generic.type == CTRL_CHECKBOX);
291     return gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(uc->toplevel));
292 }
293
294 void dlg_editbox_set(union control *ctrl, void *dlg, char const *text)
295 {
296     struct dlgparam *dp = (struct dlgparam *)dlg;
297     struct uctrl *uc = dlg_find_byctrl(dp, ctrl);
298     GtkWidget *entry;
299     char *tmpstring;
300     assert(uc->ctrl->generic.type == CTRL_EDITBOX);
301
302 #if GTK_CHECK_VERSION(2,4,0)
303     if (uc->combo)
304         entry = gtk_bin_get_child(GTK_BIN(uc->combo));
305     else
306 #endif
307     entry = uc->entry;
308
309     assert(entry != NULL);
310
311     /*
312      * GTK 2 implements gtk_entry_set_text by means of two separate
313      * operations: first delete the previous text leaving the empty
314      * string, then insert the new text. This causes two calls to
315      * the "changed" signal.
316      *
317      * The first call to "changed", if allowed to proceed normally,
318      * will cause an EVENT_VALCHANGE event on the edit box, causing
319      * a call to dlg_editbox_get() which will read the empty string
320      * out of the GtkEntry - and promptly write it straight into the
321      * Conf structure, which is precisely where our `text' pointer
322      * is probably pointing, so the second editing operation will
323      * insert that instead of the string we originally asked for.
324      *
325      * Hence, we must take our own copy of the text before we do
326      * this.
327      */
328     tmpstring = dupstr(text);
329     gtk_entry_set_text(GTK_ENTRY(entry), tmpstring);
330     sfree(tmpstring);
331 }
332
333 char *dlg_editbox_get(union control *ctrl, void *dlg)
334 {
335     struct dlgparam *dp = (struct dlgparam *)dlg;
336     struct uctrl *uc = dlg_find_byctrl(dp, ctrl);
337     assert(uc->ctrl->generic.type == CTRL_EDITBOX);
338
339 #if GTK_CHECK_VERSION(2,4,0)
340     if (uc->combo) {
341         return dupstr(gtk_entry_get_text
342                       (GTK_ENTRY(gtk_bin_get_child(GTK_BIN(uc->combo)))));
343     }
344 #endif
345
346     if (uc->entry) {
347         return dupstr(gtk_entry_get_text(GTK_ENTRY(uc->entry)));
348     }
349
350     assert(!"We shouldn't get here");
351 }
352
353 #if !GTK_CHECK_VERSION(2,4,0)
354 static void container_remove_and_destroy(GtkWidget *w, gpointer data)
355 {
356     GtkContainer *cont = GTK_CONTAINER(data);
357     /* gtk_container_remove will unref the widget for us; we need not. */
358     gtk_container_remove(cont, w);
359 }
360 #endif
361
362 /* The `listbox' functions can also apply to combo boxes. */
363 void dlg_listbox_clear(union control *ctrl, void *dlg)
364 {
365     struct dlgparam *dp = (struct dlgparam *)dlg;
366     struct uctrl *uc = dlg_find_byctrl(dp, ctrl);
367
368     assert(uc->ctrl->generic.type == CTRL_EDITBOX ||
369            uc->ctrl->generic.type == CTRL_LISTBOX);
370
371 #if !GTK_CHECK_VERSION(2,4,0)
372     if (uc->menu) {
373         gtk_container_foreach(GTK_CONTAINER(uc->menu),
374                               container_remove_and_destroy,
375                               GTK_CONTAINER(uc->menu));
376         return;
377     }
378     if (uc->list) {
379         gtk_list_clear_items(GTK_LIST(uc->list), 0, -1);
380         return;
381     }
382 #endif
383 #if GTK_CHECK_VERSION(2,0,0)
384     if (uc->listmodel) {
385         gtk_list_store_clear(uc->listmodel);
386         return;
387     }
388 #endif
389     assert(!"We shouldn't get here");
390 }
391
392 void dlg_listbox_del(union control *ctrl, void *dlg, int index)
393 {
394     struct dlgparam *dp = (struct dlgparam *)dlg;
395     struct uctrl *uc = dlg_find_byctrl(dp, ctrl);
396
397     assert(uc->ctrl->generic.type == CTRL_EDITBOX ||
398            uc->ctrl->generic.type == CTRL_LISTBOX);
399
400 #if !GTK_CHECK_VERSION(2,4,0)
401     if (uc->menu) {
402         gtk_container_remove
403             (GTK_CONTAINER(uc->menu),
404              g_list_nth_data(GTK_MENU_SHELL(uc->menu)->children, index));
405         return;
406     }
407     if (uc->list) {
408         gtk_list_clear_items(GTK_LIST(uc->list), index, index+1);
409         return;
410     }
411 #endif
412 #if GTK_CHECK_VERSION(2,0,0)
413     if (uc->listmodel) {
414         GtkTreePath *path;
415         GtkTreeIter iter;
416         assert(uc->listmodel != NULL);
417         path = gtk_tree_path_new_from_indices(index, -1);
418         gtk_tree_model_get_iter(GTK_TREE_MODEL(uc->listmodel), &iter, path);
419         gtk_list_store_remove(uc->listmodel, &iter);
420         gtk_tree_path_free(path);
421         return;
422     }
423 #endif
424     assert(!"We shouldn't get here");
425 }
426
427 void dlg_listbox_add(union control *ctrl, void *dlg, char const *text)
428 {
429     dlg_listbox_addwithid(ctrl, dlg, text, 0);
430 }
431
432 /*
433  * Each listbox entry may have a numeric id associated with it.
434  * Note that some front ends only permit a string to be stored at
435  * each position, which means that _if_ you put two identical
436  * strings in any listbox then you MUST not assign them different
437  * IDs and expect to get meaningful results back.
438  */
439 void dlg_listbox_addwithid(union control *ctrl, void *dlg,
440                            char const *text, int id)
441 {
442     struct dlgparam *dp = (struct dlgparam *)dlg;
443     struct uctrl *uc = dlg_find_byctrl(dp, ctrl);
444
445     assert(uc->ctrl->generic.type == CTRL_EDITBOX ||
446            uc->ctrl->generic.type == CTRL_LISTBOX);
447
448     /*
449      * This routine is long and complicated in both GTK 1 and 2,
450      * and completely different. Sigh.
451      */
452     dp->flags |= FLAG_UPDATING_COMBO_LIST;
453
454 #if !GTK_CHECK_VERSION(2,4,0)
455     if (uc->menu) {
456         /*
457          * List item in a drop-down (but non-combo) list. Tabs are
458          * ignored; we just provide a standard menu item with the
459          * text.
460          */
461         GtkWidget *menuitem = gtk_menu_item_new_with_label(text);
462
463         gtk_container_add(GTK_CONTAINER(uc->menu), menuitem);
464         gtk_widget_show(menuitem);
465
466         g_object_set_data(G_OBJECT(menuitem), "user-data",
467                           GINT_TO_POINTER(id));
468         g_signal_connect(G_OBJECT(menuitem), "activate",
469                          G_CALLBACK(menuitem_activate), dp);
470         goto done;
471     }
472     if (uc->list && uc->entry) {
473         /*
474          * List item in a combo-box list, which means the sensible
475          * thing to do is make it a perfectly normal label. Hence
476          * tabs are disregarded.
477          */
478         GtkWidget *listitem = gtk_list_item_new_with_label(text);
479
480         gtk_container_add(GTK_CONTAINER(uc->list), listitem);
481         gtk_widget_show(listitem);
482
483         g_object_set_data(G_OBJECT(listitem), "user-data",
484                           GINT_TO_POINTER(id));
485         goto done;
486     }
487 #endif
488 #if !GTK_CHECK_VERSION(2,0,0)
489     if (uc->list) {
490         /*
491          * List item in a non-combo-box list box. We make all of
492          * these Columns containing GtkLabels. This allows us to do
493          * the nasty force_left hack irrespective of whether there
494          * are tabs in the thing.
495          */
496         GtkWidget *listitem = gtk_list_item_new();
497         GtkWidget *cols = columns_new(10);
498         gint *percents;
499         int i, ncols;
500
501         /* Count the tabs in the text, and hence determine # of columns. */
502         ncols = 1;
503         for (i = 0; text[i]; i++)
504             if (text[i] == '\t')
505                 ncols++;
506
507         assert(ncols <=
508                (uc->ctrl->listbox.ncols ? uc->ctrl->listbox.ncols : 1));
509         percents = snewn(ncols, gint);
510         percents[ncols-1] = 100;
511         for (i = 0; i < ncols-1; i++) {
512             percents[i] = uc->ctrl->listbox.percentages[i];
513             percents[ncols-1] -= percents[i];
514         }
515         columns_set_cols(COLUMNS(cols), ncols, percents);
516         sfree(percents);
517
518         for (i = 0; i < ncols; i++) {
519             int len = strcspn(text, "\t");
520             char *dup = dupprintf("%.*s", len, text);
521             GtkWidget *label;
522
523             text += len;
524             if (*text) text++;
525             label = gtk_label_new(dup);
526             sfree(dup);
527
528             columns_add(COLUMNS(cols), label, i, 1);
529             columns_force_left_align(COLUMNS(cols), label);
530             gtk_widget_show(label);
531         }
532         gtk_container_add(GTK_CONTAINER(listitem), cols);
533         gtk_widget_show(cols);
534         gtk_container_add(GTK_CONTAINER(uc->list), listitem);
535         gtk_widget_show(listitem);
536
537         if (ctrl->listbox.multisel) {
538             g_signal_connect(G_OBJECT(listitem), "key_press_event",
539                              G_CALLBACK(listitem_multi_key), uc->adj);
540         } else {
541             g_signal_connect(G_OBJECT(listitem), "key_press_event",
542                              G_CALLBACK(listitem_single_key), uc->adj);
543         }
544         g_signal_connect(G_OBJECT(listitem), "focus_in_event",
545                          G_CALLBACK(widget_focus), dp);
546         g_signal_connect(G_OBJECT(listitem), "button_press_event",
547                          G_CALLBACK(listitem_button_press), dp);
548         g_signal_connect(G_OBJECT(listitem), "button_release_event",
549                          G_CALLBACK(listitem_button_release), dp);
550         g_object_set_data(G_OBJECT(listitem), "user-data",
551                           GINT_TO_POINTER(id));
552         goto done;
553     }
554 #else
555     if (uc->listmodel) {
556         GtkTreeIter iter;
557         int i, cols;
558
559         dp->flags |= FLAG_UPDATING_LISTBOX;/* inhibit drag-list update */
560         gtk_list_store_append(uc->listmodel, &iter);
561         dp->flags &= ~FLAG_UPDATING_LISTBOX;
562         gtk_list_store_set(uc->listmodel, &iter, 0, id, -1);
563
564         /*
565          * Now go through text and divide it into columns at the tabs,
566          * as necessary.
567          */
568         cols = (uc->ctrl->generic.type == CTRL_LISTBOX ? ctrl->listbox.ncols : 1);
569         cols = cols ? cols : 1;
570         for (i = 0; i < cols; i++) {
571             int collen = strcspn(text, "\t");
572             char *tmpstr = snewn(collen+1, char);
573             memcpy(tmpstr, text, collen);
574             tmpstr[collen] = '\0';
575             gtk_list_store_set(uc->listmodel, &iter, i+1, tmpstr, -1);
576             sfree(tmpstr);
577             text += collen;
578             if (*text) text++;
579         }
580         goto done;
581     }
582 #endif
583     assert(!"We shouldn't get here");
584     done:
585     dp->flags &= ~FLAG_UPDATING_COMBO_LIST;
586 }
587
588 int dlg_listbox_getid(union control *ctrl, void *dlg, int index)
589 {
590     struct dlgparam *dp = (struct dlgparam *)dlg;
591     struct uctrl *uc = dlg_find_byctrl(dp, ctrl);
592
593     assert(uc->ctrl->generic.type == CTRL_EDITBOX ||
594            uc->ctrl->generic.type == CTRL_LISTBOX);
595
596 #if !GTK_CHECK_VERSION(2,4,0)
597     if (uc->menu || uc->list) {
598         GList *children;
599         GObject *item;
600
601         children = gtk_container_children(GTK_CONTAINER(uc->menu ? uc->menu :
602                                                         uc->list));
603         item = G_OBJECT(g_list_nth_data(children, index));
604         g_list_free(children);
605
606         return GPOINTER_TO_INT(g_object_get_data(G_OBJECT(item), "user-data"));
607     }
608 #endif
609 #if GTK_CHECK_VERSION(2,0,0)
610     if (uc->listmodel) {
611         GtkTreePath *path;
612         GtkTreeIter iter;
613         int ret;
614
615         path = gtk_tree_path_new_from_indices(index, -1);
616         gtk_tree_model_get_iter(GTK_TREE_MODEL(uc->listmodel), &iter, path);
617         gtk_tree_model_get(GTK_TREE_MODEL(uc->listmodel), &iter, 0, &ret, -1);
618         gtk_tree_path_free(path);
619
620         return ret;
621     }
622 #endif
623     assert(!"We shouldn't get here");
624     return -1;                         /* placate dataflow analysis */
625 }
626
627 /* dlg_listbox_index returns <0 if no single element is selected. */
628 int dlg_listbox_index(union control *ctrl, void *dlg)
629 {
630     struct dlgparam *dp = (struct dlgparam *)dlg;
631     struct uctrl *uc = dlg_find_byctrl(dp, ctrl);
632
633     assert(uc->ctrl->generic.type == CTRL_EDITBOX ||
634            uc->ctrl->generic.type == CTRL_LISTBOX);
635
636 #if !GTK_CHECK_VERSION(2,4,0)
637     if (uc->menu || uc->list) {
638         GList *children;
639         GtkWidget *item, *activeitem;
640         int i;
641         int selected = -1;
642
643         if (uc->menu)
644             activeitem = gtk_menu_get_active(GTK_MENU(uc->menu));
645         else
646             activeitem = NULL;         /* unnecessarily placate gcc */
647
648         children = gtk_container_children(GTK_CONTAINER(uc->menu ? uc->menu :
649                                                         uc->list));
650         for (i = 0; children!=NULL && (item = GTK_WIDGET(children->data))!=NULL;
651              i++, children = children->next) {
652             if (uc->menu ? activeitem == item :
653                 GTK_WIDGET_STATE(item) == GTK_STATE_SELECTED) {
654                 if (selected == -1)
655                     selected = i;
656                 else
657                     selected = -2;
658             }
659         }
660         g_list_free(children);
661         return selected < 0 ? -1 : selected;
662     }
663 #else
664     if (uc->combo) {
665         /*
666          * This API function already does the right thing in the
667          * case of no current selection.
668          */
669         return gtk_combo_box_get_active(GTK_COMBO_BOX(uc->combo));
670     }
671 #endif
672 #if GTK_CHECK_VERSION(2,0,0)
673     if (uc->treeview) {
674         GtkTreeSelection *treesel;
675         GtkTreePath *path;
676         GtkTreeModel *model;
677         GList *sellist;
678         gint *indices;
679         int ret;
680
681         assert(uc->treeview != NULL);
682         treesel = gtk_tree_view_get_selection(GTK_TREE_VIEW(uc->treeview));
683
684         if (gtk_tree_selection_count_selected_rows(treesel) != 1)
685             return -1;
686
687         sellist = gtk_tree_selection_get_selected_rows(treesel, &model);
688
689         assert(sellist && sellist->data);
690         path = sellist->data;
691
692         if (gtk_tree_path_get_depth(path) != 1) {
693             ret = -1;
694         } else {
695             indices = gtk_tree_path_get_indices(path);
696             if (!indices) {
697                 ret = -1;
698             } else {
699                 ret = indices[0];
700             }
701         }
702
703         g_list_foreach(sellist, (GFunc)gtk_tree_path_free, NULL);
704         g_list_free(sellist);
705
706         return ret;
707     }
708 #endif
709     assert(!"We shouldn't get here");
710     return -1;                         /* placate dataflow analysis */
711 }
712
713 int dlg_listbox_issel(union control *ctrl, void *dlg, int index)
714 {
715     struct dlgparam *dp = (struct dlgparam *)dlg;
716     struct uctrl *uc = dlg_find_byctrl(dp, ctrl);
717
718     assert(uc->ctrl->generic.type == CTRL_EDITBOX ||
719            uc->ctrl->generic.type == CTRL_LISTBOX);
720
721 #if !GTK_CHECK_VERSION(2,4,0)
722     if (uc->menu || uc->list) {
723         GList *children;
724         GtkWidget *item, *activeitem;
725
726         assert(uc->ctrl->generic.type == CTRL_EDITBOX ||
727                uc->ctrl->generic.type == CTRL_LISTBOX);
728         assert(uc->menu != NULL || uc->list != NULL);
729
730         children = gtk_container_children(GTK_CONTAINER(uc->menu ? uc->menu :
731                                                         uc->list));
732         item = GTK_WIDGET(g_list_nth_data(children, index));
733         g_list_free(children);
734
735         if (uc->menu) {
736             activeitem = gtk_menu_get_active(GTK_MENU(uc->menu));
737             return item == activeitem;
738         } else {
739             return GTK_WIDGET_STATE(item) == GTK_STATE_SELECTED;
740         }
741     }
742 #else
743     if (uc->combo) {
744         /*
745          * This API function already does the right thing in the
746          * case of no current selection.
747          */
748         return gtk_combo_box_get_active(GTK_COMBO_BOX(uc->combo)) == index;
749     }
750 #endif
751 #if GTK_CHECK_VERSION(2,0,0)
752     if (uc->treeview) {
753         GtkTreeSelection *treesel;
754         GtkTreePath *path;
755         int ret;
756
757         assert(uc->treeview != NULL);
758         treesel = gtk_tree_view_get_selection(GTK_TREE_VIEW(uc->treeview));
759
760         path = gtk_tree_path_new_from_indices(index, -1);
761         ret = gtk_tree_selection_path_is_selected(treesel, path);
762         gtk_tree_path_free(path);
763
764         return ret;
765     }
766 #endif
767     assert(!"We shouldn't get here");
768     return -1;                         /* placate dataflow analysis */
769 }
770
771 void dlg_listbox_select(union control *ctrl, void *dlg, int index)
772 {
773     struct dlgparam *dp = (struct dlgparam *)dlg;
774     struct uctrl *uc = dlg_find_byctrl(dp, ctrl);
775
776     assert(uc->ctrl->generic.type == CTRL_EDITBOX ||
777            uc->ctrl->generic.type == CTRL_LISTBOX);
778
779 #if !GTK_CHECK_VERSION(2,4,0)
780     if (uc->optmenu) {
781         gtk_option_menu_set_history(GTK_OPTION_MENU(uc->optmenu), index);
782         return;
783     } 
784     if (uc->list) {
785         int nitems;
786         GList *items;
787         gdouble newtop, newbot;
788
789         gtk_list_select_item(GTK_LIST(uc->list), index);
790
791         /*
792          * Scroll the list box if necessary to ensure the newly
793          * selected item is visible.
794          */
795         items = gtk_container_children(GTK_CONTAINER(uc->list));
796         nitems = g_list_length(items);
797         if (nitems > 0) {
798             int modified = FALSE;
799             g_list_free(items);
800             newtop = uc->adj->lower +
801                 (uc->adj->upper - uc->adj->lower) * index / nitems;
802             newbot = uc->adj->lower +
803                 (uc->adj->upper - uc->adj->lower) * (index+1) / nitems;
804             if (uc->adj->value > newtop) {
805                 modified = TRUE;
806                 uc->adj->value = newtop;
807             } else if (uc->adj->value < newbot - uc->adj->page_size) {
808                 modified = TRUE;
809                 uc->adj->value = newbot - uc->adj->page_size;
810             }
811             if (modified)
812                 gtk_adjustment_value_changed(uc->adj);
813         }
814         return;
815     }
816 #else
817     if (uc->combo) {
818         gtk_combo_box_set_active(GTK_COMBO_BOX(uc->combo), index);
819         return;
820     }
821 #endif
822 #if GTK_CHECK_VERSION(2,0,0)
823     if (uc->treeview) {
824         GtkTreeSelection *treesel;
825         GtkTreePath *path;
826
827         treesel = gtk_tree_view_get_selection(GTK_TREE_VIEW(uc->treeview));
828
829         path = gtk_tree_path_new_from_indices(index, -1);
830         gtk_tree_selection_select_path(treesel, path);
831         gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(uc->treeview),
832                                      path, NULL, FALSE, 0.0, 0.0);
833         gtk_tree_path_free(path);
834         return;
835     }
836 #endif
837     assert(!"We shouldn't get here");
838 }
839
840 void dlg_text_set(union control *ctrl, void *dlg, char const *text)
841 {
842     struct dlgparam *dp = (struct dlgparam *)dlg;
843     struct uctrl *uc = dlg_find_byctrl(dp, ctrl);
844
845     assert(uc->ctrl->generic.type == CTRL_TEXT);
846     assert(uc->text != NULL);
847
848     gtk_label_set_text(GTK_LABEL(uc->text), text);
849 }
850
851 void dlg_label_change(union control *ctrl, void *dlg, char const *text)
852 {
853     struct dlgparam *dp = (struct dlgparam *)dlg;
854     struct uctrl *uc = dlg_find_byctrl(dp, ctrl);
855
856     switch (uc->ctrl->generic.type) {
857       case CTRL_BUTTON:
858         gtk_label_set_text(GTK_LABEL(uc->toplevel), text);
859         shortcut_highlight(uc->toplevel, ctrl->button.shortcut);
860         break;
861       case CTRL_CHECKBOX:
862         gtk_label_set_text(GTK_LABEL(uc->toplevel), text);
863         shortcut_highlight(uc->toplevel, ctrl->checkbox.shortcut);
864         break;
865       case CTRL_RADIO:
866         gtk_label_set_text(GTK_LABEL(uc->label), text);
867         shortcut_highlight(uc->label, ctrl->radio.shortcut);
868         break;
869       case CTRL_EDITBOX:
870         gtk_label_set_text(GTK_LABEL(uc->label), text);
871         shortcut_highlight(uc->label, ctrl->editbox.shortcut);
872         break;
873       case CTRL_FILESELECT:
874         gtk_label_set_text(GTK_LABEL(uc->label), text);
875         shortcut_highlight(uc->label, ctrl->fileselect.shortcut);
876         break;
877       case CTRL_FONTSELECT:
878         gtk_label_set_text(GTK_LABEL(uc->label), text);
879         shortcut_highlight(uc->label, ctrl->fontselect.shortcut);
880         break;
881       case CTRL_LISTBOX:
882         gtk_label_set_text(GTK_LABEL(uc->label), text);
883         shortcut_highlight(uc->label, ctrl->listbox.shortcut);
884         break;
885       default:
886         assert(!"This shouldn't happen");
887         break;
888     }
889 }
890
891 void dlg_filesel_set(union control *ctrl, void *dlg, Filename *fn)
892 {
893     struct dlgparam *dp = (struct dlgparam *)dlg;
894     struct uctrl *uc = dlg_find_byctrl(dp, ctrl);
895     /* We must copy fn->path before passing it to gtk_entry_set_text.
896      * See comment in dlg_editbox_set() for the reasons. */
897     char *duppath = dupstr(fn->path);
898     assert(uc->ctrl->generic.type == CTRL_FILESELECT);
899     assert(uc->entry != NULL);
900     gtk_entry_set_text(GTK_ENTRY(uc->entry), duppath);
901     sfree(duppath);
902 }
903
904 Filename *dlg_filesel_get(union control *ctrl, void *dlg)
905 {
906     struct dlgparam *dp = (struct dlgparam *)dlg;
907     struct uctrl *uc = dlg_find_byctrl(dp, ctrl);
908     assert(uc->ctrl->generic.type == CTRL_FILESELECT);
909     assert(uc->entry != NULL);
910     return filename_from_str(gtk_entry_get_text(GTK_ENTRY(uc->entry)));
911 }
912
913 void dlg_fontsel_set(union control *ctrl, void *dlg, FontSpec *fs)
914 {
915     struct dlgparam *dp = (struct dlgparam *)dlg;
916     struct uctrl *uc = dlg_find_byctrl(dp, ctrl);
917     /* We must copy fs->name before passing it to gtk_entry_set_text.
918      * See comment in dlg_editbox_set() for the reasons. */
919     char *dupname = dupstr(fs->name);
920     assert(uc->ctrl->generic.type == CTRL_FONTSELECT);
921     assert(uc->entry != NULL);
922     gtk_entry_set_text(GTK_ENTRY(uc->entry), dupname);
923     sfree(dupname);
924 }
925
926 FontSpec *dlg_fontsel_get(union control *ctrl, void *dlg)
927 {
928     struct dlgparam *dp = (struct dlgparam *)dlg;
929     struct uctrl *uc = dlg_find_byctrl(dp, ctrl);
930     assert(uc->ctrl->generic.type == CTRL_FONTSELECT);
931     assert(uc->entry != NULL);
932     return fontspec_new(gtk_entry_get_text(GTK_ENTRY(uc->entry)));
933 }
934
935 /*
936  * Bracketing a large set of updates in these two functions will
937  * cause the front end (if possible) to delay updating the screen
938  * until it's all complete, thus avoiding flicker.
939  */
940 void dlg_update_start(union control *ctrl, void *dlg)
941 {
942     /*
943      * Apparently we can't do this at all in GTK. GtkCList supports
944      * freeze and thaw, but not GtkList. Bah.
945      */
946 }
947
948 void dlg_update_done(union control *ctrl, void *dlg)
949 {
950     /*
951      * Apparently we can't do this at all in GTK. GtkCList supports
952      * freeze and thaw, but not GtkList. Bah.
953      */
954 }
955
956 void dlg_set_focus(union control *ctrl, void *dlg)
957 {
958     struct dlgparam *dp = (struct dlgparam *)dlg;
959     struct uctrl *uc = dlg_find_byctrl(dp, ctrl);
960
961     switch (ctrl->generic.type) {
962       case CTRL_CHECKBOX:
963       case CTRL_BUTTON:
964         /* Check boxes and buttons get the focus _and_ get toggled. */
965         gtk_widget_grab_focus(uc->toplevel);
966         break;
967       case CTRL_FILESELECT:
968       case CTRL_FONTSELECT:
969       case CTRL_EDITBOX:
970         if (uc->entry) {
971             /* Anything containing an edit box gets that focused. */
972             gtk_widget_grab_focus(uc->entry);
973         }
974 #if GTK_CHECK_VERSION(2,4,0)
975         else if (uc->combo) {
976             /* Failing that, there'll be a combo box. */
977             gtk_widget_grab_focus(uc->combo);
978         }
979 #endif
980         break;
981       case CTRL_RADIO:
982         /*
983          * Radio buttons: we find the currently selected button and
984          * focus it.
985          */
986         {
987             int i;
988             for (i = 0; i < ctrl->radio.nbuttons; i++)
989                 if (gtk_toggle_button_get_active
990                     (GTK_TOGGLE_BUTTON(uc->buttons[i]))) {
991                     gtk_widget_grab_focus(uc->buttons[i]);
992                 }
993         }
994         break;
995       case CTRL_LISTBOX:
996 #if !GTK_CHECK_VERSION(2,4,0)
997         if (uc->optmenu) {
998             gtk_widget_grab_focus(uc->optmenu);
999             break;
1000         }
1001 #else
1002         if (uc->combo) {
1003             gtk_widget_grab_focus(uc->combo);
1004             break;
1005         }
1006 #endif
1007 #if !GTK_CHECK_VERSION(2,0,0)
1008         if (uc->list) {
1009             /*
1010              * For GTK-1 style list boxes, we tell it to focus one
1011              * of its children, which appears to do the Right
1012              * Thing.
1013              */
1014             gtk_container_focus(GTK_CONTAINER(uc->list), GTK_DIR_TAB_FORWARD);
1015             break;
1016         }
1017 #else
1018         if (uc->treeview) {
1019             gtk_widget_grab_focus(uc->treeview);
1020             break;
1021         }
1022 #endif
1023         assert(!"We shouldn't get here");
1024         break;
1025     }
1026 }
1027
1028 /*
1029  * During event processing, you might well want to give an error
1030  * indication to the user. dlg_beep() is a quick and easy generic
1031  * error; dlg_error() puts up a message-box or equivalent.
1032  */
1033 void dlg_beep(void *dlg)
1034 {
1035     gdk_beep();
1036 }
1037
1038 static void errmsg_button_clicked(GtkButton *button, gpointer data)
1039 {
1040     gtk_widget_destroy(GTK_WIDGET(data));
1041 }
1042
1043 static void set_transient_window_pos(GtkWidget *parent, GtkWidget *child)
1044 {
1045 #if !GTK_CHECK_VERSION(2,0,0)
1046     gint x, y, w, h, dx, dy;
1047     GtkRequisition req;
1048     gtk_window_set_position(GTK_WINDOW(child), GTK_WIN_POS_NONE);
1049     gtk_widget_size_request(GTK_WIDGET(child), &req);
1050
1051     gdk_window_get_origin(gtk_widget_get_window(GTK_WIDGET(parent)), &x, &y);
1052     gdk_window_get_size(gtk_widget_get_window(GTK_WIDGET(parent)), &w, &h);
1053
1054     /*
1055      * One corner of the transient will be offset inwards, by 1/4
1056      * of the parent window's size, from the corresponding corner
1057      * of the parent window. The corner will be chosen so as to
1058      * place the transient closer to the centre of the screen; this
1059      * should avoid transients going off the edge of the screen on
1060      * a regular basis.
1061      */
1062     if (x + w/2 < gdk_screen_width() / 2)
1063         dx = x + w/4;                  /* work from left edges */
1064     else
1065         dx = x + 3*w/4 - req.width;    /* work from right edges */
1066     if (y + h/2 < gdk_screen_height() / 2)
1067         dy = y + h/4;                  /* work from top edges */
1068     else
1069         dy = y + 3*h/4 - req.height;   /* work from bottom edges */
1070     gtk_widget_set_uposition(GTK_WIDGET(child), dx, dy);
1071 #endif
1072 }
1073
1074 void dlg_error_msg(void *dlg, const char *msg)
1075 {
1076     struct dlgparam *dp = (struct dlgparam *)dlg;
1077     GtkWidget *window, *hbox, *text, *ok;
1078
1079     window = gtk_dialog_new();
1080     text = gtk_label_new(msg);
1081     gtk_misc_set_alignment(GTK_MISC(text), 0.0, 0.0);
1082     hbox = gtk_hbox_new(FALSE, 0);
1083     gtk_box_pack_start(GTK_BOX(hbox), text, FALSE, FALSE, 20);
1084     gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(window))),
1085                        hbox, FALSE, FALSE, 20);
1086     gtk_widget_show(text);
1087     gtk_widget_show(hbox);
1088     gtk_window_set_title(GTK_WINDOW(window), "Error");
1089     gtk_label_set_line_wrap(GTK_LABEL(text), TRUE);
1090     ok = gtk_button_new_with_label("OK");
1091     gtk_box_pack_end(GTK_BOX(gtk_dialog_get_action_area(GTK_DIALOG(window))),
1092                      ok, FALSE, FALSE, 0);
1093     gtk_widget_show(ok);
1094     gtk_widget_set_can_default(ok, TRUE);
1095     gtk_window_set_default(GTK_WINDOW(window), ok);
1096     g_signal_connect(G_OBJECT(ok), "clicked",
1097                      G_CALLBACK(errmsg_button_clicked), window);
1098     g_signal_connect(G_OBJECT(window), "destroy",
1099                      G_CALLBACK(window_destroy), NULL);
1100     gtk_window_set_modal(GTK_WINDOW(window), TRUE);
1101     gtk_window_set_transient_for(GTK_WINDOW(window), GTK_WINDOW(dp->window));
1102     set_transient_window_pos(dp->window, window);
1103     gtk_widget_show(window);
1104     gtk_main();
1105     post_main();
1106 }
1107
1108 /*
1109  * This function signals to the front end that the dialog's
1110  * processing is completed, and passes an integer value (typically
1111  * a success status).
1112  */
1113 void dlg_end(void *dlg, int value)
1114 {
1115     struct dlgparam *dp = (struct dlgparam *)dlg;
1116     dp->retval = value;
1117     gtk_widget_destroy(dp->window);
1118 }
1119
1120 void dlg_refresh(union control *ctrl, void *dlg)
1121 {
1122     struct dlgparam *dp = (struct dlgparam *)dlg;
1123     struct uctrl *uc;
1124
1125     if (ctrl) {
1126         if (ctrl->generic.handler != NULL)
1127             ctrl->generic.handler(ctrl, dp, dp->data, EVENT_REFRESH);
1128     } else {
1129         int i;
1130
1131         for (i = 0; (uc = index234(dp->byctrl, i)) != NULL; i++) {
1132             assert(uc->ctrl != NULL);
1133             if (uc->ctrl->generic.handler != NULL)
1134                 uc->ctrl->generic.handler(uc->ctrl, dp,
1135                                           dp->data, EVENT_REFRESH);
1136         }
1137     }
1138 }
1139
1140 void dlg_coloursel_start(union control *ctrl, void *dlg, int r, int g, int b)
1141 {
1142     struct dlgparam *dp = (struct dlgparam *)dlg;
1143     struct uctrl *uc = dlg_find_byctrl(dp, ctrl);
1144
1145 #if GTK_CHECK_VERSION(3,0,0)
1146     GtkWidget *coloursel =
1147         gtk_color_chooser_dialog_new("Select a colour",
1148                                      GTK_WINDOW(dp->window));
1149     gtk_color_chooser_set_use_alpha(GTK_COLOR_CHOOSER(coloursel), FALSE);
1150 #else
1151     GtkWidget *okbutton, *cancelbutton;
1152     GtkWidget *coloursel =
1153         gtk_color_selection_dialog_new("Select a colour");
1154     GtkColorSelectionDialog *ccs = GTK_COLOR_SELECTION_DIALOG(coloursel);
1155     GtkColorSelection *cs = GTK_COLOR_SELECTION
1156         (gtk_color_selection_dialog_get_color_selection(ccs));
1157     gtk_color_selection_set_has_opacity_control(cs, FALSE);
1158 #endif
1159
1160     dp->coloursel_result.ok = FALSE;
1161
1162     gtk_window_set_modal(GTK_WINDOW(coloursel), TRUE);
1163
1164 #if GTK_CHECK_VERSION(3,0,0)
1165     {
1166         GdkRGBA rgba;
1167         rgba.red = r / 255.0;
1168         rgba.green = g / 255.0;
1169         rgba.blue = b / 255.0;
1170         rgba.alpha = 1.0;              /* fully opaque! */
1171         gtk_color_chooser_set_rgba(GTK_COLOR_CHOOSER(coloursel), &rgba);
1172     }
1173 #elif GTK_CHECK_VERSION(2,0,0)
1174     {
1175         GdkColor col;
1176         col.red = r * 0x0101;
1177         col.green = g * 0x0101;
1178         col.blue = b * 0x0101;
1179         gtk_color_selection_set_current_color(cs, &col);
1180     }
1181 #else
1182     {
1183         gdouble cvals[4];
1184         cvals[0] = r / 255.0;
1185         cvals[1] = g / 255.0;
1186         cvals[2] = b / 255.0;
1187         cvals[3] = 1.0;                /* fully opaque! */
1188         gtk_color_selection_set_color(cs, cvals);
1189     }
1190 #endif
1191
1192     g_object_set_data(G_OBJECT(coloursel), "user-data", (gpointer)uc);
1193
1194 #if GTK_CHECK_VERSION(3,0,0)
1195     g_signal_connect(G_OBJECT(coloursel), "response",
1196                      G_CALLBACK(colourchoose_response), (gpointer)dp);
1197 #else
1198
1199 #if GTK_CHECK_VERSION(2,0,0)
1200     g_object_get(G_OBJECT(ccs),
1201                  "ok-button", &okbutton,
1202                  "cancel-button", &cancelbutton,
1203                  (const char *)NULL);
1204 #else
1205     okbutton = ccs->ok_button;
1206     cancelbutton = ccs->cancel_button;
1207 #endif
1208     g_object_set_data(G_OBJECT(okbutton), "user-data",
1209                         (gpointer)coloursel);
1210     g_object_set_data(G_OBJECT(cancelbutton), "user-data",
1211                         (gpointer)coloursel);
1212     g_signal_connect(G_OBJECT(okbutton), "clicked",
1213                      G_CALLBACK(coloursel_ok), (gpointer)dp);
1214     g_signal_connect(G_OBJECT(cancelbutton), "clicked",
1215                      G_CALLBACK(coloursel_cancel), (gpointer)dp);
1216     g_signal_connect_swapped(G_OBJECT(okbutton), "clicked",
1217                              G_CALLBACK(gtk_widget_destroy),
1218                              (gpointer)coloursel);
1219     g_signal_connect_swapped(G_OBJECT(cancelbutton), "clicked",
1220                              G_CALLBACK(gtk_widget_destroy),
1221                              (gpointer)coloursel);
1222 #endif
1223     gtk_widget_show(coloursel);
1224 }
1225
1226 int dlg_coloursel_results(union control *ctrl, void *dlg,
1227                           int *r, int *g, int *b)
1228 {
1229     struct dlgparam *dp = (struct dlgparam *)dlg;
1230     if (dp->coloursel_result.ok) {
1231         *r = dp->coloursel_result.r;
1232         *g = dp->coloursel_result.g;
1233         *b = dp->coloursel_result.b;
1234         return 1;
1235     } else
1236         return 0;
1237 }
1238
1239 /* ----------------------------------------------------------------------
1240  * Signal handlers while the dialog box is active.
1241  */
1242
1243 static gboolean widget_focus(GtkWidget *widget, GdkEventFocus *event,
1244                              gpointer data)
1245 {
1246     struct dlgparam *dp = (struct dlgparam *)data;
1247     struct uctrl *uc = dlg_find_bywidget(dp, widget);
1248     union control *focus;
1249
1250     if (uc && uc->ctrl)
1251         focus = uc->ctrl;
1252     else
1253         focus = NULL;
1254
1255     if (focus != dp->currfocus) {
1256         dp->lastfocus = dp->currfocus;
1257         dp->currfocus = focus;
1258     }
1259
1260     return FALSE;
1261 }
1262
1263 static void button_clicked(GtkButton *button, gpointer data)
1264 {
1265     struct dlgparam *dp = (struct dlgparam *)data;
1266     struct uctrl *uc = dlg_find_bywidget(dp, GTK_WIDGET(button));
1267     uc->ctrl->generic.handler(uc->ctrl, dp, dp->data, EVENT_ACTION);
1268 }
1269
1270 static void button_toggled(GtkToggleButton *tb, gpointer data)
1271 {
1272     struct dlgparam *dp = (struct dlgparam *)data;
1273     struct uctrl *uc = dlg_find_bywidget(dp, GTK_WIDGET(tb));
1274     uc->ctrl->generic.handler(uc->ctrl, dp, dp->data, EVENT_VALCHANGE);
1275 }
1276
1277 static gboolean editbox_key(GtkWidget *widget, GdkEventKey *event,
1278                             gpointer data)
1279 {
1280     /*
1281      * GtkEntry has a nasty habit of eating the Return key, which
1282      * is unhelpful since it doesn't actually _do_ anything with it
1283      * (it calls gtk_widget_activate, but our edit boxes never need
1284      * activating). So I catch Return before GtkEntry sees it, and
1285      * pass it straight on to the parent widget. Effect: hitting
1286      * Return in an edit box will now activate the default button
1287      * in the dialog just like it will everywhere else.
1288      */
1289     GtkWidget *parent = gtk_widget_get_parent(widget);
1290     if (event->keyval == GDK_KEY_Return && parent != NULL) {
1291         gboolean return_val;
1292         g_signal_stop_emission_by_name(G_OBJECT(widget), "key_press_event");
1293         g_signal_emit_by_name(G_OBJECT(parent), "key_press_event",
1294                               event, &return_val);
1295         return return_val;
1296     }
1297     return FALSE;
1298 }
1299
1300 static void editbox_changed(GtkEditable *ed, gpointer data)
1301 {
1302     struct dlgparam *dp = (struct dlgparam *)data;
1303     if (!(dp->flags & FLAG_UPDATING_COMBO_LIST)) {
1304         struct uctrl *uc = dlg_find_bywidget(dp, GTK_WIDGET(ed));
1305         uc->ctrl->generic.handler(uc->ctrl, dp, dp->data, EVENT_VALCHANGE);
1306     }
1307 }
1308
1309 static gboolean editbox_lostfocus(GtkWidget *ed, GdkEventFocus *event,
1310                                   gpointer data)
1311 {
1312     struct dlgparam *dp = (struct dlgparam *)data;
1313     struct uctrl *uc = dlg_find_bywidget(dp, GTK_WIDGET(ed));
1314     uc->ctrl->generic.handler(uc->ctrl, dp, dp->data, EVENT_REFRESH);
1315     return FALSE;
1316 }
1317
1318 #if !GTK_CHECK_VERSION(2,0,0)
1319
1320 /*
1321  * GTK 1 list box event handlers.
1322  */
1323
1324 static gboolean listitem_key(GtkWidget *item, GdkEventKey *event,
1325                              gpointer data, int multiple)
1326 {
1327     GtkAdjustment *adj = GTK_ADJUSTMENT(data);
1328
1329     if (event->keyval == GDK_Up || event->keyval == GDK_KP_Up ||
1330         event->keyval == GDK_Down || event->keyval == GDK_KP_Down ||
1331         event->keyval == GDK_Page_Up || event->keyval == GDK_KP_Page_Up ||
1332         event->keyval == GDK_Page_Down || event->keyval == GDK_KP_Page_Down) {
1333         /*
1334          * Up, Down, PgUp or PgDn have been pressed on a ListItem
1335          * in a list box. So, if the list box is single-selection:
1336          * 
1337          *  - if the list item in question isn't already selected,
1338          *    we simply select it.
1339          *  - otherwise, we find the next one (or next
1340          *    however-far-away) in whichever direction we're going,
1341          *    and select that.
1342          *     + in this case, we must also fiddle with the
1343          *       scrollbar to ensure the newly selected item is
1344          *       actually visible.
1345          * 
1346          * If it's multiple-selection, we do all of the above
1347          * except actually selecting anything, so we move the focus
1348          * and fiddle the scrollbar to follow it.
1349          */
1350         GtkWidget *list = item->parent;
1351
1352         g_signal_stop_emission_by_name(G_OBJECT(item), "key_press_event");
1353
1354         if (!multiple &&
1355             GTK_WIDGET_STATE(item) != GTK_STATE_SELECTED) {
1356                 gtk_list_select_child(GTK_LIST(list), item);
1357         } else {
1358             int direction =
1359                 (event->keyval==GDK_Up || event->keyval==GDK_KP_Up ||
1360                  event->keyval==GDK_Page_Up || event->keyval==GDK_KP_Page_Up)
1361                 ? -1 : +1;
1362             int step =
1363                 (event->keyval==GDK_Page_Down || 
1364                  event->keyval==GDK_KP_Page_Down ||
1365                  event->keyval==GDK_Page_Up || event->keyval==GDK_KP_Page_Up)
1366                 ? 2 : 1;
1367             int i, n;
1368             GList *children, *chead;
1369
1370             chead = children = gtk_container_children(GTK_CONTAINER(list));
1371
1372             n = g_list_length(children);
1373
1374             if (step == 2) {
1375                 /*
1376                  * Figure out how many list items to a screenful,
1377                  * and adjust the step appropriately.
1378                  */
1379                 step = 0.5 + adj->page_size * n / (adj->upper - adj->lower);
1380                 step--;                /* go by one less than that */
1381             }
1382
1383             i = 0;
1384             while (children != NULL) {
1385                 if (item == children->data)
1386                     break;
1387                 children = children->next;
1388                 i++;
1389             }
1390
1391             while (step > 0) {
1392                 if (direction < 0 && i > 0)
1393                     children = children->prev, i--;
1394                 else if (direction > 0 && i < n-1)
1395                     children = children->next, i++;
1396                 step--;
1397             }
1398
1399             if (children && children->data) {
1400                 if (!multiple)
1401                     gtk_list_select_child(GTK_LIST(list),
1402                                           GTK_WIDGET(children->data));
1403                 gtk_widget_grab_focus(GTK_WIDGET(children->data));
1404                 gtk_adjustment_clamp_page
1405                     (adj,
1406                      adj->lower + (adj->upper-adj->lower) * i / n,
1407                      adj->lower + (adj->upper-adj->lower) * (i+1) / n);
1408             }
1409
1410             g_list_free(chead);
1411         }
1412         return TRUE;
1413     }
1414
1415     return FALSE;
1416 }
1417
1418 static gboolean listitem_single_key(GtkWidget *item, GdkEventKey *event,
1419                                     gpointer data)
1420 {
1421     return listitem_key(item, event, data, FALSE);
1422 }
1423
1424 static gboolean listitem_multi_key(GtkWidget *item, GdkEventKey *event,
1425                                    gpointer data)
1426 {
1427     return listitem_key(item, event, data, TRUE);
1428 }
1429
1430 static gboolean listitem_button_press(GtkWidget *item, GdkEventButton *event,
1431                                       gpointer data)
1432 {
1433     struct dlgparam *dp = (struct dlgparam *)data;
1434     struct uctrl *uc = dlg_find_bywidget(dp, GTK_WIDGET(item));
1435     switch (event->type) {
1436     default:
1437     case GDK_BUTTON_PRESS: uc->nclicks = 1; break;
1438     case GDK_2BUTTON_PRESS: uc->nclicks = 2; break;
1439     case GDK_3BUTTON_PRESS: uc->nclicks = 3; break;
1440     }
1441     return FALSE;
1442 }
1443
1444 static gboolean listitem_button_release(GtkWidget *item, GdkEventButton *event,
1445                                         gpointer data)
1446 {
1447     struct dlgparam *dp = (struct dlgparam *)data;
1448     struct uctrl *uc = dlg_find_bywidget(dp, GTK_WIDGET(item));
1449     if (uc->nclicks>1) {
1450         uc->ctrl->generic.handler(uc->ctrl, dp, dp->data, EVENT_ACTION);
1451         return TRUE;
1452     }
1453     return FALSE;
1454 }
1455
1456 static void list_selchange(GtkList *list, gpointer data)
1457 {
1458     struct dlgparam *dp = (struct dlgparam *)data;
1459     struct uctrl *uc = dlg_find_bywidget(dp, GTK_WIDGET(list));
1460     if (!uc) return;
1461     uc->ctrl->generic.handler(uc->ctrl, dp, dp->data, EVENT_SELCHANGE);
1462 }
1463
1464 static void draglist_move(struct dlgparam *dp, struct uctrl *uc, int direction)
1465 {
1466     int index = dlg_listbox_index(uc->ctrl, dp);
1467     GList *children = gtk_container_children(GTK_CONTAINER(uc->list));
1468     GtkWidget *child;
1469
1470     if ((index < 0) ||
1471         (index == 0 && direction < 0) ||
1472         (index == g_list_length(children)-1 && direction > 0)) {
1473         gdk_beep();
1474         return;
1475     }
1476
1477     child = g_list_nth_data(children, index);
1478     gtk_widget_ref(child);
1479     gtk_list_clear_items(GTK_LIST(uc->list), index, index+1);
1480     g_list_free(children);
1481
1482     children = NULL;
1483     children = g_list_append(children, child);
1484     gtk_list_insert_items(GTK_LIST(uc->list), children, index + direction);
1485     gtk_list_select_item(GTK_LIST(uc->list), index + direction);
1486     uc->ctrl->generic.handler(uc->ctrl, dp, dp->data, EVENT_VALCHANGE);
1487 }
1488
1489 static void draglist_up(GtkButton *button, gpointer data)
1490 {
1491     struct dlgparam *dp = (struct dlgparam *)data;
1492     struct uctrl *uc = dlg_find_bywidget(dp, GTK_WIDGET(button));
1493     draglist_move(dp, uc, -1);
1494 }
1495
1496 static void draglist_down(GtkButton *button, gpointer data)
1497 {
1498     struct dlgparam *dp = (struct dlgparam *)data;
1499     struct uctrl *uc = dlg_find_bywidget(dp, GTK_WIDGET(button));
1500     draglist_move(dp, uc, +1);
1501 }
1502
1503 #else /* !GTK_CHECK_VERSION(2,0,0) */
1504
1505 /*
1506  * GTK 2 list box event handlers.
1507  */
1508
1509 static void listbox_doubleclick(GtkTreeView *treeview, GtkTreePath *path,
1510                                 GtkTreeViewColumn *column, gpointer data)
1511 {
1512     struct dlgparam *dp = (struct dlgparam *)data;
1513     struct uctrl *uc = dlg_find_bywidget(dp, GTK_WIDGET(treeview));
1514     if (uc)
1515         uc->ctrl->generic.handler(uc->ctrl, dp, dp->data, EVENT_ACTION);
1516 }
1517
1518 static void listbox_selchange(GtkTreeSelection *treeselection,
1519                               gpointer data)
1520 {
1521     struct dlgparam *dp = (struct dlgparam *)data;
1522     GtkTreeView *tree = gtk_tree_selection_get_tree_view(treeselection);
1523     struct uctrl *uc = dlg_find_bywidget(dp, GTK_WIDGET(tree));
1524     if (uc)
1525         uc->ctrl->generic.handler(uc->ctrl, dp, dp->data, EVENT_SELCHANGE);
1526 }
1527
1528 struct draglist_valchange_ctx {
1529     struct uctrl *uc;
1530     struct dlgparam *dp;
1531 };
1532
1533 static gboolean draglist_valchange(gpointer data)
1534 {
1535     struct draglist_valchange_ctx *ctx =
1536         (struct draglist_valchange_ctx *)data;
1537
1538     ctx->uc->ctrl->generic.handler(ctx->uc->ctrl, ctx->dp,
1539                                    ctx->dp->data, EVENT_VALCHANGE);
1540
1541     sfree(ctx);
1542
1543     return FALSE;
1544 }
1545
1546 static void listbox_reorder(GtkTreeModel *treemodel, GtkTreePath *path,
1547                             GtkTreeIter *iter, gpointer data)
1548 {
1549     struct dlgparam *dp = (struct dlgparam *)data;
1550     gpointer tree;
1551     struct uctrl *uc;
1552
1553     if (dp->flags & FLAG_UPDATING_LISTBOX)
1554         return;                        /* not a user drag operation */
1555
1556     tree = g_object_get_data(G_OBJECT(treemodel), "user-data");
1557     uc = dlg_find_bywidget(dp, GTK_WIDGET(tree));
1558     if (uc) {
1559         /*
1560          * We should cause EVENT_VALCHANGE on the list box, now
1561          * that its rows have been reordered. However, the GTK 2
1562          * docs say that at the point this signal is received the
1563          * new row might not have actually been filled in yet.
1564          *
1565          * (So what smegging use is it then, eh? Don't suppose it
1566          * occurred to you at any point that letting the
1567          * application know _after_ the reordering was compelete
1568          * might be helpful to someone?)
1569          *
1570          * To get round this, I schedule an idle function, which I
1571          * hope won't be called until the main event loop is
1572          * re-entered after the drag-and-drop handler has finished
1573          * furtling with the list store.
1574          */
1575         struct draglist_valchange_ctx *ctx =
1576             snew(struct draglist_valchange_ctx);
1577         ctx->uc = uc;
1578         ctx->dp = dp;
1579         g_idle_add(draglist_valchange, ctx);
1580     }
1581 }
1582
1583 #endif /* !GTK_CHECK_VERSION(2,0,0) */
1584
1585 #if !GTK_CHECK_VERSION(2,4,0)
1586
1587 static void menuitem_activate(GtkMenuItem *item, gpointer data)
1588 {
1589     struct dlgparam *dp = (struct dlgparam *)data;
1590     GtkWidget *menushell = GTK_WIDGET(item)->parent;
1591     gpointer optmenu = g_object_get_data(G_OBJECT(menushell), "user-data");
1592     struct uctrl *uc = dlg_find_bywidget(dp, GTK_WIDGET(optmenu));
1593     uc->ctrl->generic.handler(uc->ctrl, dp, dp->data, EVENT_SELCHANGE);
1594 }
1595
1596 #else
1597
1598 static void droplist_selchange(GtkComboBox *combo, gpointer data)
1599 {
1600     struct dlgparam *dp = (struct dlgparam *)data;
1601     struct uctrl *uc = dlg_find_bywidget(dp, GTK_WIDGET(combo));
1602     if (uc)
1603         uc->ctrl->generic.handler(uc->ctrl, dp, dp->data, EVENT_SELCHANGE);
1604 }
1605
1606 #endif /* !GTK_CHECK_VERSION(2,4,0) */
1607
1608 #ifdef USE_GTK_FILE_CHOOSER_DIALOG
1609 static void filechoose_response(GtkDialog *dialog, gint response,
1610                                 gpointer data)
1611 {
1612     /* struct dlgparam *dp = (struct dlgparam *)data; */
1613     struct uctrl *uc = g_object_get_data(G_OBJECT(dialog), "user-data");
1614     if (response == GTK_RESPONSE_ACCEPT) {
1615         gchar *name = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));
1616     gtk_entry_set_text(GTK_ENTRY(uc->entry), name);
1617         g_free(name);
1618     }
1619     gtk_widget_destroy(GTK_WIDGET(dialog));
1620 }
1621 #else
1622 static void filesel_ok(GtkButton *button, gpointer data)
1623 {
1624     /* struct dlgparam *dp = (struct dlgparam *)data; */
1625     gpointer filesel = g_object_get_data(G_OBJECT(button), "user-data");
1626     struct uctrl *uc = g_object_get_data(G_OBJECT(filesel), "user-data");
1627     const char *name = gtk_file_selection_get_filename
1628         (GTK_FILE_SELECTION(filesel));
1629     gtk_entry_set_text(GTK_ENTRY(uc->entry), name);
1630 }
1631 #endif
1632
1633 static void fontsel_ok(GtkButton *button, gpointer data)
1634 {
1635     /* struct dlgparam *dp = (struct dlgparam *)data; */
1636
1637 #if !GTK_CHECK_VERSION(2,0,0)
1638
1639     gpointer fontsel = g_object_get_data(G_OBJECT(button), "user-data");
1640     struct uctrl *uc = g_object_get_data(G_OBJECT(fontsel), "user-data");
1641     const char *name = gtk_font_selection_dialog_get_font_name
1642         (GTK_FONT_SELECTION_DIALOG(fontsel));
1643     gtk_entry_set_text(GTK_ENTRY(uc->entry), name);
1644
1645 #else
1646
1647     unifontsel *fontsel = (unifontsel *)g_object_get_data
1648         (G_OBJECT(button), "user-data");
1649     struct uctrl *uc = (struct uctrl *)fontsel->user_data;
1650     char *name = unifontsel_get_name(fontsel);
1651     assert(name);              /* should always be ok after OK pressed */
1652     gtk_entry_set_text(GTK_ENTRY(uc->entry), name);
1653     sfree(name);
1654
1655 #endif
1656 }
1657
1658 #if GTK_CHECK_VERSION(3,0,0)
1659
1660 static void colourchoose_response(GtkDialog *dialog,
1661                                   gint response_id, gpointer data)
1662 {
1663     struct dlgparam *dp = (struct dlgparam *)data;
1664     struct uctrl *uc = g_object_get_data(G_OBJECT(dialog), "user-data");
1665
1666     if (response_id == GTK_RESPONSE_OK) {
1667         GdkRGBA rgba;
1668         gtk_color_chooser_get_rgba(GTK_COLOR_CHOOSER(dialog), &rgba);
1669         dp->coloursel_result.r = (int) (255 * rgba.red);
1670         dp->coloursel_result.g = (int) (255 * rgba.green);
1671         dp->coloursel_result.b = (int) (255 * rgba.blue);
1672         dp->coloursel_result.ok = TRUE;
1673     } else {
1674         dp->coloursel_result.ok = FALSE;
1675     }
1676
1677     uc->ctrl->generic.handler(uc->ctrl, dp, dp->data, EVENT_CALLBACK);
1678
1679     gtk_widget_destroy(GTK_WIDGET(dialog));
1680 }
1681
1682 #else /* GTK 1/2 coloursel response handlers */
1683
1684 static void coloursel_ok(GtkButton *button, gpointer data)
1685 {
1686     struct dlgparam *dp = (struct dlgparam *)data;
1687     gpointer coloursel = g_object_get_data(G_OBJECT(button), "user-data");
1688     struct uctrl *uc = g_object_get_data(G_OBJECT(coloursel), "user-data");
1689
1690 #if GTK_CHECK_VERSION(2,0,0)
1691     {
1692         GtkColorSelection *cs = GTK_COLOR_SELECTION
1693             (gtk_color_selection_dialog_get_color_selection
1694              (GTK_COLOR_SELECTION_DIALOG(coloursel)));
1695         GdkColor col;
1696         gtk_color_selection_get_current_color(cs, &col);
1697         dp->coloursel_result.r = col.red / 0x0100;
1698         dp->coloursel_result.g = col.green / 0x0100;
1699         dp->coloursel_result.b = col.blue / 0x0100;
1700     }
1701 #else
1702     {
1703         GtkColorSelection *cs = GTK_COLOR_SELECTION
1704             (gtk_color_selection_dialog_get_color_selection
1705              (GTK_COLOR_SELECTION_DIALOG(coloursel)));
1706         gdouble cvals[4];
1707         gtk_color_selection_get_color(cs, cvals);
1708         dp->coloursel_result.r = (int) (255 * cvals[0]);
1709         dp->coloursel_result.g = (int) (255 * cvals[1]);
1710         dp->coloursel_result.b = (int) (255 * cvals[2]);
1711     }
1712 #endif
1713     dp->coloursel_result.ok = TRUE;
1714     uc->ctrl->generic.handler(uc->ctrl, dp, dp->data, EVENT_CALLBACK);
1715 }
1716
1717 static void coloursel_cancel(GtkButton *button, gpointer data)
1718 {
1719     struct dlgparam *dp = (struct dlgparam *)data;
1720     gpointer coloursel = g_object_get_data(G_OBJECT(button), "user-data");
1721     struct uctrl *uc = g_object_get_data(G_OBJECT(coloursel), "user-data");
1722     dp->coloursel_result.ok = FALSE;
1723     uc->ctrl->generic.handler(uc->ctrl, dp, dp->data, EVENT_CALLBACK);
1724 }
1725
1726 #endif /* end of coloursel response handlers */
1727
1728 static void filefont_clicked(GtkButton *button, gpointer data)
1729 {
1730     struct dlgparam *dp = (struct dlgparam *)data;
1731     struct uctrl *uc = dlg_find_bywidget(dp, GTK_WIDGET(button));
1732
1733     if (uc->ctrl->generic.type == CTRL_FILESELECT) {
1734 #ifdef USE_GTK_FILE_CHOOSER_DIALOG
1735         GtkWidget *filechoose = gtk_file_chooser_dialog_new
1736             (uc->ctrl->fileselect.title, GTK_WINDOW(dp->window),
1737              (uc->ctrl->fileselect.for_writing ?
1738               GTK_FILE_CHOOSER_ACTION_SAVE :
1739               GTK_FILE_CHOOSER_ACTION_OPEN),
1740              STANDARD_CANCEL_LABEL, GTK_RESPONSE_CANCEL,
1741              STANDARD_OPEN_LABEL, GTK_RESPONSE_ACCEPT,
1742              (const gchar *)NULL);
1743         gtk_window_set_modal(GTK_WINDOW(filechoose), TRUE);
1744         g_object_set_data(G_OBJECT(filechoose), "user-data", (gpointer)uc);
1745         g_signal_connect(G_OBJECT(filechoose), "response",
1746                          G_CALLBACK(filechoose_response), (gpointer)dp);
1747         gtk_widget_show(filechoose);
1748 #else
1749         GtkWidget *filesel =
1750             gtk_file_selection_new(uc->ctrl->fileselect.title);
1751         gtk_window_set_modal(GTK_WINDOW(filesel), TRUE);
1752         g_object_set_data
1753             (G_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "user-data",
1754              (gpointer)filesel);
1755         g_object_set_data(G_OBJECT(filesel), "user-data", (gpointer)uc);
1756         g_signal_connect
1757             (G_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "clicked",
1758              G_CALLBACK(filesel_ok), (gpointer)dp);
1759         g_signal_connect_swapped
1760             (G_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "clicked",
1761              G_CALLBACK(gtk_widget_destroy), (gpointer)filesel);
1762         g_signal_connect_swapped
1763             (G_OBJECT(GTK_FILE_SELECTION(filesel)->cancel_button), "clicked",
1764              G_CALLBACK(gtk_widget_destroy), (gpointer)filesel);
1765         gtk_widget_show(filesel);
1766 #endif
1767     }
1768
1769     if (uc->ctrl->generic.type == CTRL_FONTSELECT) {
1770         const gchar *fontname = gtk_entry_get_text(GTK_ENTRY(uc->entry));
1771
1772 #if !GTK_CHECK_VERSION(2,0,0)
1773
1774         /*
1775          * Use the GTK 1 standard font selector.
1776          */
1777
1778         gchar *spacings[] = { "c", "m", NULL };
1779         GtkWidget *fontsel =
1780             gtk_font_selection_dialog_new("Select a font");
1781         gtk_window_set_modal(GTK_WINDOW(fontsel), TRUE);
1782         gtk_font_selection_dialog_set_filter
1783             (GTK_FONT_SELECTION_DIALOG(fontsel),
1784              GTK_FONT_FILTER_BASE, GTK_FONT_ALL,
1785              NULL, NULL, NULL, NULL, spacings, NULL);
1786         if (!gtk_font_selection_dialog_set_font_name
1787             (GTK_FONT_SELECTION_DIALOG(fontsel), fontname)) {
1788             /*
1789              * If the font name wasn't found as it was, try opening
1790              * it and extracting its FONT property. This should
1791              * have the effect of mapping short aliases into true
1792              * XLFDs.
1793              */
1794             GdkFont *font = gdk_font_load(fontname);
1795             if (font) {
1796                 XFontStruct *xfs = GDK_FONT_XFONT(font);
1797                 Display *disp = GDK_FONT_XDISPLAY(font);
1798                 Atom fontprop = XInternAtom(disp, "FONT", False);
1799                 unsigned long ret;
1800                 gdk_font_ref(font);
1801                 if (XGetFontProperty(xfs, fontprop, &ret)) {
1802                     char *name = XGetAtomName(disp, (Atom)ret);
1803                     if (name)
1804                         gtk_font_selection_dialog_set_font_name
1805                         (GTK_FONT_SELECTION_DIALOG(fontsel), name);
1806                 }
1807                 gdk_font_unref(font);
1808             }
1809         }
1810         g_object_set_data
1811             (G_OBJECT(GTK_FONT_SELECTION_DIALOG(fontsel)->ok_button),
1812              "user-data", (gpointer)fontsel);
1813         g_object_set_data(G_OBJECT(fontsel), "user-data", (gpointer)uc);
1814         g_signal_connect
1815             (G_OBJECT(GTK_FONT_SELECTION_DIALOG(fontsel)->ok_button),
1816              "clicked", G_CALLBACK(fontsel_ok), (gpointer)dp);
1817         g_signal_connect_swapped
1818             (G_OBJECT(GTK_FONT_SELECTION_DIALOG(fontsel)->ok_button),
1819              "clicked", G_CALLBACK(gtk_widget_destroy),
1820              (gpointer)fontsel);
1821         g_signal_connect_swapped
1822             (G_OBJECT(GTK_FONT_SELECTION_DIALOG(fontsel)->cancel_button),
1823              "clicked", G_CALLBACK(gtk_widget_destroy),
1824              (gpointer)fontsel);
1825         gtk_widget_show(fontsel);
1826
1827 #else /* !GTK_CHECK_VERSION(2,0,0) */
1828
1829         /*
1830          * Use the unifontsel code provided in gtkfont.c.
1831          */
1832
1833         unifontsel *fontsel = unifontsel_new("Select a font");
1834
1835         gtk_window_set_modal(fontsel->window, TRUE);
1836         unifontsel_set_name(fontsel, fontname);
1837         
1838         g_object_set_data(G_OBJECT(fontsel->ok_button),
1839                           "user-data", (gpointer)fontsel);
1840         fontsel->user_data = uc;
1841         g_signal_connect(G_OBJECT(fontsel->ok_button), "clicked",
1842                          G_CALLBACK(fontsel_ok), (gpointer)dp);
1843         g_signal_connect_swapped(G_OBJECT(fontsel->ok_button), "clicked",
1844                                  G_CALLBACK(unifontsel_destroy),
1845                                  (gpointer)fontsel);
1846         g_signal_connect_swapped(G_OBJECT(fontsel->cancel_button),"clicked",
1847                                  G_CALLBACK(unifontsel_destroy),
1848                                  (gpointer)fontsel);
1849
1850         gtk_widget_show(GTK_WIDGET(fontsel->window));
1851
1852 #endif /* !GTK_CHECK_VERSION(2,0,0) */
1853
1854     }
1855 }
1856
1857 #if !GTK_CHECK_VERSION(3,0,0)
1858 static void label_sizealloc(GtkWidget *widget, GtkAllocation *alloc,
1859                             gpointer data)
1860 {
1861     struct dlgparam *dp = (struct dlgparam *)data;
1862     struct uctrl *uc = dlg_find_bywidget(dp, widget);
1863
1864     gtk_widget_set_size_request(uc->text, alloc->width, -1);
1865     gtk_label_set_text(GTK_LABEL(uc->text), uc->ctrl->generic.label);
1866     g_signal_handler_disconnect(G_OBJECT(uc->text), uc->textsig);
1867 }
1868 #endif
1869
1870 /* ----------------------------------------------------------------------
1871  * This function does the main layout work: it reads a controlset,
1872  * it creates the relevant GTK controls, and returns a GtkWidget
1873  * containing the result. (This widget might be a title of some
1874  * sort, it might be a Columns containing many controls, or it
1875  * might be a GtkFrame containing a Columns; whatever it is, it's
1876  * definitely a GtkWidget and should probably be added to a
1877  * GtkVbox.)
1878  * 
1879  * `win' is required for setting the default button. If it is
1880  * non-NULL, all buttons created will be default-capable (so they
1881  * have extra space round them for the default highlight).
1882  */
1883 GtkWidget *layout_ctrls(struct dlgparam *dp, struct Shortcuts *scs,
1884                         struct controlset *s, GtkWindow *win)
1885 {
1886     Columns *cols;
1887     GtkWidget *ret;
1888     int i;
1889
1890     if (!s->boxname && s->boxtitle) {
1891         /* This controlset is a panel title. */
1892         return gtk_label_new(s->boxtitle);
1893     }
1894
1895     /*
1896      * Otherwise, we expect to be laying out actual controls, so
1897      * we'll start by creating a Columns for the purpose.
1898      */
1899     cols = COLUMNS(columns_new(4));
1900     ret = GTK_WIDGET(cols);
1901     gtk_widget_show(ret);
1902
1903     /*
1904      * Create a containing frame if we have a box name.
1905      */
1906     if (*s->boxname) {
1907         ret = gtk_frame_new(s->boxtitle);   /* NULL is valid here */
1908         gtk_container_set_border_width(GTK_CONTAINER(cols), 4);
1909         gtk_container_add(GTK_CONTAINER(ret), GTK_WIDGET(cols));
1910         gtk_widget_show(ret);
1911     }
1912
1913     /*
1914      * Now iterate through the controls themselves, create them,
1915      * and add them to the Columns.
1916      */
1917     for (i = 0; i < s->ncontrols; i++) {
1918         union control *ctrl = s->ctrls[i];
1919         struct uctrl *uc;
1920         int left = FALSE;
1921         GtkWidget *w = NULL;
1922
1923         switch (ctrl->generic.type) {
1924           case CTRL_COLUMNS:
1925             {
1926                 static const int simplecols[1] = { 100 };
1927                 columns_set_cols(cols, ctrl->columns.ncols,
1928                                  (ctrl->columns.percentages ?
1929                                   ctrl->columns.percentages : simplecols));
1930             }
1931             continue;                  /* no actual control created */
1932           case CTRL_TABDELAY:
1933             {
1934                 struct uctrl *uc = dlg_find_byctrl(dp, ctrl->tabdelay.ctrl);
1935                 if (uc)
1936                     columns_taborder_last(cols, uc->toplevel);
1937             }
1938             continue;                  /* no actual control created */
1939         }
1940
1941         uc = snew(struct uctrl);
1942         uc->ctrl = ctrl;
1943         uc->buttons = NULL;
1944         uc->entry = NULL;
1945 #if !GTK_CHECK_VERSION(2,4,0)
1946         uc->list = uc->menu = uc->optmenu = NULL;
1947 #else
1948         uc->combo = NULL;
1949 #endif
1950 #if GTK_CHECK_VERSION(2,0,0)
1951         uc->treeview = NULL;
1952         uc->listmodel = NULL;
1953 #endif
1954         uc->button = uc->text = NULL;
1955         uc->label = NULL;
1956         uc->nclicks = 0;
1957
1958         switch (ctrl->generic.type) {
1959           case CTRL_BUTTON:
1960             w = gtk_button_new_with_label(ctrl->generic.label);
1961             if (win) {
1962                 gtk_widget_set_can_default(w, TRUE);
1963                 if (ctrl->button.isdefault)
1964                     gtk_window_set_default(win, w);
1965                 if (ctrl->button.iscancel)
1966                     dp->cancelbutton = w;
1967             }
1968             g_signal_connect(G_OBJECT(w), "clicked",
1969                              G_CALLBACK(button_clicked), dp);
1970             g_signal_connect(G_OBJECT(w), "focus_in_event",
1971                              G_CALLBACK(widget_focus), dp);
1972             shortcut_add(scs, gtk_bin_get_child(GTK_BIN(w)),
1973                          ctrl->button.shortcut, SHORTCUT_UCTRL, uc);
1974             break;
1975           case CTRL_CHECKBOX:
1976             w = gtk_check_button_new_with_label(ctrl->generic.label);
1977             g_signal_connect(G_OBJECT(w), "toggled",
1978                              G_CALLBACK(button_toggled), dp);
1979             g_signal_connect(G_OBJECT(w), "focus_in_event",
1980                              G_CALLBACK(widget_focus), dp);
1981             shortcut_add(scs, gtk_bin_get_child(GTK_BIN(w)),
1982                          ctrl->checkbox.shortcut, SHORTCUT_UCTRL, uc);
1983             left = TRUE;
1984             break;
1985           case CTRL_RADIO:
1986             /*
1987              * Radio buttons get to go inside their own Columns, no
1988              * matter what.
1989              */
1990             {
1991                 gint i, *percentages;
1992                 GSList *group;
1993
1994                 w = columns_new(0);
1995                 if (ctrl->generic.label) {
1996                     GtkWidget *label = gtk_label_new(ctrl->generic.label);
1997                     columns_add(COLUMNS(w), label, 0, 1);
1998                     columns_force_left_align(COLUMNS(w), label);
1999                     gtk_widget_show(label);
2000                     shortcut_add(scs, label, ctrl->radio.shortcut,
2001                                  SHORTCUT_UCTRL, uc);
2002                     uc->label = label;
2003                 }
2004                 percentages = g_new(gint, ctrl->radio.ncolumns);
2005                 for (i = 0; i < ctrl->radio.ncolumns; i++) {
2006                     percentages[i] =
2007                         ((100 * (i+1) / ctrl->radio.ncolumns) -
2008                          100 * i / ctrl->radio.ncolumns);
2009                 }
2010                 columns_set_cols(COLUMNS(w), ctrl->radio.ncolumns,
2011                                  percentages);
2012                 g_free(percentages);
2013                 group = NULL;
2014
2015                 uc->nbuttons = ctrl->radio.nbuttons;
2016                 uc->buttons = snewn(uc->nbuttons, GtkWidget *);
2017
2018                 for (i = 0; i < ctrl->radio.nbuttons; i++) {
2019                     GtkWidget *b;
2020                     gint colstart;
2021
2022                     b = (gtk_radio_button_new_with_label
2023                          (group, ctrl->radio.buttons[i]));
2024                     uc->buttons[i] = b;
2025                     group = gtk_radio_button_get_group(GTK_RADIO_BUTTON(b));
2026                     colstart = i % ctrl->radio.ncolumns;
2027                     columns_add(COLUMNS(w), b, colstart,
2028                                 (i == ctrl->radio.nbuttons-1 ?
2029                                  ctrl->radio.ncolumns - colstart : 1));
2030                     columns_force_left_align(COLUMNS(w), b);
2031                     gtk_widget_show(b);
2032                     g_signal_connect(G_OBJECT(b), "toggled",
2033                                      G_CALLBACK(button_toggled), dp);
2034                     g_signal_connect(G_OBJECT(b), "focus_in_event",
2035                                      G_CALLBACK(widget_focus), dp);
2036                     if (ctrl->radio.shortcuts) {
2037                         shortcut_add(scs, gtk_bin_get_child(GTK_BIN(b)),
2038                                      ctrl->radio.shortcuts[i],
2039                                      SHORTCUT_UCTRL, uc);
2040                     }
2041                 }
2042             }
2043             break;
2044           case CTRL_EDITBOX:
2045             {
2046                 GtkWidget *signalobject;
2047
2048                 if (ctrl->editbox.has_list) {
2049 #if !GTK_CHECK_VERSION(2,4,0)
2050                     /*
2051                      * GTK 1 combo box.
2052                      */
2053                     w = gtk_combo_new();
2054                     gtk_combo_set_value_in_list(GTK_COMBO(w), FALSE, TRUE);
2055                     uc->entry = GTK_COMBO(w)->entry;
2056                     uc->list = GTK_COMBO(w)->list;
2057                     signalobject = uc->entry;
2058 #else
2059                     /*
2060                      * GTK 2 combo box.
2061                      */
2062                     uc->listmodel = gtk_list_store_new(2, G_TYPE_INT,
2063                                                        G_TYPE_STRING);
2064                     w = gtk_combo_box_new_with_model_and_entry
2065                         (GTK_TREE_MODEL(uc->listmodel));
2066                     /* We cannot support password combo boxes. */
2067                     assert(!ctrl->editbox.password);
2068                     uc->combo = w;
2069                     signalobject = uc->combo;
2070 #endif
2071                 } else {
2072                     w = gtk_entry_new();
2073                     if (ctrl->editbox.password)
2074                         gtk_entry_set_visibility(GTK_ENTRY(w), FALSE);
2075                     uc->entry = w;
2076                     signalobject = w;
2077                 }
2078                 uc->entrysig =
2079                     g_signal_connect(G_OBJECT(signalobject), "changed",
2080                                      G_CALLBACK(editbox_changed), dp);
2081                 g_signal_connect(G_OBJECT(signalobject), "key_press_event",
2082                                  G_CALLBACK(editbox_key), dp);
2083                 g_signal_connect(G_OBJECT(signalobject), "focus_in_event",
2084                                  G_CALLBACK(widget_focus), dp);
2085                 g_signal_connect(G_OBJECT(signalobject), "focus_out_event",
2086                                  G_CALLBACK(editbox_lostfocus), dp);
2087                 g_signal_connect(G_OBJECT(signalobject), "focus_out_event",
2088                                  G_CALLBACK(editbox_lostfocus), dp);
2089
2090 #if !GTK_CHECK_VERSION(3,0,0)
2091                 /*
2092                  * Edit boxes, for some strange reason, have a minimum
2093                  * width of 150 in GTK 1.2. We don't want this - we'd
2094                  * rather the edit boxes acquired their natural width
2095                  * from the column layout of the rest of the box.
2096                  */
2097                 {
2098                     GtkRequisition req;
2099                     gtk_widget_size_request(w, &req);
2100                     gtk_widget_set_size_request(w, 10, req.height);
2101                 }
2102 #else
2103                 /*
2104                  * In GTK 3, this is still true, but there's a special
2105                  * method for GtkEntry in particular to fix it.
2106                  */
2107                 if (GTK_IS_ENTRY(w))
2108                     gtk_entry_set_width_chars(GTK_ENTRY(w), 1);
2109 #endif
2110
2111                 if (ctrl->generic.label) {
2112                     GtkWidget *label, *container;
2113
2114                     label = gtk_label_new(ctrl->generic.label);
2115
2116                     shortcut_add(scs, label, ctrl->editbox.shortcut,
2117                                  SHORTCUT_FOCUS, uc->entry);
2118
2119                     container = columns_new(4);
2120                     if (ctrl->editbox.percentwidth == 100) {
2121                         columns_add(COLUMNS(container), label, 0, 1);
2122                         columns_force_left_align(COLUMNS(container), label);
2123                         columns_add(COLUMNS(container), w, 0, 1);
2124                     } else {
2125                         gint percentages[2];
2126                         percentages[1] = ctrl->editbox.percentwidth;
2127                         percentages[0] = 100 - ctrl->editbox.percentwidth;
2128                         columns_set_cols(COLUMNS(container), 2, percentages);
2129                         columns_add(COLUMNS(container), label, 0, 1);
2130                         columns_force_left_align(COLUMNS(container), label);
2131                         columns_add(COLUMNS(container), w, 1, 1);
2132                         columns_force_same_height(COLUMNS(container),
2133                                                   label, w);
2134                     }
2135                     gtk_widget_show(label);
2136                     gtk_widget_show(w);
2137
2138                     w = container;
2139                     uc->label = label;
2140                 }
2141             }
2142             break;
2143           case CTRL_FILESELECT:
2144           case CTRL_FONTSELECT:
2145             {
2146                 GtkWidget *ww;
2147                 const char *browsebtn =
2148                     (ctrl->generic.type == CTRL_FILESELECT ?
2149                      "Browse..." : "Change...");
2150
2151                 gint percentages[] = { 75, 25 };
2152                 w = columns_new(4);
2153                 columns_set_cols(COLUMNS(w), 2, percentages);
2154
2155                 if (ctrl->generic.label) {
2156                     ww = gtk_label_new(ctrl->generic.label);
2157                     columns_add(COLUMNS(w), ww, 0, 2);
2158                     columns_force_left_align(COLUMNS(w), ww);
2159                     gtk_widget_show(ww);
2160                     shortcut_add(scs, ww,
2161                                  (ctrl->generic.type == CTRL_FILESELECT ?
2162                                   ctrl->fileselect.shortcut :
2163                                   ctrl->fontselect.shortcut),
2164                                  SHORTCUT_UCTRL, uc);
2165                     uc->label = ww;
2166                 }
2167
2168                 uc->entry = ww = gtk_entry_new();
2169 #if !GTK_CHECK_VERSION(3,0,0)
2170                 {
2171                     GtkRequisition req;
2172                     gtk_widget_size_request(ww, &req);
2173                     gtk_widget_set_size_request(ww, 10, req.height);
2174                 }
2175 #else
2176                 gtk_entry_set_width_chars(GTK_ENTRY(ww), 1);
2177 #endif
2178                 columns_add(COLUMNS(w), ww, 0, 1);
2179                 gtk_widget_show(ww);
2180
2181                 uc->button = ww = gtk_button_new_with_label(browsebtn);
2182                 columns_add(COLUMNS(w), ww, 1, 1);
2183                 gtk_widget_show(ww);
2184
2185                 columns_force_same_height(COLUMNS(w), uc->entry, uc->button);
2186
2187                 g_signal_connect(G_OBJECT(uc->entry), "key_press_event",
2188                                  G_CALLBACK(editbox_key), dp);
2189                 uc->entrysig =
2190                     g_signal_connect(G_OBJECT(uc->entry), "changed",
2191                                      G_CALLBACK(editbox_changed), dp);
2192                 g_signal_connect(G_OBJECT(uc->entry), "focus_in_event",
2193                                  G_CALLBACK(widget_focus), dp);
2194                 g_signal_connect(G_OBJECT(uc->button), "focus_in_event",
2195                                  G_CALLBACK(widget_focus), dp);
2196                 g_signal_connect(G_OBJECT(ww), "clicked",
2197                                  G_CALLBACK(filefont_clicked), dp);
2198             }
2199             break;
2200           case CTRL_LISTBOX:
2201
2202 #if GTK_CHECK_VERSION(2,0,0)
2203             /*
2204              * First construct the list data store, with the right
2205              * number of columns.
2206              */
2207 #  if !GTK_CHECK_VERSION(2,4,0)
2208             /* (For GTK 2.0 to 2.3, we do this for full listboxes only,
2209              * because combo boxes are still done the old GTK1 way.) */
2210             if (ctrl->listbox.height > 0)
2211 #  endif
2212             {
2213                 GType *types;
2214                 int i;
2215                 int cols;
2216
2217                 cols = ctrl->listbox.ncols;
2218                 cols = cols ? cols : 1;
2219                 types = snewn(1 + cols, GType);
2220
2221                 types[0] = G_TYPE_INT;
2222                 for (i = 0; i < cols; i++)
2223                     types[i+1] = G_TYPE_STRING;
2224
2225                 uc->listmodel = gtk_list_store_newv(1 + cols, types);
2226
2227                 sfree(types);
2228             }
2229 #endif
2230
2231             /*
2232              * See if it's a drop-down list (non-editable combo
2233              * box).
2234              */
2235             if (ctrl->listbox.height == 0) {
2236 #if !GTK_CHECK_VERSION(2,4,0)
2237                 /*
2238                  * GTK1 and early-GTK2 option-menu style of
2239                  * drop-down list.
2240                  */
2241                 uc->optmenu = w = gtk_option_menu_new();
2242                 uc->menu = gtk_menu_new();
2243                 gtk_option_menu_set_menu(GTK_OPTION_MENU(w), uc->menu);
2244                 g_object_set_data(G_OBJECT(uc->menu), "user-data",
2245                                   (gpointer)uc->optmenu);
2246                 g_signal_connect(G_OBJECT(uc->optmenu), "focus_in_event",
2247                                  G_CALLBACK(widget_focus), dp);
2248 #else
2249                 /*
2250                  * Late-GTK2 style using a GtkComboBox.
2251                  */
2252                 GtkCellRenderer *cr;
2253
2254                 /*
2255                  * Create a non-editable GtkComboBox (that is, not
2256                  * its subclass GtkComboBoxEntry).
2257                  */
2258                 w = gtk_combo_box_new_with_model
2259                     (GTK_TREE_MODEL(uc->listmodel));
2260                 uc->combo = w;
2261
2262                 /*
2263                  * Tell it how to render a list item (i.e. which
2264                  * column to look at in the list model).
2265                  */
2266                 cr = gtk_cell_renderer_text_new();
2267                 gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(w), cr, TRUE);
2268                 gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(w), cr,
2269                                                "text", 1, NULL);
2270
2271                 /*
2272                  * And tell it to notify us when the selection
2273                  * changes.
2274                  */
2275                 g_signal_connect(G_OBJECT(w), "changed",
2276                                  G_CALLBACK(droplist_selchange), dp);
2277 #endif
2278             } else {
2279 #if !GTK_CHECK_VERSION(2,0,0)
2280                 /*
2281                  * GTK1-style full list box.
2282                  */
2283                 uc->list = gtk_list_new();
2284                 if (ctrl->listbox.multisel == 2) {
2285                     gtk_list_set_selection_mode(GTK_LIST(uc->list),
2286                                                 GTK_SELECTION_EXTENDED);
2287                 } else if (ctrl->listbox.multisel == 1) {
2288                     gtk_list_set_selection_mode(GTK_LIST(uc->list),
2289                                                 GTK_SELECTION_MULTIPLE);
2290                 } else {
2291                     gtk_list_set_selection_mode(GTK_LIST(uc->list),
2292                                                 GTK_SELECTION_SINGLE);
2293                 }
2294                 w = gtk_scrolled_window_new(NULL, NULL);
2295                 gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(w),
2296                                                       uc->list);
2297                 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(w),
2298                                                GTK_POLICY_NEVER,
2299                                                GTK_POLICY_AUTOMATIC);
2300                 uc->adj = gtk_scrolled_window_get_vadjustment
2301                     (GTK_SCROLLED_WINDOW(w));
2302
2303                 gtk_widget_show(uc->list);
2304                 g_signal_connect(G_OBJECT(uc->list), "selection-changed",
2305                                  G_CALLBACK(list_selchange), dp);
2306                 g_signal_connect(G_OBJECT(uc->list), "focus_in_event",
2307                                  G_CALLBACK(widget_focus), dp);
2308
2309                 /*
2310                  * Adjust the height of the scrolled window to the
2311                  * minimum given by the height parameter.
2312                  * 
2313                  * This piece of guesswork is a horrid hack based
2314                  * on looking inside the GTK 1.2 sources
2315                  * (specifically gtkviewport.c, which appears to be
2316                  * the widget which provides the border around the
2317                  * scrolling area). Anyone lets me know how I can
2318                  * do this in a way which isn't at risk from GTK
2319                  * upgrades, I'd be grateful.
2320                  */
2321                 {
2322                     int edge;
2323                     edge = GTK_WIDGET(uc->list)->style->klass->ythickness;
2324                     gtk_widget_set_size_request(w, 10,
2325                                          2*edge + (ctrl->listbox.height *
2326                                                    get_listitemheight(w)));
2327                 }
2328
2329                 if (ctrl->listbox.draglist) {
2330                     /*
2331                      * GTK doesn't appear to make it easy to
2332                      * implement a proper draggable list; so
2333                      * instead I'm just going to have to put an Up
2334                      * and a Down button to the right of the actual
2335                      * list box. Ah well.
2336                      */
2337                     GtkWidget *cols, *button;
2338                     static const gint percentages[2] = { 80, 20 };
2339
2340                     cols = columns_new(4);
2341                     columns_set_cols(COLUMNS(cols), 2, percentages);
2342                     columns_add(COLUMNS(cols), w, 0, 1);
2343                     gtk_widget_show(w);
2344                     button = gtk_button_new_with_label("Up");
2345                     columns_add(COLUMNS(cols), button, 1, 1);
2346                     gtk_widget_show(button);
2347                     g_signal_connect(G_OBJECT(button), "clicked",
2348                                      G_CALLBACK(draglist_up), dp);
2349                     g_signal_connect(G_OBJECT(button), "focus_in_event",
2350                                      G_CALLBACK(widget_focus), dp);
2351                     button = gtk_button_new_with_label("Down");
2352                     columns_add(COLUMNS(cols), button, 1, 1);
2353                     gtk_widget_show(button);
2354                     g_signal_connect(G_OBJECT(button), "clicked",
2355                                      G_CALLBACK(draglist_down), dp);
2356                     g_signal_connect(G_OBJECT(button), "focus_in_event",
2357                                      G_CALLBACK(widget_focus), dp);
2358
2359                     w = cols;
2360                 }
2361 #else
2362                 /*
2363                  * GTK2 treeview-based full list box.
2364                  */
2365                 GtkTreeSelection *sel;
2366
2367                 /*
2368                  * Create the list box itself, its columns, and
2369                  * its containing scrolled window.
2370                  */
2371                 w = gtk_tree_view_new_with_model
2372                     (GTK_TREE_MODEL(uc->listmodel));
2373                 g_object_set_data(G_OBJECT(uc->listmodel), "user-data",
2374                                   (gpointer)w);
2375                 gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(w), FALSE);
2376                 sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(w));
2377                 gtk_tree_selection_set_mode
2378                     (sel, ctrl->listbox.multisel ? GTK_SELECTION_MULTIPLE :
2379                      GTK_SELECTION_SINGLE);
2380                 uc->treeview = w;
2381                 g_signal_connect(G_OBJECT(w), "row-activated",
2382                                  G_CALLBACK(listbox_doubleclick), dp);
2383                 g_signal_connect(G_OBJECT(sel), "changed",
2384                                  G_CALLBACK(listbox_selchange), dp);
2385
2386                 if (ctrl->listbox.draglist) {
2387                     gtk_tree_view_set_reorderable(GTK_TREE_VIEW(w), TRUE);
2388                     g_signal_connect(G_OBJECT(uc->listmodel), "row-inserted",
2389                                      G_CALLBACK(listbox_reorder), dp);
2390                 }
2391
2392                 {
2393                     int i;
2394                     int cols;
2395
2396                     cols = ctrl->listbox.ncols;
2397                     cols = cols ? cols : 1;
2398                     for (i = 0; i < cols; i++) {
2399                         GtkTreeViewColumn *column;
2400                         GtkCellRenderer *cellrend;
2401                         /*
2402                          * It appears that GTK 2 doesn't leave us any
2403                          * particularly sensible way to honour the
2404                          * "percentages" specification in the ctrl
2405                          * structure.
2406                          */
2407                         cellrend = gtk_cell_renderer_text_new();
2408                         if (!ctrl->listbox.hscroll) {
2409                             g_object_set(G_OBJECT(cellrend),
2410                                          "ellipsize", PANGO_ELLIPSIZE_END,
2411                                          "ellipsize-set", TRUE,
2412                                          NULL);
2413                         }
2414                         column = gtk_tree_view_column_new_with_attributes
2415                             ("heading", cellrend, "text", i+1, (char *)NULL);
2416                         gtk_tree_view_column_set_sizing
2417                             (column, GTK_TREE_VIEW_COLUMN_GROW_ONLY);
2418                         gtk_tree_view_append_column(GTK_TREE_VIEW(w), column);
2419                     }
2420                 }
2421
2422                 {
2423                     GtkWidget *scroll;
2424
2425                     scroll = gtk_scrolled_window_new(NULL, NULL);
2426                     gtk_scrolled_window_set_shadow_type
2427                         (GTK_SCROLLED_WINDOW(scroll), GTK_SHADOW_IN);
2428                     gtk_widget_show(w);
2429                     gtk_container_add(GTK_CONTAINER(scroll), w);
2430                     gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
2431                                                    GTK_POLICY_AUTOMATIC,
2432                                                    GTK_POLICY_ALWAYS);
2433                     gtk_widget_set_size_request
2434                         (scroll, -1,
2435                          ctrl->listbox.height * get_listitemheight(w));
2436
2437                     w = scroll;
2438                 }
2439 #endif
2440             }
2441
2442             if (ctrl->generic.label) {
2443                 GtkWidget *label, *container;
2444
2445                 label = gtk_label_new(ctrl->generic.label);
2446                 gtk_label_set_width_chars(GTK_LABEL(label), 3);
2447
2448                 shortcut_add(scs, label, ctrl->listbox.shortcut,
2449                              SHORTCUT_FOCUS, w);
2450
2451                 container = columns_new(4);
2452                 if (ctrl->listbox.percentwidth == 100) {
2453                     columns_add(COLUMNS(container), label, 0, 1);
2454                     columns_force_left_align(COLUMNS(container), label);
2455                     columns_add(COLUMNS(container), w, 0, 1);
2456                 } else {
2457                     gint percentages[2];
2458                     percentages[1] = ctrl->listbox.percentwidth;
2459                     percentages[0] = 100 - ctrl->listbox.percentwidth;
2460                     columns_set_cols(COLUMNS(container), 2, percentages);
2461                     columns_add(COLUMNS(container), label, 0, 1);
2462                     columns_force_left_align(COLUMNS(container), label);
2463                     columns_add(COLUMNS(container), w, 1, 1);
2464                     columns_force_same_height(COLUMNS(container),
2465                                               label, w);
2466                 }
2467                 gtk_widget_show(label);
2468                 gtk_widget_show(w);
2469
2470                 w = container;
2471                 uc->label = label;
2472             }
2473
2474             break;
2475           case CTRL_TEXT:
2476 #if !GTK_CHECK_VERSION(3,0,0)
2477             /*
2478              * Wrapping text widgets don't sit well with the GTK2
2479              * layout model, in which widgets state a minimum size
2480              * and the whole window then adjusts to the smallest
2481              * size it can sensibly take given its contents. A
2482              * wrapping text widget _has_ no clear minimum size;
2483              * instead it has a range of possibilities. It can be
2484              * one line deep but 2000 wide, or two lines deep and
2485              * 1000 pixels, or three by 867, or four by 500 and so
2486              * on. It can be as short as you like provided you
2487              * don't mind it being wide, or as narrow as you like
2488              * provided you don't mind it being tall.
2489              * 
2490              * Therefore, it fits very badly into the layout model.
2491              * Hence the only thing to do is pick a width and let
2492              * it choose its own number of lines. To do this I'm
2493              * going to cheat a little. All new wrapping text
2494              * widgets will be created with a minimal text content
2495              * "X"; then, after the rest of the dialog box is set
2496              * up and its size calculated, the text widgets will be
2497              * told their width and given their real text, which
2498              * will cause the size to be recomputed in the y
2499              * direction (because many of them will expand to more
2500              * than one line).
2501              */
2502             uc->text = w = gtk_label_new("X");
2503             uc->textsig =
2504                 g_signal_connect(G_OBJECT(w), "size-allocate",
2505                                  G_CALLBACK(label_sizealloc), dp);
2506 #else
2507             /*
2508              * In GTK3, this is all fixed, because the main aim of the
2509              * new 'height-for-width' geometry management is to make
2510              * wrapping labels behave sensibly. So now we can just do
2511              * the obvious thing.
2512              */
2513             uc->text = w = gtk_label_new(uc->ctrl->generic.label);
2514 #endif
2515             gtk_misc_set_alignment(GTK_MISC(w), 0.0, 0.0);
2516             gtk_label_set_line_wrap(GTK_LABEL(w), TRUE);
2517             break;
2518         }
2519
2520         assert(w != NULL);
2521
2522         columns_add(cols, w,
2523                     COLUMN_START(ctrl->generic.column),
2524                     COLUMN_SPAN(ctrl->generic.column));
2525         if (left)
2526             columns_force_left_align(cols, w);
2527         gtk_widget_show(w);
2528
2529         uc->toplevel = w;
2530         dlg_add_uctrl(dp, uc);
2531     }
2532
2533     return ret;
2534 }
2535
2536 struct selparam {
2537     struct dlgparam *dp;
2538     GtkNotebook *panels;
2539     GtkWidget *panel;
2540 #if !GTK_CHECK_VERSION(2,0,0)
2541     GtkWidget *treeitem;
2542 #else
2543     int depth;
2544     GtkTreePath *treepath;
2545 #endif
2546     struct Shortcuts shortcuts;
2547 };
2548
2549 #if GTK_CHECK_VERSION(2,0,0)
2550 static void treeselection_changed(GtkTreeSelection *treeselection,
2551                                   gpointer data)
2552 {
2553     struct selparam *sps = (struct selparam *)data, *sp;
2554     GtkTreeModel *treemodel;
2555     GtkTreeIter treeiter;
2556     gint spindex;
2557     gint page_num;
2558
2559     if (!gtk_tree_selection_get_selected(treeselection, &treemodel, &treeiter))
2560         return;
2561
2562     gtk_tree_model_get(treemodel, &treeiter, TREESTORE_PARAMS, &spindex, -1);
2563     sp = &sps[spindex];
2564
2565     page_num = gtk_notebook_page_num(sp->panels, sp->panel);
2566     gtk_notebook_set_current_page(sp->panels, page_num);
2567
2568     dlg_refresh(NULL, sp->dp);
2569
2570     sp->dp->shortcuts = &sp->shortcuts;
2571 }
2572 #else
2573 static void treeitem_sel(GtkItem *item, gpointer data)
2574 {
2575     struct selparam *sp = (struct selparam *)data;
2576     gint page_num;
2577
2578     page_num = gtk_notebook_page_num(sp->panels, sp->panel);
2579     gtk_notebook_set_page(sp->panels, page_num);
2580
2581     dlg_refresh(NULL, sp->dp);
2582
2583     sp->dp->shortcuts = &sp->shortcuts;
2584     sp->dp->currtreeitem = sp->treeitem;
2585 }
2586 #endif
2587
2588 static void window_destroy(GtkWidget *widget, gpointer data)
2589 {
2590     gtk_main_quit();
2591 }
2592
2593 #if !GTK_CHECK_VERSION(2,0,0)
2594 static int tree_grab_focus(struct dlgparam *dp)
2595 {
2596     int i, f;
2597
2598     /*
2599      * See if any of the treeitems has the focus.
2600      */
2601     f = -1;
2602     for (i = 0; i < dp->ntreeitems; i++)
2603         if (GTK_WIDGET_HAS_FOCUS(dp->treeitems[i])) {
2604             f = i;
2605             break;
2606         }
2607
2608     if (f >= 0)
2609         return FALSE;
2610     else {
2611         gtk_widget_grab_focus(dp->currtreeitem);
2612         return TRUE;
2613     }
2614 }
2615
2616 gint tree_focus(GtkContainer *container, GtkDirectionType direction,
2617                 gpointer data)
2618 {
2619     struct dlgparam *dp = (struct dlgparam *)data;
2620
2621     g_signal_stop_emission_by_name(G_OBJECT(container), "focus");
2622     /*
2623      * If there's a focused treeitem, we return FALSE to cause the
2624      * focus to move on to some totally other control. If not, we
2625      * focus the selected one.
2626      */
2627     return tree_grab_focus(dp);
2628 }
2629 #endif
2630
2631 int win_key_press(GtkWidget *widget, GdkEventKey *event, gpointer data)
2632 {
2633     struct dlgparam *dp = (struct dlgparam *)data;
2634
2635     if (event->keyval == GDK_KEY_Escape && dp->cancelbutton) {
2636         g_signal_emit_by_name(G_OBJECT(dp->cancelbutton), "clicked");
2637         return TRUE;
2638     }
2639
2640     if ((event->state & GDK_MOD1_MASK) &&
2641         (unsigned char)event->string[0] > 0 &&
2642         (unsigned char)event->string[0] <= 127) {
2643         int schr = (unsigned char)event->string[0];
2644         struct Shortcut *sc = &dp->shortcuts->sc[schr];
2645
2646         switch (sc->action) {
2647           case SHORTCUT_TREE:
2648 #if GTK_CHECK_VERSION(2,0,0)
2649             gtk_widget_grab_focus(sc->widget);
2650 #else
2651             tree_grab_focus(dp);
2652 #endif
2653             break;
2654           case SHORTCUT_FOCUS:
2655             gtk_widget_grab_focus(sc->widget);
2656             break;
2657           case SHORTCUT_UCTRL:
2658             /*
2659              * We must do something sensible with a uctrl.
2660              * Precisely what this is depends on the type of
2661              * control.
2662              */
2663             switch (sc->uc->ctrl->generic.type) {
2664               case CTRL_CHECKBOX:
2665               case CTRL_BUTTON:
2666                 /* Check boxes and buttons get the focus _and_ get toggled. */
2667                 gtk_widget_grab_focus(sc->uc->toplevel);
2668                 g_signal_emit_by_name(G_OBJECT(sc->uc->toplevel), "clicked");
2669                 break;
2670               case CTRL_FILESELECT:
2671               case CTRL_FONTSELECT:
2672                 /* File/font selectors have their buttons pressed (ooer),
2673                  * and focus transferred to the edit box. */
2674                 g_signal_emit_by_name(G_OBJECT(sc->uc->button), "clicked");
2675                 gtk_widget_grab_focus(sc->uc->entry);
2676                 break;
2677               case CTRL_RADIO:
2678                 /*
2679                  * Radio buttons are fun, because they have
2680                  * multiple shortcuts. We must find whether the
2681                  * activated shortcut is the shortcut for the whole
2682                  * group, or for a particular button. In the former
2683                  * case, we find the currently selected button and
2684                  * focus it; in the latter, we focus-and-click the
2685                  * button whose shortcut was pressed.
2686                  */
2687                 if (schr == sc->uc->ctrl->radio.shortcut) {
2688                     int i;
2689                     for (i = 0; i < sc->uc->ctrl->radio.nbuttons; i++)
2690                         if (gtk_toggle_button_get_active
2691                             (GTK_TOGGLE_BUTTON(sc->uc->buttons[i]))) {
2692                             gtk_widget_grab_focus(sc->uc->buttons[i]);
2693                         }
2694                 } else if (sc->uc->ctrl->radio.shortcuts) {
2695                     int i;
2696                     for (i = 0; i < sc->uc->ctrl->radio.nbuttons; i++)
2697                         if (schr == sc->uc->ctrl->radio.shortcuts[i]) {
2698                             gtk_widget_grab_focus(sc->uc->buttons[i]);
2699                             g_signal_emit_by_name
2700                                 (G_OBJECT(sc->uc->buttons[i]), "clicked");
2701                         }
2702                 }
2703                 break;
2704               case CTRL_LISTBOX:
2705
2706 #if !GTK_CHECK_VERSION(2,4,0)
2707                 if (sc->uc->optmenu) {
2708                     GdkEventButton bev;
2709                     gint returnval;
2710
2711                     gtk_widget_grab_focus(sc->uc->optmenu);
2712                     /* Option menus don't work using the "clicked" signal.
2713                      * We need to manufacture a button press event :-/ */
2714                     bev.type = GDK_BUTTON_PRESS;
2715                     bev.button = 1;
2716                     g_signal_emit_by_name(G_OBJECT(sc->uc->optmenu),
2717                                           "button_press_event",
2718                                           &bev, &returnval);
2719                     break;
2720                 }
2721 #else
2722                 if (sc->uc->combo) {
2723                     gtk_widget_grab_focus(sc->uc->combo);
2724                     gtk_combo_box_popup(GTK_COMBO_BOX(sc->uc->combo));
2725                     break;
2726                 }
2727 #endif
2728 #if !GTK_CHECK_VERSION(2,0,0)
2729                 if (sc->uc->list) {
2730                     /*
2731                      * For GTK-1 style list boxes, we tell it to
2732                      * focus one of its children, which appears to
2733                      * do the Right Thing.
2734                      */
2735                     gtk_container_focus(GTK_CONTAINER(sc->uc->list),
2736                                         GTK_DIR_TAB_FORWARD);
2737                     break;
2738                 }
2739 #else
2740                 if (sc->uc->treeview) {
2741                     gtk_widget_grab_focus(sc->uc->treeview);
2742                     break;
2743                 }
2744 #endif
2745                 assert(!"We shouldn't get here");
2746                 break;
2747             }
2748             break;
2749         }
2750     }
2751
2752     return FALSE;
2753 }
2754
2755 #if !GTK_CHECK_VERSION(2,0,0)
2756 int tree_key_press(GtkWidget *widget, GdkEventKey *event, gpointer data)
2757 {
2758     struct dlgparam *dp = (struct dlgparam *)data;
2759
2760     if (event->keyval == GDK_Up || event->keyval == GDK_KP_Up ||
2761         event->keyval == GDK_Down || event->keyval == GDK_KP_Down) {
2762         int dir, i, j = -1;
2763         for (i = 0; i < dp->ntreeitems; i++)
2764             if (widget == dp->treeitems[i])
2765                 break;
2766         if (i < dp->ntreeitems) {
2767             if (event->keyval == GDK_Up || event->keyval == GDK_KP_Up)
2768                 dir = -1;
2769             else
2770                 dir = +1;
2771
2772             while (1) {
2773                 i += dir;
2774                 if (i < 0 || i >= dp->ntreeitems)
2775                     break;             /* nothing in that dir to select */
2776                 /*
2777                  * Determine if this tree item is visible.
2778                  */
2779                 {
2780                     GtkWidget *w = dp->treeitems[i];
2781                     int vis = TRUE;
2782                     while (w && (GTK_IS_TREE_ITEM(w) || GTK_IS_TREE(w))) {
2783                         if (!GTK_WIDGET_VISIBLE(w)) {
2784                             vis = FALSE;
2785                             break;
2786                         }
2787                         w = w->parent;
2788                     }
2789                     if (vis) {
2790                         j = i;         /* got one */
2791                         break;
2792                     }
2793                 }
2794             }
2795         }
2796         g_signal_stop_emission_by_name(G_OBJECT(widget), "key_press_event");
2797         if (j >= 0) {
2798             g_signal_emit_by_name(G_OBJECT(dp->treeitems[j]), "toggle");
2799             gtk_widget_grab_focus(dp->treeitems[j]);
2800         }
2801         return TRUE;
2802     }
2803
2804     /*
2805      * It's nice for Left and Right to expand and collapse tree
2806      * branches.
2807      */
2808     if (event->keyval == GDK_Left || event->keyval == GDK_KP_Left) {
2809         g_signal_stop_emission_by_name(G_OBJECT(widget), "key_press_event");
2810         gtk_tree_item_collapse(GTK_TREE_ITEM(widget));
2811         return TRUE;
2812     }
2813     if (event->keyval == GDK_Right || event->keyval == GDK_KP_Right) {
2814         g_signal_stop_emission_by_name(G_OBJECT(widget), "key_press_event");
2815         gtk_tree_item_expand(GTK_TREE_ITEM(widget));
2816         return TRUE;
2817     }
2818
2819     return FALSE;
2820 }
2821 #endif
2822
2823 static void shortcut_highlight(GtkWidget *labelw, int chr)
2824 {
2825     GtkLabel *label = GTK_LABEL(labelw);
2826     const gchar *currstr;
2827     gchar *pattern;
2828     int i;
2829
2830 #if !GTK_CHECK_VERSION(2,0,0)
2831     {
2832         gchar *currstr_nonconst;
2833         gtk_label_get(label, &currstr_nonconst);
2834         currstr = currstr_nonconst;
2835     }
2836 #else
2837     currstr = gtk_label_get_text(label);
2838 #endif
2839
2840     for (i = 0; currstr[i]; i++)
2841         if (tolower((unsigned char)currstr[i]) == chr) {
2842             GtkRequisition req;
2843
2844             pattern = dupprintf("%*s_", i, "");
2845
2846             gtk_widget_size_request(GTK_WIDGET(label), &req);
2847             gtk_label_set_pattern(label, pattern);
2848             gtk_widget_set_size_request(GTK_WIDGET(label), -1, req.height);
2849
2850             sfree(pattern);
2851             break;
2852         }
2853 }
2854
2855 void shortcut_add(struct Shortcuts *scs, GtkWidget *labelw,
2856                   int chr, int action, void *ptr)
2857 {
2858     if (chr == NO_SHORTCUT)
2859         return;
2860
2861     chr = tolower((unsigned char)chr);
2862
2863     assert(scs->sc[chr].action == SHORTCUT_EMPTY);
2864
2865     scs->sc[chr].action = action;
2866
2867     if (action == SHORTCUT_FOCUS) {
2868         scs->sc[chr].uc = NULL;
2869         scs->sc[chr].widget = (GtkWidget *)ptr;
2870     } else {
2871         scs->sc[chr].widget = NULL;
2872         scs->sc[chr].uc = (struct uctrl *)ptr;
2873     }
2874
2875     shortcut_highlight(labelw, chr);
2876 }
2877
2878 int get_listitemheight(GtkWidget *w)
2879 {
2880 #if !GTK_CHECK_VERSION(2,0,0)
2881     GtkWidget *listitem = gtk_list_item_new_with_label("foo");
2882     GtkRequisition req;
2883     gtk_widget_size_request(listitem, &req);
2884     g_object_ref_sink(G_OBJECT(listitem));
2885     return req.height;
2886 #else
2887     int height;
2888     GtkCellRenderer *cr = gtk_cell_renderer_text_new();
2889 #if GTK_CHECK_VERSION(3,0,0)
2890     {
2891         GtkRequisition req;
2892         /*
2893          * Since none of my list items wraps in this GUI, no
2894          * interesting width-for-height behaviour should be happening,
2895          * so I don't think it should matter here whether I ask for
2896          * the minimum or natural height.
2897          */
2898         gtk_cell_renderer_get_preferred_size(cr, w, &req, NULL);
2899         height = req.height;
2900     }
2901 #else
2902     gtk_cell_renderer_get_size(cr, w, NULL, NULL, NULL, NULL, &height);
2903 #endif
2904     g_object_ref(G_OBJECT(cr));
2905     g_object_ref_sink(G_OBJECT(cr));
2906     g_object_unref(G_OBJECT(cr));
2907     return height;
2908 #endif
2909 }
2910
2911 void set_dialog_action_area(GtkDialog *dlg, GtkWidget *w)
2912 {
2913 #if !GTK_CHECK_VERSION(2,0,0)
2914
2915     /*
2916      * In GTK 1, laying out the buttons at the bottom of the
2917      * configuration box is nice and easy, because a GtkDialog's
2918      * action_area is a GtkHBox which stretches to cover the full
2919      * width of the dialog. So we just put our Columns widget
2920      * straight into that hbox, and it ends up just where we want
2921      * it.
2922      */
2923     gtk_box_pack_start(GTK_BOX(dlg->action_area), w, TRUE, TRUE, 0);
2924
2925 #else
2926     /*
2927      * In GTK 2, the action area is now a GtkHButtonBox and its
2928      * layout behaviour seems to be different: it doesn't stretch
2929      * to cover the full width of the window, but instead finds its
2930      * own preferred width and right-aligns that within the window.
2931      * This isn't what we want, because we have both left-aligned
2932      * and right-aligned buttons coming out of the above call to
2933      * layout_ctrls(), and right-aligning the whole thing will
2934      * result in the former being centred and looking weird.
2935      *
2936      * So instead we abandon the dialog's action area completely:
2937      * we gtk_widget_hide() it in the below code, and we also call
2938      * gtk_dialog_set_has_separator() to remove the separator above
2939      * it. We then insert our own action area into the end of the
2940      * dialog's main vbox, and add our own separator above that.
2941      *
2942      * (Ideally, if we were a native GTK app, we would use the
2943      * GtkHButtonBox's _own_ innate ability to support one set of
2944      * buttons being right-aligned and one left-aligned. But to do
2945      * that here, we would have to either (a) pick apart our cross-
2946      * platform layout structures and treat them specially for this
2947      * particular set of controls, which would be painful, or else
2948      * (b) develop a special and simpler cross-platform
2949      * representation for these particular controls, and introduce
2950      * special-case code into all the _other_ platforms to handle
2951      * it. Neither appeals. Therefore, I regretfully discard the
2952      * GTKHButtonBox and go it alone.)
2953      */
2954
2955     GtkWidget *align;
2956     align = gtk_alignment_new(0, 0, 1, 1);
2957     gtk_container_add(GTK_CONTAINER(align), w);
2958     /*
2959      * The purpose of this GtkAlignment is to provide padding
2960      * around the buttons. The padding we use is twice the padding
2961      * used in our GtkColumns, because we nest two GtkColumns most
2962      * of the time (one separating the tree view from the main
2963      * controls, and another for the main controls themselves).
2964      */
2965 #if GTK_CHECK_VERSION(2,4,0)
2966     gtk_alignment_set_padding(GTK_ALIGNMENT(align), 8, 8, 8, 8);
2967 #endif
2968     gtk_widget_show(align);
2969     gtk_box_pack_end(GTK_BOX(gtk_dialog_get_content_area(dlg)),
2970                      align, FALSE, TRUE, 0);
2971     w = gtk_hseparator_new();
2972     gtk_box_pack_end(GTK_BOX(gtk_dialog_get_content_area(dlg)),
2973                      w, FALSE, TRUE, 0);
2974     gtk_widget_show(w);
2975     gtk_widget_hide(gtk_dialog_get_action_area(dlg));
2976 #if !GTK_CHECK_VERSION(3,0,0)
2977     /* This cosmetic property is withdrawn in GTK 3's GtkDialog */
2978     g_object_set(G_OBJECT(dlg), "has-separator", TRUE, (const char *)NULL);
2979 #endif
2980 #endif
2981 }
2982
2983 #if GTK_CHECK_VERSION(2,0,0)
2984 void initial_treeview_collapse(struct dlgparam *dp, GtkWidget *tree)
2985 {
2986     /*
2987      * Collapse the deeper branches of the treeview into the state we
2988      * like them to start off in. See comment below in do_config_box.
2989      */
2990     int i;
2991     for (i = 0; i < dp->nselparams; i++)
2992         if (dp->selparams[i].depth >= 2)
2993             gtk_tree_view_collapse_row(GTK_TREE_VIEW(tree),
2994                                        dp->selparams[i].treepath);
2995 }
2996 #endif
2997
2998 #if GTK_CHECK_VERSION(3,0,0)
2999 void treeview_map_event(GtkWidget *tree, gpointer data)
3000 {
3001     struct dlgparam *dp = (struct dlgparam *)data;
3002     GtkAllocation alloc;
3003     gtk_widget_get_allocation(tree, &alloc);
3004     gtk_widget_set_size_request(tree, alloc.width, -1);
3005     initial_treeview_collapse(dp, tree);
3006 }
3007 #endif
3008
3009 int do_config_box(const char *title, Conf *conf, int midsession,
3010                   int protcfginfo)
3011 {
3012     GtkWidget *window, *hbox, *vbox, *cols, *label,
3013         *tree, *treescroll, *panels, *panelvbox;
3014     int index, level, protocol;
3015     struct controlbox *ctrlbox;
3016     char *path;
3017 #if GTK_CHECK_VERSION(2,0,0)
3018     GtkTreeStore *treestore;
3019     GtkCellRenderer *treerenderer;
3020     GtkTreeViewColumn *treecolumn;
3021     GtkTreeSelection *treeselection;
3022     GtkTreeIter treeiterlevels[8];
3023 #else
3024     GtkTreeItem *treeitemlevels[8];
3025     GtkTree *treelevels[8];
3026 #endif
3027     struct dlgparam dp;
3028     struct Shortcuts scs;
3029
3030     struct selparam *selparams = NULL;
3031     int nselparams = 0, selparamsize = 0;
3032
3033     dlg_init(&dp);
3034
3035     for (index = 0; index < lenof(scs.sc); index++) {
3036         scs.sc[index].action = SHORTCUT_EMPTY;
3037     }
3038
3039     window = gtk_dialog_new();
3040
3041     ctrlbox = ctrl_new_box();
3042     protocol = conf_get_int(conf, CONF_protocol);
3043     setup_config_box(ctrlbox, midsession, protocol, protcfginfo);
3044     unix_setup_config_box(ctrlbox, midsession, protocol);
3045     gtk_setup_config_box(ctrlbox, midsession, window);
3046
3047     gtk_window_set_title(GTK_WINDOW(window), title);
3048     hbox = gtk_hbox_new(FALSE, 4);
3049     gtk_box_pack_start
3050         (GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(window))),
3051          hbox, TRUE, TRUE, 0);
3052     gtk_container_set_border_width(GTK_CONTAINER(hbox), 10);
3053     gtk_widget_show(hbox);
3054     vbox = gtk_vbox_new(FALSE, 4);
3055     gtk_box_pack_start(GTK_BOX(hbox), vbox, FALSE, FALSE, 0);
3056     gtk_widget_show(vbox);
3057     cols = columns_new(4);
3058     gtk_box_pack_start(GTK_BOX(vbox), cols, FALSE, FALSE, 0);
3059     gtk_widget_show(cols);
3060     label = gtk_label_new("Category:");
3061     columns_add(COLUMNS(cols), label, 0, 1);
3062     columns_force_left_align(COLUMNS(cols), label);
3063     gtk_widget_show(label);
3064     treescroll = gtk_scrolled_window_new(NULL, NULL);
3065 #if GTK_CHECK_VERSION(2,0,0)
3066     treestore = gtk_tree_store_new
3067         (TREESTORE_NUM, G_TYPE_STRING, G_TYPE_INT);
3068     tree = gtk_tree_view_new_with_model(GTK_TREE_MODEL(treestore));
3069     gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(tree), FALSE);
3070     treerenderer = gtk_cell_renderer_text_new();
3071     treecolumn = gtk_tree_view_column_new_with_attributes
3072         ("Label", treerenderer, "text", 0, NULL);
3073     gtk_tree_view_append_column(GTK_TREE_VIEW(tree), treecolumn);
3074     treeselection = gtk_tree_view_get_selection(GTK_TREE_VIEW(tree));
3075     gtk_tree_selection_set_mode(treeselection, GTK_SELECTION_BROWSE);
3076     gtk_container_add(GTK_CONTAINER(treescroll), tree);
3077 #else
3078     tree = gtk_tree_new();
3079     gtk_tree_set_view_mode(GTK_TREE(tree), GTK_TREE_VIEW_ITEM);
3080     gtk_tree_set_selection_mode(GTK_TREE(tree), GTK_SELECTION_BROWSE);
3081     g_signal_connect(G_OBJECT(tree), "focus",
3082                      G_CALLBACK(tree_focus), &dp);
3083 #endif
3084     g_signal_connect(G_OBJECT(tree), "focus_in_event",
3085                      G_CALLBACK(widget_focus), &dp);
3086     shortcut_add(&scs, label, 'g', SHORTCUT_TREE, tree);
3087     gtk_widget_show(treescroll);
3088     gtk_box_pack_start(GTK_BOX(vbox), treescroll, TRUE, TRUE, 0);
3089     panels = gtk_notebook_new();
3090     gtk_notebook_set_show_tabs(GTK_NOTEBOOK(panels), FALSE);
3091     gtk_notebook_set_show_border(GTK_NOTEBOOK(panels), FALSE);
3092     gtk_box_pack_start(GTK_BOX(hbox), panels, TRUE, TRUE, 0);
3093     gtk_widget_show(panels);
3094
3095     panelvbox = NULL;
3096     path = NULL;
3097     level = 0;
3098     for (index = 0; index < ctrlbox->nctrlsets; index++) {
3099         struct controlset *s = ctrlbox->ctrlsets[index];
3100         GtkWidget *w;
3101
3102         if (!*s->pathname) {
3103             w = layout_ctrls(&dp, &scs, s, GTK_WINDOW(window));
3104
3105             set_dialog_action_area(GTK_DIALOG(window), w);
3106         } else {
3107             int j = path ? ctrl_path_compare(s->pathname, path) : 0;
3108             if (j != INT_MAX) {        /* add to treeview, start new panel */
3109                 char *c;
3110 #if GTK_CHECK_VERSION(2,0,0)
3111                 GtkTreeIter treeiter;
3112 #else
3113                 GtkWidget *treeitem;
3114 #endif
3115                 int first;
3116
3117                 /*
3118                  * We expect never to find an implicit path
3119                  * component. For example, we expect never to see
3120                  * A/B/C followed by A/D/E, because that would
3121                  * _implicitly_ create A/D. All our path prefixes
3122                  * are expected to contain actual controls and be
3123                  * selectable in the treeview; so we would expect
3124                  * to see A/D _explicitly_ before encountering
3125                  * A/D/E.
3126                  */
3127                 assert(j == ctrl_path_elements(s->pathname) - 1);
3128
3129                 c = strrchr(s->pathname, '/');
3130                 if (!c)
3131                     c = s->pathname;
3132                 else
3133                     c++;
3134
3135                 path = s->pathname;
3136
3137                 first = (panelvbox == NULL);
3138
3139                 panelvbox = gtk_vbox_new(FALSE, 4);
3140                 gtk_widget_show(panelvbox);
3141                 gtk_notebook_append_page(GTK_NOTEBOOK(panels), panelvbox,
3142                                          NULL);
3143                 if (first) {
3144                     gint page_num;
3145
3146                     page_num = gtk_notebook_page_num(GTK_NOTEBOOK(panels),
3147                                                      panelvbox);
3148                     gtk_notebook_set_current_page(GTK_NOTEBOOK(panels),
3149                                                   page_num);
3150                 }
3151
3152                 if (nselparams >= selparamsize) {
3153                     selparamsize += 16;
3154                     selparams = sresize(selparams, selparamsize,
3155                                         struct selparam);
3156                 }
3157                 selparams[nselparams].dp = &dp;
3158                 selparams[nselparams].panels = GTK_NOTEBOOK(panels);
3159                 selparams[nselparams].panel = panelvbox;
3160                 selparams[nselparams].shortcuts = scs;   /* structure copy */
3161
3162                 assert(j-1 < level);
3163
3164 #if GTK_CHECK_VERSION(2,0,0)
3165                 if (j > 0)
3166                     /* treeiterlevels[j-1] will always be valid because we
3167                      * don't allow implicit path components; see above.
3168                      */
3169                     gtk_tree_store_append(treestore, &treeiter,
3170                                           &treeiterlevels[j-1]);
3171                 else
3172                     gtk_tree_store_append(treestore, &treeiter, NULL);
3173                 gtk_tree_store_set(treestore, &treeiter,
3174                                    TREESTORE_PATH, c,
3175                                    TREESTORE_PARAMS, nselparams,
3176                                    -1);
3177                 treeiterlevels[j] = treeiter;
3178
3179                 selparams[nselparams].depth = j;
3180                 if (j > 0) {
3181                     selparams[nselparams].treepath =
3182                         gtk_tree_model_get_path(GTK_TREE_MODEL(treestore),
3183                                                 &treeiterlevels[j-1]);
3184                     /*
3185                      * We are going to collapse all tree branches
3186                      * at depth greater than 2, but not _yet_; see
3187                      * the comment at the call to
3188                      * gtk_tree_view_collapse_row below.
3189                      */
3190                     gtk_tree_view_expand_row(GTK_TREE_VIEW(tree),
3191                                              selparams[nselparams].treepath,
3192                                              FALSE);
3193                 } else {
3194                     selparams[nselparams].treepath = NULL;
3195                 }
3196 #else
3197                 treeitem = gtk_tree_item_new_with_label(c);
3198                 if (j > 0) {
3199                     if (!treelevels[j-1]) {
3200                         treelevels[j-1] = GTK_TREE(gtk_tree_new());
3201                         gtk_tree_item_set_subtree
3202                             (treeitemlevels[j-1],
3203                              GTK_WIDGET(treelevels[j-1]));
3204                         if (j < 2)
3205                             gtk_tree_item_expand(treeitemlevels[j-1]);
3206                         else
3207                             gtk_tree_item_collapse(treeitemlevels[j-1]);
3208                     }
3209                     gtk_tree_append(treelevels[j-1], treeitem);
3210                 } else {
3211                     gtk_tree_append(GTK_TREE(tree), treeitem);
3212                 }
3213                 treeitemlevels[j] = GTK_TREE_ITEM(treeitem);
3214                 treelevels[j] = NULL;
3215
3216                 g_signal_connect(G_OBJECT(treeitem), "key_press_event",
3217                                  G_CALLBACK(tree_key_press), &dp);
3218                 g_signal_connect(G_OBJECT(treeitem), "focus_in_event",
3219                                  G_CALLBACK(widget_focus), &dp);
3220
3221                 gtk_widget_show(treeitem);
3222
3223                 if (first)
3224                     gtk_tree_select_child(GTK_TREE(tree), treeitem);
3225                 selparams[nselparams].treeitem = treeitem;
3226 #endif
3227
3228                 level = j+1;
3229                 nselparams++;
3230             }
3231
3232             w = layout_ctrls(&dp, &selparams[nselparams-1].shortcuts, s, NULL);
3233             gtk_box_pack_start(GTK_BOX(panelvbox), w, FALSE, FALSE, 0);
3234             gtk_widget_show(w);
3235         }
3236     }
3237
3238 #if GTK_CHECK_VERSION(2,0,0)
3239     /*
3240      * We want our tree view to come up with all branches at depth 2
3241      * or more collapsed. However, if we start off with those branches
3242      * collapsed, then the tree view's size request will be calculated
3243      * based on the width of the collapsed tree, and then when the
3244      * collapsed branches are expanded later, the tree view will
3245      * jarringly change size.
3246      *
3247      * So instead we start with everything expanded; then, once the
3248      * tree view has computed its resulting width requirement, we
3249      * collapse the relevant rows, but force the width to be the value
3250      * we just retrieved. This arranges that the tree view is wide
3251      * enough to have all branches expanded without further resizing.
3252      */
3253
3254     dp.nselparams = nselparams;
3255     dp.selparams = selparams;
3256
3257 #if !GTK_CHECK_VERSION(3,0,0)
3258     {
3259         /*
3260          * In GTK2, we can just do the job right now.
3261          */
3262         GtkRequisition req;
3263         gtk_widget_size_request(tree, &req);
3264         initial_treeview_collapse(&dp, tree);
3265         gtk_widget_set_size_request(tree, req.width, -1);
3266     }
3267 #else
3268     /*
3269      * But in GTK3, we have to wait until the widget is about to be
3270      * mapped, because the size computation won't have been done yet.
3271      */
3272     g_signal_connect(G_OBJECT(tree), "map",
3273                      G_CALLBACK(treeview_map_event), &dp);
3274 #endif /* GTK 2 vs 3 */
3275 #endif /* GTK 2+ vs 1 */
3276
3277 #if GTK_CHECK_VERSION(2,0,0)
3278     g_signal_connect(G_OBJECT(treeselection), "changed",
3279                      G_CALLBACK(treeselection_changed), selparams);
3280 #else
3281     dp.ntreeitems = nselparams;
3282     dp.treeitems = snewn(dp.ntreeitems, GtkWidget *);
3283     for (index = 0; index < nselparams; index++) {
3284         g_signal_connect(G_OBJECT(selparams[index].treeitem), "select",
3285                          G_CALLBACK(treeitem_sel),
3286                          &selparams[index]);
3287         dp.treeitems[index] = selparams[index].treeitem;
3288     }
3289 #endif
3290
3291     dp.data = conf;
3292     dlg_refresh(NULL, &dp);
3293
3294     dp.shortcuts = &selparams[0].shortcuts;
3295 #if !GTK_CHECK_VERSION(2,0,0)
3296     dp.currtreeitem = dp.treeitems[0];
3297 #endif
3298     dp.lastfocus = NULL;
3299     dp.retval = 0;
3300     dp.window = window;
3301
3302     {
3303         /* in gtkwin.c */
3304         extern void set_window_icon(GtkWidget *window,
3305                                     const char *const *const *icon,
3306                                     int n_icon);
3307         extern const char *const *const cfg_icon[];
3308         extern const int n_cfg_icon;
3309         set_window_icon(window, cfg_icon, n_cfg_icon);
3310     }
3311
3312 #if !GTK_CHECK_VERSION(2,0,0)
3313     gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(treescroll),
3314                                           tree);
3315 #endif
3316     gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(treescroll),
3317                                    GTK_POLICY_NEVER,
3318                                    GTK_POLICY_AUTOMATIC);
3319     gtk_widget_show(tree);
3320
3321     gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
3322     gtk_widget_show(window);
3323
3324     /*
3325      * Set focus into the first available control.
3326      */
3327     for (index = 0; index < ctrlbox->nctrlsets; index++) {
3328         struct controlset *s = ctrlbox->ctrlsets[index];
3329         int done = 0;
3330         int j;
3331
3332         if (*s->pathname) {
3333             for (j = 0; j < s->ncontrols; j++)
3334                 if (s->ctrls[j]->generic.type != CTRL_TABDELAY &&
3335                     s->ctrls[j]->generic.type != CTRL_COLUMNS &&
3336                     s->ctrls[j]->generic.type != CTRL_TEXT) {
3337                     dlg_set_focus(s->ctrls[j], &dp);
3338                     dp.lastfocus = s->ctrls[j];
3339                     done = 1;
3340                     break;
3341                 }
3342         }
3343         if (done)
3344             break;
3345     }
3346
3347     g_signal_connect(G_OBJECT(window), "destroy",
3348                      G_CALLBACK(window_destroy), NULL);
3349     g_signal_connect(G_OBJECT(window), "key_press_event",
3350                      G_CALLBACK(win_key_press), &dp);
3351
3352     gtk_main();
3353     post_main();
3354
3355     dlg_cleanup(&dp);
3356     sfree(selparams);
3357
3358     return dp.retval;
3359 }
3360
3361 static void messagebox_handler(union control *ctrl, void *dlg,
3362                                void *data, int event)
3363 {
3364     if (event == EVENT_ACTION)
3365         dlg_end(dlg, ctrl->generic.context.i);
3366 }
3367 int messagebox(GtkWidget *parentwin, const char *title, const char *msg,
3368                int minwid, ...)
3369 {
3370     GtkWidget *window, *w0, *w1;
3371     struct controlbox *ctrlbox;
3372     struct controlset *s0, *s1;
3373     union control *c;
3374     struct dlgparam dp;
3375     struct Shortcuts scs;
3376     int index, ncols;
3377     va_list ap;
3378
3379     dlg_init(&dp);
3380
3381     for (index = 0; index < lenof(scs.sc); index++) {
3382         scs.sc[index].action = SHORTCUT_EMPTY;
3383     }
3384
3385     ctrlbox = ctrl_new_box();
3386
3387     ncols = 0;
3388     va_start(ap, minwid);
3389     while (va_arg(ap, char *) != NULL) {
3390         ncols++;
3391         (void) va_arg(ap, int);        /* shortcut */
3392         (void) va_arg(ap, int);        /* normal/default/cancel */
3393         (void) va_arg(ap, int);        /* end value */
3394     }
3395     va_end(ap);
3396
3397     s0 = ctrl_getset(ctrlbox, "", "", "");
3398     c = ctrl_columns(s0, 2, 50, 50);
3399     c->columns.ncols = s0->ncolumns = ncols;
3400     c->columns.percentages = sresize(c->columns.percentages, ncols, int);
3401     for (index = 0; index < ncols; index++)
3402         c->columns.percentages[index] = (index+1)*100/ncols - index*100/ncols;
3403     va_start(ap, minwid);
3404     index = 0;
3405     while (1) {
3406         char *title = va_arg(ap, char *);
3407         int shortcut, type, value;
3408         if (title == NULL)
3409             break;
3410         shortcut = va_arg(ap, int);
3411         type = va_arg(ap, int);
3412         value = va_arg(ap, int);
3413         c = ctrl_pushbutton(s0, title, shortcut, HELPCTX(no_help),
3414                             messagebox_handler, I(value));
3415         c->generic.column = index++;
3416         if (type > 0)
3417             c->button.isdefault = TRUE;
3418         else if (type < 0)
3419             c->button.iscancel = TRUE;
3420     }
3421     va_end(ap);
3422
3423     s1 = ctrl_getset(ctrlbox, "x", "", "");
3424     ctrl_text(s1, msg, HELPCTX(no_help));
3425
3426     window = gtk_dialog_new();
3427     gtk_window_set_title(GTK_WINDOW(window), title);
3428     w0 = layout_ctrls(&dp, &scs, s0, GTK_WINDOW(window));
3429     set_dialog_action_area(GTK_DIALOG(window), w0);
3430     gtk_widget_show(w0);
3431     w1 = layout_ctrls(&dp, &scs, s1, GTK_WINDOW(window));
3432     gtk_container_set_border_width(GTK_CONTAINER(w1), 10);
3433     gtk_widget_set_size_request(w1, minwid+20, -1);
3434     gtk_box_pack_start
3435         (GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(window))),
3436          w1, TRUE, TRUE, 0);
3437     gtk_widget_show(w1);
3438
3439     dp.shortcuts = &scs;
3440     dp.lastfocus = NULL;
3441     dp.retval = 0;
3442     dp.window = window;
3443
3444     gtk_window_set_modal(GTK_WINDOW(window), TRUE);
3445     if (parentwin) {
3446         set_transient_window_pos(parentwin, window);
3447         gtk_window_set_transient_for(GTK_WINDOW(window),
3448                                      GTK_WINDOW(parentwin));
3449     } else
3450         gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
3451     gtk_widget_show(window);
3452
3453     g_signal_connect(G_OBJECT(window), "destroy",
3454                      G_CALLBACK(window_destroy), NULL);
3455     g_signal_connect(G_OBJECT(window), "key_press_event",
3456                      G_CALLBACK(win_key_press), &dp);
3457
3458     gtk_main();
3459     post_main();
3460
3461     dlg_cleanup(&dp);
3462     ctrl_free_box(ctrlbox);
3463
3464     return dp.retval;
3465 }
3466
3467 int string_width(const char *text)
3468 {
3469     int ret;
3470     get_label_text_dimensions(text, &ret, NULL);
3471     return ret;
3472 }
3473
3474 int reallyclose(void *frontend)
3475 {
3476     char *title = dupcat(appname, " Exit Confirmation", NULL);
3477     int ret = messagebox(GTK_WIDGET(get_window(frontend)),
3478                          title, "Are you sure you want to close this session?",
3479                          string_width("Most of the width of the above text"),
3480                          "Yes", 'y', +1, 1,
3481                          "No", 'n', -1, 0,
3482                          NULL);
3483     sfree(title);
3484     return ret;
3485 }
3486
3487 int verify_ssh_host_key(void *frontend, char *host, int port,
3488                         const char *keytype, char *keystr, char *fingerprint,
3489                         void (*callback)(void *ctx, int result), void *ctx)
3490 {
3491     static const char absenttxt[] =
3492         "The server's host key is not cached. You have no guarantee "
3493         "that the server is the computer you think it is.\n"
3494         "The server's %s key fingerprint is:\n"
3495         "%s\n"
3496         "If you trust this host, press \"Accept\" to add the key to "
3497         "PuTTY's cache and carry on connecting.\n"
3498         "If you want to carry on connecting just once, without "
3499         "adding the key to the cache, press \"Connect Once\".\n"
3500         "If you do not trust this host, press \"Cancel\" to abandon the "
3501         "connection.";
3502     static const char wrongtxt[] =
3503         "WARNING - POTENTIAL SECURITY BREACH!\n"
3504         "The server's host key does not match the one PuTTY has "
3505         "cached. This means that either the server administrator "
3506         "has changed the host key, or you have actually connected "
3507         "to another computer pretending to be the server.\n"
3508         "The new %s key fingerprint is:\n"
3509         "%s\n"
3510         "If you were expecting this change and trust the new key, "
3511         "press \"Accept\" to update PuTTY's cache and continue connecting.\n"
3512         "If you want to carry on connecting but without updating "
3513         "the cache, press \"Connect Once\".\n"
3514         "If you want to abandon the connection completely, press "
3515         "\"Cancel\" to cancel. Pressing \"Cancel\" is the ONLY guaranteed "
3516         "safe choice.";
3517     char *text;
3518     int ret;
3519
3520     /*
3521      * Verify the key.
3522      */
3523     ret = verify_host_key(host, port, keytype, keystr);
3524
3525     if (ret == 0)                      /* success - key matched OK */
3526         return 1;
3527
3528     text = dupprintf((ret == 2 ? wrongtxt : absenttxt), keytype, fingerprint);
3529
3530     ret = messagebox(GTK_WIDGET(get_window(frontend)),
3531                      "PuTTY Security Alert", text,
3532                      string_width(fingerprint),
3533                      "Accept", 'a', 0, 2,
3534                      "Connect Once", 'o', 0, 1,
3535                      "Cancel", 'c', -1, 0,
3536                      NULL);
3537
3538     sfree(text);
3539
3540     if (ret == 2) {
3541         store_host_key(host, port, keytype, keystr);
3542         return 1;                      /* continue with connection */
3543     } else if (ret == 1)
3544         return 1;                      /* continue with connection */
3545     return 0;                          /* do not continue with connection */
3546 }
3547
3548 /*
3549  * Ask whether the selected algorithm is acceptable (since it was
3550  * below the configured 'warn' threshold).
3551  */
3552 int askalg(void *frontend, const char *algtype, const char *algname,
3553            void (*callback)(void *ctx, int result), void *ctx)
3554 {
3555     static const char msg[] =
3556         "The first %s supported by the server is "
3557         "%s, which is below the configured warning threshold.\n"
3558         "Continue with connection?";
3559     char *text;
3560     int ret;
3561
3562     text = dupprintf(msg, algtype, algname);
3563     ret = messagebox(GTK_WIDGET(get_window(frontend)),
3564                      "PuTTY Security Alert", text,
3565                      string_width("Continue with connection?"),
3566                      "Yes", 'y', 0, 1,
3567                      "No", 'n', 0, 0,
3568                      NULL);
3569     sfree(text);
3570
3571     if (ret) {
3572         return 1;
3573     } else {
3574         return 0;
3575     }
3576 }
3577
3578 void old_keyfile_warning(void)
3579 {
3580     /*
3581      * This should never happen on Unix. We hope.
3582      */
3583 }
3584
3585 void fatal_message_box(void *window, const char *msg)
3586 {
3587     messagebox(window, "PuTTY Fatal Error", msg,
3588                string_width("REASONABLY LONG LINE OF TEXT FOR BASIC SANITY"),
3589                "OK", 'o', 1, 1, NULL);
3590 }
3591
3592 void nonfatal_message_box(void *window, const char *msg)
3593 {
3594     messagebox(window, "PuTTY Error", msg,
3595                string_width("REASONABLY LONG LINE OF TEXT FOR BASIC SANITY"),
3596                "OK", 'o', 1, 1, NULL);
3597 }
3598
3599 void fatalbox(const char *p, ...)
3600 {
3601     va_list ap;
3602     char *msg;
3603     va_start(ap, p);
3604     msg = dupvprintf(p, ap);
3605     va_end(ap);
3606     fatal_message_box(NULL, msg);
3607     sfree(msg);
3608     cleanup_exit(1);
3609 }
3610
3611 void nonfatal(const char *p, ...)
3612 {
3613     va_list ap;
3614     char *msg;
3615     va_start(ap, p);
3616     msg = dupvprintf(p, ap);
3617     va_end(ap);
3618     nonfatal_message_box(NULL, msg);
3619     sfree(msg);
3620 }
3621
3622 static GtkWidget *aboutbox = NULL;
3623
3624 static void about_close_clicked(GtkButton *button, gpointer data)
3625 {
3626     gtk_widget_destroy(aboutbox);
3627     aboutbox = NULL;
3628 }
3629
3630 static void licence_clicked(GtkButton *button, gpointer data)
3631 {
3632     char *title;
3633
3634     const char *licence =
3635         "Copyright 1997-2015 Simon Tatham.\n\n"
3636
3637         "Portions copyright Robert de Bath, Joris van Rantwijk, Delian "
3638         "Delchev, Andreas Schultz, Jeroen Massar, Wez Furlong, Nicolas "
3639         "Barry, Justin Bradford, Ben Harris, Malcolm Smith, Ahmad Khalifa, "
3640         "Markus Kuhn, Colin Watson, Christopher Staite, and CORE SDI S.A.\n\n"
3641
3642         "Permission is hereby granted, free of charge, to any person "
3643         "obtaining a copy of this software and associated documentation "
3644         "files (the ""Software""), to deal in the Software without restriction, "
3645         "including without limitation the rights to use, copy, modify, merge, "
3646         "publish, distribute, sublicense, and/or sell copies of the Software, "
3647         "and to permit persons to whom the Software is furnished to do so, "
3648         "subject to the following conditions:\n\n"
3649
3650         "The above copyright notice and this permission notice shall be "
3651         "included in all copies or substantial portions of the Software.\n\n"
3652
3653         "THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT "
3654         "WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, "
3655         "INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF "
3656         "MERCHANTABILITY, FITNESS FOR A PARTICULAR "
3657         "PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE "
3658         "COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES "
3659         "OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, "
3660         "TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN "
3661         "CONNECTION WITH THE SOFTWARE OR THE USE OR "
3662         "OTHER DEALINGS IN THE SOFTWARE.";
3663
3664     title = dupcat(appname, " Licence", NULL);
3665     assert(aboutbox != NULL);
3666     messagebox(aboutbox, title, licence,
3667                string_width("LONGISH LINE OF TEXT SO THE LICENCE"
3668                             " BOX ISN'T EXCESSIVELY TALL AND THIN"),
3669                "OK", 'o', 1, 1, NULL);
3670     sfree(title);
3671 }
3672
3673 void about_box(void *window)
3674 {
3675     GtkWidget *w;
3676     char *title;
3677
3678     if (aboutbox) {
3679         gtk_widget_grab_focus(aboutbox);
3680         return;
3681     }
3682
3683     aboutbox = gtk_dialog_new();
3684     gtk_container_set_border_width(GTK_CONTAINER(aboutbox), 10);
3685     title = dupcat("About ", appname, NULL);
3686     gtk_window_set_title(GTK_WINDOW(aboutbox), title);
3687     sfree(title);
3688
3689     w = gtk_button_new_with_label("Close");
3690     gtk_widget_set_can_default(w, TRUE);
3691     gtk_window_set_default(GTK_WINDOW(aboutbox), w);
3692     gtk_box_pack_end(GTK_BOX(gtk_dialog_get_action_area(GTK_DIALOG(aboutbox))),
3693                      w, FALSE, FALSE, 0);
3694     g_signal_connect(G_OBJECT(w), "clicked",
3695                      G_CALLBACK(about_close_clicked), NULL);
3696     gtk_widget_show(w);
3697
3698     w = gtk_button_new_with_label("View Licence");
3699     gtk_widget_set_can_default(w, TRUE);
3700     gtk_box_pack_end(GTK_BOX(gtk_dialog_get_action_area(GTK_DIALOG(aboutbox))),
3701                      w, FALSE, FALSE, 0);
3702     g_signal_connect(G_OBJECT(w), "clicked",
3703                      G_CALLBACK(licence_clicked), NULL);
3704     gtk_widget_show(w);
3705
3706     w = gtk_label_new(appname);
3707     gtk_box_pack_start
3708         (GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(aboutbox))),
3709          w, FALSE, FALSE, 0);
3710     gtk_widget_show(w);
3711
3712     w = gtk_label_new(ver);
3713     gtk_box_pack_start
3714         (GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(aboutbox))),
3715          w, FALSE, FALSE, 5);
3716     gtk_widget_show(w);
3717
3718     w = gtk_label_new("Copyright 1997-2015 Simon Tatham. All rights reserved");
3719     gtk_box_pack_start
3720         (GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(aboutbox))),
3721          w, FALSE, FALSE, 5);
3722     gtk_widget_show(w);
3723
3724     set_transient_window_pos(GTK_WIDGET(window), aboutbox);
3725     gtk_window_set_transient_for(GTK_WINDOW(aboutbox),
3726                                  GTK_WINDOW(window));
3727     gtk_widget_show(aboutbox);
3728 }
3729
3730 struct eventlog_stuff {
3731     GtkWidget *parentwin, *window;
3732     struct controlbox *eventbox;
3733     struct Shortcuts scs;
3734     struct dlgparam dp;
3735     union control *listctrl;
3736     char **events;
3737     int nevents, negsize;
3738     char *seldata;
3739     int sellen;
3740     int ignore_selchange;
3741 };
3742
3743 static void eventlog_destroy(GtkWidget *widget, gpointer data)
3744 {
3745     struct eventlog_stuff *es = (struct eventlog_stuff *)data;
3746
3747     es->window = NULL;
3748     sfree(es->seldata);
3749     es->seldata = NULL;
3750     dlg_cleanup(&es->dp);
3751     ctrl_free_box(es->eventbox);
3752 }
3753 static void eventlog_ok_handler(union control *ctrl, void *dlg,
3754                                 void *data, int event)
3755 {
3756     if (event == EVENT_ACTION)
3757         dlg_end(dlg, 0);
3758 }
3759 static void eventlog_list_handler(union control *ctrl, void *dlg,
3760                                   void *data, int event)
3761 {
3762     struct eventlog_stuff *es = (struct eventlog_stuff *)data;
3763
3764     if (event == EVENT_REFRESH) {
3765         int i;
3766
3767         dlg_update_start(ctrl, dlg);
3768         dlg_listbox_clear(ctrl, dlg);
3769         for (i = 0; i < es->nevents; i++) {
3770             dlg_listbox_add(ctrl, dlg, es->events[i]);
3771         }
3772         dlg_update_done(ctrl, dlg);
3773     } else if (event == EVENT_SELCHANGE) {
3774         int i;
3775         int selsize = 0;
3776
3777         /*
3778          * If this SELCHANGE event is happening as a result of
3779          * deliberate deselection because someone else has grabbed
3780          * the selection, the last thing we want to do is pre-empt
3781          * them.
3782          */
3783         if (es->ignore_selchange)
3784             return;
3785
3786         /*
3787          * Construct the data to use as the selection.
3788          */
3789         sfree(es->seldata);
3790         es->seldata = NULL;
3791         es->sellen = 0;
3792         for (i = 0; i < es->nevents; i++) {
3793             if (dlg_listbox_issel(ctrl, dlg, i)) {
3794                 int extralen = strlen(es->events[i]);
3795
3796                 if (es->sellen + extralen + 2 > selsize) {
3797                     selsize = es->sellen + extralen + 512;
3798                     es->seldata = sresize(es->seldata, selsize, char);
3799                 }
3800
3801                 strcpy(es->seldata + es->sellen, es->events[i]);
3802                 es->sellen += extralen;
3803                 es->seldata[es->sellen++] = '\n';
3804             }
3805         }
3806
3807         if (gtk_selection_owner_set(es->window, GDK_SELECTION_PRIMARY,
3808                                     GDK_CURRENT_TIME)) {
3809             extern GdkAtom compound_text_atom;
3810
3811             gtk_selection_add_target(es->window, GDK_SELECTION_PRIMARY,
3812                                      GDK_SELECTION_TYPE_STRING, 1);
3813             gtk_selection_add_target(es->window, GDK_SELECTION_PRIMARY,
3814                                      compound_text_atom, 1);
3815         }
3816
3817     }
3818 }
3819
3820 void eventlog_selection_get(GtkWidget *widget, GtkSelectionData *seldata,
3821                             guint info, guint time_stamp, gpointer data)
3822 {
3823     struct eventlog_stuff *es = (struct eventlog_stuff *)data;
3824
3825     gtk_selection_data_set(seldata, gtk_selection_data_get_target(seldata), 8,
3826                            (unsigned char *)es->seldata, es->sellen);
3827 }
3828
3829 gint eventlog_selection_clear(GtkWidget *widget, GdkEventSelection *seldata,
3830                               gpointer data)
3831 {
3832     struct eventlog_stuff *es = (struct eventlog_stuff *)data;
3833     struct uctrl *uc;
3834
3835     /*
3836      * Deselect everything in the list box.
3837      */
3838     uc = dlg_find_byctrl(&es->dp, es->listctrl);
3839     es->ignore_selchange = 1;
3840 #if !GTK_CHECK_VERSION(2,0,0)
3841     assert(uc->list);
3842     gtk_list_unselect_all(GTK_LIST(uc->list));
3843 #else
3844     assert(uc->treeview);
3845     gtk_tree_selection_unselect_all
3846         (gtk_tree_view_get_selection(GTK_TREE_VIEW(uc->treeview)));
3847 #endif
3848     es->ignore_selchange = 0;
3849
3850     sfree(es->seldata);
3851     es->sellen = 0;
3852     es->seldata = NULL;
3853     return TRUE;
3854 }
3855
3856 void showeventlog(void *estuff, void *parentwin)
3857 {
3858     struct eventlog_stuff *es = (struct eventlog_stuff *)estuff;
3859     GtkWidget *window, *w0, *w1;
3860     GtkWidget *parent = GTK_WIDGET(parentwin);
3861     struct controlset *s0, *s1;
3862     union control *c;
3863     int index;
3864     char *title;
3865
3866     if (es->window) {
3867         gtk_widget_grab_focus(es->window);
3868         return;
3869     }
3870
3871     dlg_init(&es->dp);
3872
3873     for (index = 0; index < lenof(es->scs.sc); index++) {
3874         es->scs.sc[index].action = SHORTCUT_EMPTY;
3875     }
3876
3877     es->eventbox = ctrl_new_box();
3878
3879     s0 = ctrl_getset(es->eventbox, "", "", "");
3880     ctrl_columns(s0, 3, 33, 34, 33);
3881     c = ctrl_pushbutton(s0, "Close", 'c', HELPCTX(no_help),
3882                         eventlog_ok_handler, P(NULL));
3883     c->button.column = 1;
3884     c->button.isdefault = TRUE;
3885
3886     s1 = ctrl_getset(es->eventbox, "x", "", "");
3887     es->listctrl = c = ctrl_listbox(s1, NULL, NO_SHORTCUT, HELPCTX(no_help),
3888                                     eventlog_list_handler, P(es));
3889     c->listbox.height = 10;
3890     c->listbox.multisel = 2;
3891     c->listbox.ncols = 3;
3892     c->listbox.percentages = snewn(3, int);
3893     c->listbox.percentages[0] = 25;
3894     c->listbox.percentages[1] = 10;
3895     c->listbox.percentages[2] = 65;
3896
3897     es->window = window = gtk_dialog_new();
3898     title = dupcat(appname, " Event Log", NULL);
3899     gtk_window_set_title(GTK_WINDOW(window), title);
3900     sfree(title);
3901     w0 = layout_ctrls(&es->dp, &es->scs, s0, GTK_WINDOW(window));
3902     set_dialog_action_area(GTK_DIALOG(window), w0);
3903     gtk_widget_show(w0);
3904     w1 = layout_ctrls(&es->dp, &es->scs, s1, GTK_WINDOW(window));
3905     gtk_container_set_border_width(GTK_CONTAINER(w1), 10);
3906     gtk_widget_set_size_request(w1, 20 + string_width
3907                                 ("LINE OF TEXT GIVING WIDTH OF EVENT LOG IS "
3908                                  "QUITE LONG 'COS SSH LOG ENTRIES ARE WIDE"),
3909                                 -1);
3910     gtk_box_pack_start
3911         (GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(window))),
3912          w1, TRUE, TRUE, 0);
3913     gtk_widget_show(w1);
3914
3915     es->dp.data = es;
3916     es->dp.shortcuts = &es->scs;
3917     es->dp.lastfocus = NULL;
3918     es->dp.retval = 0;
3919     es->dp.window = window;
3920
3921     dlg_refresh(NULL, &es->dp);
3922
3923     if (parent) {
3924         set_transient_window_pos(parent, window);
3925         gtk_window_set_transient_for(GTK_WINDOW(window),
3926                                      GTK_WINDOW(parent));
3927     } else
3928         gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
3929     gtk_widget_show(window);
3930
3931     g_signal_connect(G_OBJECT(window), "destroy",
3932                      G_CALLBACK(eventlog_destroy), es);
3933     g_signal_connect(G_OBJECT(window), "key_press_event",
3934                      G_CALLBACK(win_key_press), &es->dp);
3935     g_signal_connect(G_OBJECT(window), "selection_get",
3936                      G_CALLBACK(eventlog_selection_get), es);
3937     g_signal_connect(G_OBJECT(window), "selection_clear_event",
3938                      G_CALLBACK(eventlog_selection_clear), es);
3939 }
3940
3941 void *eventlogstuff_new(void)
3942 {
3943     struct eventlog_stuff *es;
3944     es = snew(struct eventlog_stuff);
3945     memset(es, 0, sizeof(*es));
3946     return es;
3947 }
3948
3949 void logevent_dlg(void *estuff, const char *string)
3950 {
3951     struct eventlog_stuff *es = (struct eventlog_stuff *)estuff;
3952
3953     char timebuf[40];
3954     struct tm tm;
3955
3956     if (es->nevents >= es->negsize) {
3957         es->negsize += 64;
3958         es->events = sresize(es->events, es->negsize, char *);
3959     }
3960
3961     tm=ltime();
3962     strftime(timebuf, sizeof(timebuf), "%Y-%m-%d %H:%M:%S\t", &tm);
3963
3964     es->events[es->nevents] = snewn(strlen(timebuf) + strlen(string) + 1, char);
3965     strcpy(es->events[es->nevents], timebuf);
3966     strcat(es->events[es->nevents], string);
3967     if (es->window) {
3968         dlg_listbox_add(es->listctrl, &es->dp, es->events[es->nevents]);
3969     }
3970     es->nevents++;
3971 }
3972
3973 int askappend(void *frontend, Filename *filename,
3974               void (*callback)(void *ctx, int result), void *ctx)
3975 {
3976     static const char msgtemplate[] =
3977         "The session log file \"%.*s\" already exists. "
3978         "You can overwrite it with a new session log, "
3979         "append your session log to the end of it, "
3980         "or disable session logging for this session.";
3981     char *message;
3982     char *mbtitle;
3983     int mbret;
3984
3985     message = dupprintf(msgtemplate, FILENAME_MAX, filename->path);
3986     mbtitle = dupprintf("%s Log to File", appname);
3987
3988     mbret = messagebox(get_window(frontend), mbtitle, message,
3989                        string_width("LINE OF TEXT SUITABLE FOR THE"
3990                                     " ASKAPPEND WIDTH"),
3991                        "Overwrite", 'o', 1, 2,
3992                        "Append", 'a', 0, 1,
3993                        "Disable", 'd', -1, 0,
3994                        NULL);
3995
3996     sfree(message);
3997     sfree(mbtitle);
3998
3999     return mbret;
4000 }