]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - unix/gtkdlg.c
Remove a mysterious GTK size-request tweak.
[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 #if GTK_CHECK_VERSION(3,0,0)
2447                 gtk_label_set_width_chars(GTK_LABEL(label), 3);
2448 #endif
2449
2450                 shortcut_add(scs, label, ctrl->listbox.shortcut,
2451                              SHORTCUT_FOCUS, w);
2452
2453                 container = columns_new(4);
2454                 if (ctrl->listbox.percentwidth == 100) {
2455                     columns_add(COLUMNS(container), label, 0, 1);
2456                     columns_force_left_align(COLUMNS(container), label);
2457                     columns_add(COLUMNS(container), w, 0, 1);
2458                 } else {
2459                     gint percentages[2];
2460                     percentages[1] = ctrl->listbox.percentwidth;
2461                     percentages[0] = 100 - ctrl->listbox.percentwidth;
2462                     columns_set_cols(COLUMNS(container), 2, percentages);
2463                     columns_add(COLUMNS(container), label, 0, 1);
2464                     columns_force_left_align(COLUMNS(container), label);
2465                     columns_add(COLUMNS(container), w, 1, 1);
2466                     columns_force_same_height(COLUMNS(container),
2467                                               label, w);
2468                 }
2469                 gtk_widget_show(label);
2470                 gtk_widget_show(w);
2471
2472                 w = container;
2473                 uc->label = label;
2474             }
2475
2476             break;
2477           case CTRL_TEXT:
2478 #if !GTK_CHECK_VERSION(3,0,0)
2479             /*
2480              * Wrapping text widgets don't sit well with the GTK2
2481              * layout model, in which widgets state a minimum size
2482              * and the whole window then adjusts to the smallest
2483              * size it can sensibly take given its contents. A
2484              * wrapping text widget _has_ no clear minimum size;
2485              * instead it has a range of possibilities. It can be
2486              * one line deep but 2000 wide, or two lines deep and
2487              * 1000 pixels, or three by 867, or four by 500 and so
2488              * on. It can be as short as you like provided you
2489              * don't mind it being wide, or as narrow as you like
2490              * provided you don't mind it being tall.
2491              * 
2492              * Therefore, it fits very badly into the layout model.
2493              * Hence the only thing to do is pick a width and let
2494              * it choose its own number of lines. To do this I'm
2495              * going to cheat a little. All new wrapping text
2496              * widgets will be created with a minimal text content
2497              * "X"; then, after the rest of the dialog box is set
2498              * up and its size calculated, the text widgets will be
2499              * told their width and given their real text, which
2500              * will cause the size to be recomputed in the y
2501              * direction (because many of them will expand to more
2502              * than one line).
2503              */
2504             uc->text = w = gtk_label_new("X");
2505             uc->textsig =
2506                 g_signal_connect(G_OBJECT(w), "size-allocate",
2507                                  G_CALLBACK(label_sizealloc), dp);
2508 #else
2509             /*
2510              * In GTK3, this is all fixed, because the main aim of the
2511              * new 'height-for-width' geometry management is to make
2512              * wrapping labels behave sensibly. So now we can just do
2513              * the obvious thing.
2514              */
2515             uc->text = w = gtk_label_new(uc->ctrl->generic.label);
2516 #endif
2517             gtk_misc_set_alignment(GTK_MISC(w), 0.0, 0.0);
2518             gtk_label_set_line_wrap(GTK_LABEL(w), TRUE);
2519             break;
2520         }
2521
2522         assert(w != NULL);
2523
2524         columns_add(cols, w,
2525                     COLUMN_START(ctrl->generic.column),
2526                     COLUMN_SPAN(ctrl->generic.column));
2527         if (left)
2528             columns_force_left_align(cols, w);
2529         gtk_widget_show(w);
2530
2531         uc->toplevel = w;
2532         dlg_add_uctrl(dp, uc);
2533     }
2534
2535     return ret;
2536 }
2537
2538 struct selparam {
2539     struct dlgparam *dp;
2540     GtkNotebook *panels;
2541     GtkWidget *panel;
2542 #if !GTK_CHECK_VERSION(2,0,0)
2543     GtkWidget *treeitem;
2544 #else
2545     int depth;
2546     GtkTreePath *treepath;
2547 #endif
2548     struct Shortcuts shortcuts;
2549 };
2550
2551 #if GTK_CHECK_VERSION(2,0,0)
2552 static void treeselection_changed(GtkTreeSelection *treeselection,
2553                                   gpointer data)
2554 {
2555     struct selparam *sps = (struct selparam *)data, *sp;
2556     GtkTreeModel *treemodel;
2557     GtkTreeIter treeiter;
2558     gint spindex;
2559     gint page_num;
2560
2561     if (!gtk_tree_selection_get_selected(treeselection, &treemodel, &treeiter))
2562         return;
2563
2564     gtk_tree_model_get(treemodel, &treeiter, TREESTORE_PARAMS, &spindex, -1);
2565     sp = &sps[spindex];
2566
2567     page_num = gtk_notebook_page_num(sp->panels, sp->panel);
2568     gtk_notebook_set_current_page(sp->panels, page_num);
2569
2570     dlg_refresh(NULL, sp->dp);
2571
2572     sp->dp->shortcuts = &sp->shortcuts;
2573 }
2574 #else
2575 static void treeitem_sel(GtkItem *item, gpointer data)
2576 {
2577     struct selparam *sp = (struct selparam *)data;
2578     gint page_num;
2579
2580     page_num = gtk_notebook_page_num(sp->panels, sp->panel);
2581     gtk_notebook_set_page(sp->panels, page_num);
2582
2583     dlg_refresh(NULL, sp->dp);
2584
2585     sp->dp->shortcuts = &sp->shortcuts;
2586     sp->dp->currtreeitem = sp->treeitem;
2587 }
2588 #endif
2589
2590 static void window_destroy(GtkWidget *widget, gpointer data)
2591 {
2592     gtk_main_quit();
2593 }
2594
2595 #if !GTK_CHECK_VERSION(2,0,0)
2596 static int tree_grab_focus(struct dlgparam *dp)
2597 {
2598     int i, f;
2599
2600     /*
2601      * See if any of the treeitems has the focus.
2602      */
2603     f = -1;
2604     for (i = 0; i < dp->ntreeitems; i++)
2605         if (GTK_WIDGET_HAS_FOCUS(dp->treeitems[i])) {
2606             f = i;
2607             break;
2608         }
2609
2610     if (f >= 0)
2611         return FALSE;
2612     else {
2613         gtk_widget_grab_focus(dp->currtreeitem);
2614         return TRUE;
2615     }
2616 }
2617
2618 gint tree_focus(GtkContainer *container, GtkDirectionType direction,
2619                 gpointer data)
2620 {
2621     struct dlgparam *dp = (struct dlgparam *)data;
2622
2623     g_signal_stop_emission_by_name(G_OBJECT(container), "focus");
2624     /*
2625      * If there's a focused treeitem, we return FALSE to cause the
2626      * focus to move on to some totally other control. If not, we
2627      * focus the selected one.
2628      */
2629     return tree_grab_focus(dp);
2630 }
2631 #endif
2632
2633 int win_key_press(GtkWidget *widget, GdkEventKey *event, gpointer data)
2634 {
2635     struct dlgparam *dp = (struct dlgparam *)data;
2636
2637     if (event->keyval == GDK_KEY_Escape && dp->cancelbutton) {
2638         g_signal_emit_by_name(G_OBJECT(dp->cancelbutton), "clicked");
2639         return TRUE;
2640     }
2641
2642     if ((event->state & GDK_MOD1_MASK) &&
2643         (unsigned char)event->string[0] > 0 &&
2644         (unsigned char)event->string[0] <= 127) {
2645         int schr = (unsigned char)event->string[0];
2646         struct Shortcut *sc = &dp->shortcuts->sc[schr];
2647
2648         switch (sc->action) {
2649           case SHORTCUT_TREE:
2650 #if GTK_CHECK_VERSION(2,0,0)
2651             gtk_widget_grab_focus(sc->widget);
2652 #else
2653             tree_grab_focus(dp);
2654 #endif
2655             break;
2656           case SHORTCUT_FOCUS:
2657             gtk_widget_grab_focus(sc->widget);
2658             break;
2659           case SHORTCUT_UCTRL:
2660             /*
2661              * We must do something sensible with a uctrl.
2662              * Precisely what this is depends on the type of
2663              * control.
2664              */
2665             switch (sc->uc->ctrl->generic.type) {
2666               case CTRL_CHECKBOX:
2667               case CTRL_BUTTON:
2668                 /* Check boxes and buttons get the focus _and_ get toggled. */
2669                 gtk_widget_grab_focus(sc->uc->toplevel);
2670                 g_signal_emit_by_name(G_OBJECT(sc->uc->toplevel), "clicked");
2671                 break;
2672               case CTRL_FILESELECT:
2673               case CTRL_FONTSELECT:
2674                 /* File/font selectors have their buttons pressed (ooer),
2675                  * and focus transferred to the edit box. */
2676                 g_signal_emit_by_name(G_OBJECT(sc->uc->button), "clicked");
2677                 gtk_widget_grab_focus(sc->uc->entry);
2678                 break;
2679               case CTRL_RADIO:
2680                 /*
2681                  * Radio buttons are fun, because they have
2682                  * multiple shortcuts. We must find whether the
2683                  * activated shortcut is the shortcut for the whole
2684                  * group, or for a particular button. In the former
2685                  * case, we find the currently selected button and
2686                  * focus it; in the latter, we focus-and-click the
2687                  * button whose shortcut was pressed.
2688                  */
2689                 if (schr == sc->uc->ctrl->radio.shortcut) {
2690                     int i;
2691                     for (i = 0; i < sc->uc->ctrl->radio.nbuttons; i++)
2692                         if (gtk_toggle_button_get_active
2693                             (GTK_TOGGLE_BUTTON(sc->uc->buttons[i]))) {
2694                             gtk_widget_grab_focus(sc->uc->buttons[i]);
2695                         }
2696                 } else if (sc->uc->ctrl->radio.shortcuts) {
2697                     int i;
2698                     for (i = 0; i < sc->uc->ctrl->radio.nbuttons; i++)
2699                         if (schr == sc->uc->ctrl->radio.shortcuts[i]) {
2700                             gtk_widget_grab_focus(sc->uc->buttons[i]);
2701                             g_signal_emit_by_name
2702                                 (G_OBJECT(sc->uc->buttons[i]), "clicked");
2703                         }
2704                 }
2705                 break;
2706               case CTRL_LISTBOX:
2707
2708 #if !GTK_CHECK_VERSION(2,4,0)
2709                 if (sc->uc->optmenu) {
2710                     GdkEventButton bev;
2711                     gint returnval;
2712
2713                     gtk_widget_grab_focus(sc->uc->optmenu);
2714                     /* Option menus don't work using the "clicked" signal.
2715                      * We need to manufacture a button press event :-/ */
2716                     bev.type = GDK_BUTTON_PRESS;
2717                     bev.button = 1;
2718                     g_signal_emit_by_name(G_OBJECT(sc->uc->optmenu),
2719                                           "button_press_event",
2720                                           &bev, &returnval);
2721                     break;
2722                 }
2723 #else
2724                 if (sc->uc->combo) {
2725                     gtk_widget_grab_focus(sc->uc->combo);
2726                     gtk_combo_box_popup(GTK_COMBO_BOX(sc->uc->combo));
2727                     break;
2728                 }
2729 #endif
2730 #if !GTK_CHECK_VERSION(2,0,0)
2731                 if (sc->uc->list) {
2732                     /*
2733                      * For GTK-1 style list boxes, we tell it to
2734                      * focus one of its children, which appears to
2735                      * do the Right Thing.
2736                      */
2737                     gtk_container_focus(GTK_CONTAINER(sc->uc->list),
2738                                         GTK_DIR_TAB_FORWARD);
2739                     break;
2740                 }
2741 #else
2742                 if (sc->uc->treeview) {
2743                     gtk_widget_grab_focus(sc->uc->treeview);
2744                     break;
2745                 }
2746 #endif
2747                 assert(!"We shouldn't get here");
2748                 break;
2749             }
2750             break;
2751         }
2752     }
2753
2754     return FALSE;
2755 }
2756
2757 #if !GTK_CHECK_VERSION(2,0,0)
2758 int tree_key_press(GtkWidget *widget, GdkEventKey *event, gpointer data)
2759 {
2760     struct dlgparam *dp = (struct dlgparam *)data;
2761
2762     if (event->keyval == GDK_Up || event->keyval == GDK_KP_Up ||
2763         event->keyval == GDK_Down || event->keyval == GDK_KP_Down) {
2764         int dir, i, j = -1;
2765         for (i = 0; i < dp->ntreeitems; i++)
2766             if (widget == dp->treeitems[i])
2767                 break;
2768         if (i < dp->ntreeitems) {
2769             if (event->keyval == GDK_Up || event->keyval == GDK_KP_Up)
2770                 dir = -1;
2771             else
2772                 dir = +1;
2773
2774             while (1) {
2775                 i += dir;
2776                 if (i < 0 || i >= dp->ntreeitems)
2777                     break;             /* nothing in that dir to select */
2778                 /*
2779                  * Determine if this tree item is visible.
2780                  */
2781                 {
2782                     GtkWidget *w = dp->treeitems[i];
2783                     int vis = TRUE;
2784                     while (w && (GTK_IS_TREE_ITEM(w) || GTK_IS_TREE(w))) {
2785                         if (!GTK_WIDGET_VISIBLE(w)) {
2786                             vis = FALSE;
2787                             break;
2788                         }
2789                         w = w->parent;
2790                     }
2791                     if (vis) {
2792                         j = i;         /* got one */
2793                         break;
2794                     }
2795                 }
2796             }
2797         }
2798         g_signal_stop_emission_by_name(G_OBJECT(widget), "key_press_event");
2799         if (j >= 0) {
2800             g_signal_emit_by_name(G_OBJECT(dp->treeitems[j]), "toggle");
2801             gtk_widget_grab_focus(dp->treeitems[j]);
2802         }
2803         return TRUE;
2804     }
2805
2806     /*
2807      * It's nice for Left and Right to expand and collapse tree
2808      * branches.
2809      */
2810     if (event->keyval == GDK_Left || event->keyval == GDK_KP_Left) {
2811         g_signal_stop_emission_by_name(G_OBJECT(widget), "key_press_event");
2812         gtk_tree_item_collapse(GTK_TREE_ITEM(widget));
2813         return TRUE;
2814     }
2815     if (event->keyval == GDK_Right || event->keyval == GDK_KP_Right) {
2816         g_signal_stop_emission_by_name(G_OBJECT(widget), "key_press_event");
2817         gtk_tree_item_expand(GTK_TREE_ITEM(widget));
2818         return TRUE;
2819     }
2820
2821     return FALSE;
2822 }
2823 #endif
2824
2825 static void shortcut_highlight(GtkWidget *labelw, int chr)
2826 {
2827     GtkLabel *label = GTK_LABEL(labelw);
2828     const gchar *currstr;
2829     gchar *pattern;
2830     int i;
2831
2832 #if !GTK_CHECK_VERSION(2,0,0)
2833     {
2834         gchar *currstr_nonconst;
2835         gtk_label_get(label, &currstr_nonconst);
2836         currstr = currstr_nonconst;
2837     }
2838 #else
2839     currstr = gtk_label_get_text(label);
2840 #endif
2841
2842     for (i = 0; currstr[i]; i++)
2843         if (tolower((unsigned char)currstr[i]) == chr) {
2844             pattern = dupprintf("%*s_", i, "");
2845             gtk_label_set_pattern(label, pattern);
2846             sfree(pattern);
2847             break;
2848         }
2849 }
2850
2851 void shortcut_add(struct Shortcuts *scs, GtkWidget *labelw,
2852                   int chr, int action, void *ptr)
2853 {
2854     if (chr == NO_SHORTCUT)
2855         return;
2856
2857     chr = tolower((unsigned char)chr);
2858
2859     assert(scs->sc[chr].action == SHORTCUT_EMPTY);
2860
2861     scs->sc[chr].action = action;
2862
2863     if (action == SHORTCUT_FOCUS) {
2864         scs->sc[chr].uc = NULL;
2865         scs->sc[chr].widget = (GtkWidget *)ptr;
2866     } else {
2867         scs->sc[chr].widget = NULL;
2868         scs->sc[chr].uc = (struct uctrl *)ptr;
2869     }
2870
2871     shortcut_highlight(labelw, chr);
2872 }
2873
2874 int get_listitemheight(GtkWidget *w)
2875 {
2876 #if !GTK_CHECK_VERSION(2,0,0)
2877     GtkWidget *listitem = gtk_list_item_new_with_label("foo");
2878     GtkRequisition req;
2879     gtk_widget_size_request(listitem, &req);
2880     g_object_ref_sink(G_OBJECT(listitem));
2881     return req.height;
2882 #else
2883     int height;
2884     GtkCellRenderer *cr = gtk_cell_renderer_text_new();
2885 #if GTK_CHECK_VERSION(3,0,0)
2886     {
2887         GtkRequisition req;
2888         /*
2889          * Since none of my list items wraps in this GUI, no
2890          * interesting width-for-height behaviour should be happening,
2891          * so I don't think it should matter here whether I ask for
2892          * the minimum or natural height.
2893          */
2894         gtk_cell_renderer_get_preferred_size(cr, w, &req, NULL);
2895         height = req.height;
2896     }
2897 #else
2898     gtk_cell_renderer_get_size(cr, w, NULL, NULL, NULL, NULL, &height);
2899 #endif
2900     g_object_ref(G_OBJECT(cr));
2901     g_object_ref_sink(G_OBJECT(cr));
2902     g_object_unref(G_OBJECT(cr));
2903     return height;
2904 #endif
2905 }
2906
2907 void set_dialog_action_area(GtkDialog *dlg, GtkWidget *w)
2908 {
2909 #if !GTK_CHECK_VERSION(2,0,0)
2910
2911     /*
2912      * In GTK 1, laying out the buttons at the bottom of the
2913      * configuration box is nice and easy, because a GtkDialog's
2914      * action_area is a GtkHBox which stretches to cover the full
2915      * width of the dialog. So we just put our Columns widget
2916      * straight into that hbox, and it ends up just where we want
2917      * it.
2918      */
2919     gtk_box_pack_start(GTK_BOX(dlg->action_area), w, TRUE, TRUE, 0);
2920
2921 #else
2922     /*
2923      * In GTK 2, the action area is now a GtkHButtonBox and its
2924      * layout behaviour seems to be different: it doesn't stretch
2925      * to cover the full width of the window, but instead finds its
2926      * own preferred width and right-aligns that within the window.
2927      * This isn't what we want, because we have both left-aligned
2928      * and right-aligned buttons coming out of the above call to
2929      * layout_ctrls(), and right-aligning the whole thing will
2930      * result in the former being centred and looking weird.
2931      *
2932      * So instead we abandon the dialog's action area completely:
2933      * we gtk_widget_hide() it in the below code, and we also call
2934      * gtk_dialog_set_has_separator() to remove the separator above
2935      * it. We then insert our own action area into the end of the
2936      * dialog's main vbox, and add our own separator above that.
2937      *
2938      * (Ideally, if we were a native GTK app, we would use the
2939      * GtkHButtonBox's _own_ innate ability to support one set of
2940      * buttons being right-aligned and one left-aligned. But to do
2941      * that here, we would have to either (a) pick apart our cross-
2942      * platform layout structures and treat them specially for this
2943      * particular set of controls, which would be painful, or else
2944      * (b) develop a special and simpler cross-platform
2945      * representation for these particular controls, and introduce
2946      * special-case code into all the _other_ platforms to handle
2947      * it. Neither appeals. Therefore, I regretfully discard the
2948      * GTKHButtonBox and go it alone.)
2949      */
2950
2951     GtkWidget *align;
2952     align = gtk_alignment_new(0, 0, 1, 1);
2953     gtk_container_add(GTK_CONTAINER(align), w);
2954     /*
2955      * The purpose of this GtkAlignment is to provide padding
2956      * around the buttons. The padding we use is twice the padding
2957      * used in our GtkColumns, because we nest two GtkColumns most
2958      * of the time (one separating the tree view from the main
2959      * controls, and another for the main controls themselves).
2960      */
2961 #if GTK_CHECK_VERSION(2,4,0)
2962     gtk_alignment_set_padding(GTK_ALIGNMENT(align), 8, 8, 8, 8);
2963 #endif
2964     gtk_widget_show(align);
2965     gtk_box_pack_end(GTK_BOX(gtk_dialog_get_content_area(dlg)),
2966                      align, FALSE, TRUE, 0);
2967     w = gtk_hseparator_new();
2968     gtk_box_pack_end(GTK_BOX(gtk_dialog_get_content_area(dlg)),
2969                      w, FALSE, TRUE, 0);
2970     gtk_widget_show(w);
2971     gtk_widget_hide(gtk_dialog_get_action_area(dlg));
2972 #if !GTK_CHECK_VERSION(3,0,0)
2973     /* This cosmetic property is withdrawn in GTK 3's GtkDialog */
2974     g_object_set(G_OBJECT(dlg), "has-separator", TRUE, (const char *)NULL);
2975 #endif
2976 #endif
2977 }
2978
2979 #if GTK_CHECK_VERSION(2,0,0)
2980 void initial_treeview_collapse(struct dlgparam *dp, GtkWidget *tree)
2981 {
2982     /*
2983      * Collapse the deeper branches of the treeview into the state we
2984      * like them to start off in. See comment below in do_config_box.
2985      */
2986     int i;
2987     for (i = 0; i < dp->nselparams; i++)
2988         if (dp->selparams[i].depth >= 2)
2989             gtk_tree_view_collapse_row(GTK_TREE_VIEW(tree),
2990                                        dp->selparams[i].treepath);
2991 }
2992 #endif
2993
2994 #if GTK_CHECK_VERSION(3,0,0)
2995 void treeview_map_event(GtkWidget *tree, gpointer data)
2996 {
2997     struct dlgparam *dp = (struct dlgparam *)data;
2998     GtkAllocation alloc;
2999     gtk_widget_get_allocation(tree, &alloc);
3000     gtk_widget_set_size_request(tree, alloc.width, -1);
3001     initial_treeview_collapse(dp, tree);
3002 }
3003 #endif
3004
3005 int do_config_box(const char *title, Conf *conf, int midsession,
3006                   int protcfginfo)
3007 {
3008     GtkWidget *window, *hbox, *vbox, *cols, *label,
3009         *tree, *treescroll, *panels, *panelvbox;
3010     int index, level, protocol;
3011     struct controlbox *ctrlbox;
3012     char *path;
3013 #if GTK_CHECK_VERSION(2,0,0)
3014     GtkTreeStore *treestore;
3015     GtkCellRenderer *treerenderer;
3016     GtkTreeViewColumn *treecolumn;
3017     GtkTreeSelection *treeselection;
3018     GtkTreeIter treeiterlevels[8];
3019 #else
3020     GtkTreeItem *treeitemlevels[8];
3021     GtkTree *treelevels[8];
3022 #endif
3023     struct dlgparam dp;
3024     struct Shortcuts scs;
3025
3026     struct selparam *selparams = NULL;
3027     int nselparams = 0, selparamsize = 0;
3028
3029     dlg_init(&dp);
3030
3031     for (index = 0; index < lenof(scs.sc); index++) {
3032         scs.sc[index].action = SHORTCUT_EMPTY;
3033     }
3034
3035     window = gtk_dialog_new();
3036
3037     ctrlbox = ctrl_new_box();
3038     protocol = conf_get_int(conf, CONF_protocol);
3039     setup_config_box(ctrlbox, midsession, protocol, protcfginfo);
3040     unix_setup_config_box(ctrlbox, midsession, protocol);
3041     gtk_setup_config_box(ctrlbox, midsession, window);
3042
3043     gtk_window_set_title(GTK_WINDOW(window), title);
3044     hbox = gtk_hbox_new(FALSE, 4);
3045     gtk_box_pack_start
3046         (GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(window))),
3047          hbox, TRUE, TRUE, 0);
3048     gtk_container_set_border_width(GTK_CONTAINER(hbox), 10);
3049     gtk_widget_show(hbox);
3050     vbox = gtk_vbox_new(FALSE, 4);
3051     gtk_box_pack_start(GTK_BOX(hbox), vbox, FALSE, FALSE, 0);
3052     gtk_widget_show(vbox);
3053     cols = columns_new(4);
3054     gtk_box_pack_start(GTK_BOX(vbox), cols, FALSE, FALSE, 0);
3055     gtk_widget_show(cols);
3056     label = gtk_label_new("Category:");
3057     columns_add(COLUMNS(cols), label, 0, 1);
3058     columns_force_left_align(COLUMNS(cols), label);
3059     gtk_widget_show(label);
3060     treescroll = gtk_scrolled_window_new(NULL, NULL);
3061 #if GTK_CHECK_VERSION(2,0,0)
3062     treestore = gtk_tree_store_new
3063         (TREESTORE_NUM, G_TYPE_STRING, G_TYPE_INT);
3064     tree = gtk_tree_view_new_with_model(GTK_TREE_MODEL(treestore));
3065     gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(tree), FALSE);
3066     treerenderer = gtk_cell_renderer_text_new();
3067     treecolumn = gtk_tree_view_column_new_with_attributes
3068         ("Label", treerenderer, "text", 0, NULL);
3069     gtk_tree_view_append_column(GTK_TREE_VIEW(tree), treecolumn);
3070     treeselection = gtk_tree_view_get_selection(GTK_TREE_VIEW(tree));
3071     gtk_tree_selection_set_mode(treeselection, GTK_SELECTION_BROWSE);
3072     gtk_container_add(GTK_CONTAINER(treescroll), tree);
3073 #else
3074     tree = gtk_tree_new();
3075     gtk_tree_set_view_mode(GTK_TREE(tree), GTK_TREE_VIEW_ITEM);
3076     gtk_tree_set_selection_mode(GTK_TREE(tree), GTK_SELECTION_BROWSE);
3077     g_signal_connect(G_OBJECT(tree), "focus",
3078                      G_CALLBACK(tree_focus), &dp);
3079 #endif
3080     g_signal_connect(G_OBJECT(tree), "focus_in_event",
3081                      G_CALLBACK(widget_focus), &dp);
3082     shortcut_add(&scs, label, 'g', SHORTCUT_TREE, tree);
3083     gtk_widget_show(treescroll);
3084     gtk_box_pack_start(GTK_BOX(vbox), treescroll, TRUE, TRUE, 0);
3085     panels = gtk_notebook_new();
3086     gtk_notebook_set_show_tabs(GTK_NOTEBOOK(panels), FALSE);
3087     gtk_notebook_set_show_border(GTK_NOTEBOOK(panels), FALSE);
3088     gtk_box_pack_start(GTK_BOX(hbox), panels, TRUE, TRUE, 0);
3089     gtk_widget_show(panels);
3090
3091     panelvbox = NULL;
3092     path = NULL;
3093     level = 0;
3094     for (index = 0; index < ctrlbox->nctrlsets; index++) {
3095         struct controlset *s = ctrlbox->ctrlsets[index];
3096         GtkWidget *w;
3097
3098         if (!*s->pathname) {
3099             w = layout_ctrls(&dp, &scs, s, GTK_WINDOW(window));
3100
3101             set_dialog_action_area(GTK_DIALOG(window), w);
3102         } else {
3103             int j = path ? ctrl_path_compare(s->pathname, path) : 0;
3104             if (j != INT_MAX) {        /* add to treeview, start new panel */
3105                 char *c;
3106 #if GTK_CHECK_VERSION(2,0,0)
3107                 GtkTreeIter treeiter;
3108 #else
3109                 GtkWidget *treeitem;
3110 #endif
3111                 int first;
3112
3113                 /*
3114                  * We expect never to find an implicit path
3115                  * component. For example, we expect never to see
3116                  * A/B/C followed by A/D/E, because that would
3117                  * _implicitly_ create A/D. All our path prefixes
3118                  * are expected to contain actual controls and be
3119                  * selectable in the treeview; so we would expect
3120                  * to see A/D _explicitly_ before encountering
3121                  * A/D/E.
3122                  */
3123                 assert(j == ctrl_path_elements(s->pathname) - 1);
3124
3125                 c = strrchr(s->pathname, '/');
3126                 if (!c)
3127                     c = s->pathname;
3128                 else
3129                     c++;
3130
3131                 path = s->pathname;
3132
3133                 first = (panelvbox == NULL);
3134
3135                 panelvbox = gtk_vbox_new(FALSE, 4);
3136                 gtk_widget_show(panelvbox);
3137                 gtk_notebook_append_page(GTK_NOTEBOOK(panels), panelvbox,
3138                                          NULL);
3139                 if (first) {
3140                     gint page_num;
3141
3142                     page_num = gtk_notebook_page_num(GTK_NOTEBOOK(panels),
3143                                                      panelvbox);
3144                     gtk_notebook_set_current_page(GTK_NOTEBOOK(panels),
3145                                                   page_num);
3146                 }
3147
3148                 if (nselparams >= selparamsize) {
3149                     selparamsize += 16;
3150                     selparams = sresize(selparams, selparamsize,
3151                                         struct selparam);
3152                 }
3153                 selparams[nselparams].dp = &dp;
3154                 selparams[nselparams].panels = GTK_NOTEBOOK(panels);
3155                 selparams[nselparams].panel = panelvbox;
3156                 selparams[nselparams].shortcuts = scs;   /* structure copy */
3157
3158                 assert(j-1 < level);
3159
3160 #if GTK_CHECK_VERSION(2,0,0)
3161                 if (j > 0)
3162                     /* treeiterlevels[j-1] will always be valid because we
3163                      * don't allow implicit path components; see above.
3164                      */
3165                     gtk_tree_store_append(treestore, &treeiter,
3166                                           &treeiterlevels[j-1]);
3167                 else
3168                     gtk_tree_store_append(treestore, &treeiter, NULL);
3169                 gtk_tree_store_set(treestore, &treeiter,
3170                                    TREESTORE_PATH, c,
3171                                    TREESTORE_PARAMS, nselparams,
3172                                    -1);
3173                 treeiterlevels[j] = treeiter;
3174
3175                 selparams[nselparams].depth = j;
3176                 if (j > 0) {
3177                     selparams[nselparams].treepath =
3178                         gtk_tree_model_get_path(GTK_TREE_MODEL(treestore),
3179                                                 &treeiterlevels[j-1]);
3180                     /*
3181                      * We are going to collapse all tree branches
3182                      * at depth greater than 2, but not _yet_; see
3183                      * the comment at the call to
3184                      * gtk_tree_view_collapse_row below.
3185                      */
3186                     gtk_tree_view_expand_row(GTK_TREE_VIEW(tree),
3187                                              selparams[nselparams].treepath,
3188                                              FALSE);
3189                 } else {
3190                     selparams[nselparams].treepath = NULL;
3191                 }
3192 #else
3193                 treeitem = gtk_tree_item_new_with_label(c);
3194                 if (j > 0) {
3195                     if (!treelevels[j-1]) {
3196                         treelevels[j-1] = GTK_TREE(gtk_tree_new());
3197                         gtk_tree_item_set_subtree
3198                             (treeitemlevels[j-1],
3199                              GTK_WIDGET(treelevels[j-1]));
3200                         if (j < 2)
3201                             gtk_tree_item_expand(treeitemlevels[j-1]);
3202                         else
3203                             gtk_tree_item_collapse(treeitemlevels[j-1]);
3204                     }
3205                     gtk_tree_append(treelevels[j-1], treeitem);
3206                 } else {
3207                     gtk_tree_append(GTK_TREE(tree), treeitem);
3208                 }
3209                 treeitemlevels[j] = GTK_TREE_ITEM(treeitem);
3210                 treelevels[j] = NULL;
3211
3212                 g_signal_connect(G_OBJECT(treeitem), "key_press_event",
3213                                  G_CALLBACK(tree_key_press), &dp);
3214                 g_signal_connect(G_OBJECT(treeitem), "focus_in_event",
3215                                  G_CALLBACK(widget_focus), &dp);
3216
3217                 gtk_widget_show(treeitem);
3218
3219                 if (first)
3220                     gtk_tree_select_child(GTK_TREE(tree), treeitem);
3221                 selparams[nselparams].treeitem = treeitem;
3222 #endif
3223
3224                 level = j+1;
3225                 nselparams++;
3226             }
3227
3228             w = layout_ctrls(&dp, &selparams[nselparams-1].shortcuts, s, NULL);
3229             gtk_box_pack_start(GTK_BOX(panelvbox), w, FALSE, FALSE, 0);
3230             gtk_widget_show(w);
3231         }
3232     }
3233
3234 #if GTK_CHECK_VERSION(2,0,0)
3235     /*
3236      * We want our tree view to come up with all branches at depth 2
3237      * or more collapsed. However, if we start off with those branches
3238      * collapsed, then the tree view's size request will be calculated
3239      * based on the width of the collapsed tree, and then when the
3240      * collapsed branches are expanded later, the tree view will
3241      * jarringly change size.
3242      *
3243      * So instead we start with everything expanded; then, once the
3244      * tree view has computed its resulting width requirement, we
3245      * collapse the relevant rows, but force the width to be the value
3246      * we just retrieved. This arranges that the tree view is wide
3247      * enough to have all branches expanded without further resizing.
3248      */
3249
3250     dp.nselparams = nselparams;
3251     dp.selparams = selparams;
3252
3253 #if !GTK_CHECK_VERSION(3,0,0)
3254     {
3255         /*
3256          * In GTK2, we can just do the job right now.
3257          */
3258         GtkRequisition req;
3259         gtk_widget_size_request(tree, &req);
3260         initial_treeview_collapse(&dp, tree);
3261         gtk_widget_set_size_request(tree, req.width, -1);
3262     }
3263 #else
3264     /*
3265      * But in GTK3, we have to wait until the widget is about to be
3266      * mapped, because the size computation won't have been done yet.
3267      */
3268     g_signal_connect(G_OBJECT(tree), "map",
3269                      G_CALLBACK(treeview_map_event), &dp);
3270 #endif /* GTK 2 vs 3 */
3271 #endif /* GTK 2+ vs 1 */
3272
3273 #if GTK_CHECK_VERSION(2,0,0)
3274     g_signal_connect(G_OBJECT(treeselection), "changed",
3275                      G_CALLBACK(treeselection_changed), selparams);
3276 #else
3277     dp.ntreeitems = nselparams;
3278     dp.treeitems = snewn(dp.ntreeitems, GtkWidget *);
3279     for (index = 0; index < nselparams; index++) {
3280         g_signal_connect(G_OBJECT(selparams[index].treeitem), "select",
3281                          G_CALLBACK(treeitem_sel),
3282                          &selparams[index]);
3283         dp.treeitems[index] = selparams[index].treeitem;
3284     }
3285 #endif
3286
3287     dp.data = conf;
3288     dlg_refresh(NULL, &dp);
3289
3290     dp.shortcuts = &selparams[0].shortcuts;
3291 #if !GTK_CHECK_VERSION(2,0,0)
3292     dp.currtreeitem = dp.treeitems[0];
3293 #endif
3294     dp.lastfocus = NULL;
3295     dp.retval = 0;
3296     dp.window = window;
3297
3298     {
3299         /* in gtkwin.c */
3300         extern void set_window_icon(GtkWidget *window,
3301                                     const char *const *const *icon,
3302                                     int n_icon);
3303         extern const char *const *const cfg_icon[];
3304         extern const int n_cfg_icon;
3305         set_window_icon(window, cfg_icon, n_cfg_icon);
3306     }
3307
3308 #if !GTK_CHECK_VERSION(2,0,0)
3309     gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(treescroll),
3310                                           tree);
3311 #endif
3312     gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(treescroll),
3313                                    GTK_POLICY_NEVER,
3314                                    GTK_POLICY_AUTOMATIC);
3315     gtk_widget_show(tree);
3316
3317     gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
3318     gtk_widget_show(window);
3319
3320     /*
3321      * Set focus into the first available control.
3322      */
3323     for (index = 0; index < ctrlbox->nctrlsets; index++) {
3324         struct controlset *s = ctrlbox->ctrlsets[index];
3325         int done = 0;
3326         int j;
3327
3328         if (*s->pathname) {
3329             for (j = 0; j < s->ncontrols; j++)
3330                 if (s->ctrls[j]->generic.type != CTRL_TABDELAY &&
3331                     s->ctrls[j]->generic.type != CTRL_COLUMNS &&
3332                     s->ctrls[j]->generic.type != CTRL_TEXT) {
3333                     dlg_set_focus(s->ctrls[j], &dp);
3334                     dp.lastfocus = s->ctrls[j];
3335                     done = 1;
3336                     break;
3337                 }
3338         }
3339         if (done)
3340             break;
3341     }
3342
3343     g_signal_connect(G_OBJECT(window), "destroy",
3344                      G_CALLBACK(window_destroy), NULL);
3345     g_signal_connect(G_OBJECT(window), "key_press_event",
3346                      G_CALLBACK(win_key_press), &dp);
3347
3348     gtk_main();
3349     post_main();
3350
3351     dlg_cleanup(&dp);
3352     sfree(selparams);
3353
3354     return dp.retval;
3355 }
3356
3357 static void messagebox_handler(union control *ctrl, void *dlg,
3358                                void *data, int event)
3359 {
3360     if (event == EVENT_ACTION)
3361         dlg_end(dlg, ctrl->generic.context.i);
3362 }
3363 int messagebox(GtkWidget *parentwin, const char *title, const char *msg,
3364                int minwid, ...)
3365 {
3366     GtkWidget *window, *w0, *w1;
3367     struct controlbox *ctrlbox;
3368     struct controlset *s0, *s1;
3369     union control *c;
3370     struct dlgparam dp;
3371     struct Shortcuts scs;
3372     int index, ncols;
3373     va_list ap;
3374
3375     dlg_init(&dp);
3376
3377     for (index = 0; index < lenof(scs.sc); index++) {
3378         scs.sc[index].action = SHORTCUT_EMPTY;
3379     }
3380
3381     ctrlbox = ctrl_new_box();
3382
3383     ncols = 0;
3384     va_start(ap, minwid);
3385     while (va_arg(ap, char *) != NULL) {
3386         ncols++;
3387         (void) va_arg(ap, int);        /* shortcut */
3388         (void) va_arg(ap, int);        /* normal/default/cancel */
3389         (void) va_arg(ap, int);        /* end value */
3390     }
3391     va_end(ap);
3392
3393     s0 = ctrl_getset(ctrlbox, "", "", "");
3394     c = ctrl_columns(s0, 2, 50, 50);
3395     c->columns.ncols = s0->ncolumns = ncols;
3396     c->columns.percentages = sresize(c->columns.percentages, ncols, int);
3397     for (index = 0; index < ncols; index++)
3398         c->columns.percentages[index] = (index+1)*100/ncols - index*100/ncols;
3399     va_start(ap, minwid);
3400     index = 0;
3401     while (1) {
3402         char *title = va_arg(ap, char *);
3403         int shortcut, type, value;
3404         if (title == NULL)
3405             break;
3406         shortcut = va_arg(ap, int);
3407         type = va_arg(ap, int);
3408         value = va_arg(ap, int);
3409         c = ctrl_pushbutton(s0, title, shortcut, HELPCTX(no_help),
3410                             messagebox_handler, I(value));
3411         c->generic.column = index++;
3412         if (type > 0)
3413             c->button.isdefault = TRUE;
3414         else if (type < 0)
3415             c->button.iscancel = TRUE;
3416     }
3417     va_end(ap);
3418
3419     s1 = ctrl_getset(ctrlbox, "x", "", "");
3420     ctrl_text(s1, msg, HELPCTX(no_help));
3421
3422     window = gtk_dialog_new();
3423     gtk_window_set_title(GTK_WINDOW(window), title);
3424     w0 = layout_ctrls(&dp, &scs, s0, GTK_WINDOW(window));
3425     set_dialog_action_area(GTK_DIALOG(window), w0);
3426     gtk_widget_show(w0);
3427     w1 = layout_ctrls(&dp, &scs, s1, GTK_WINDOW(window));
3428     gtk_container_set_border_width(GTK_CONTAINER(w1), 10);
3429     gtk_widget_set_size_request(w1, minwid+20, -1);
3430     gtk_box_pack_start
3431         (GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(window))),
3432          w1, TRUE, TRUE, 0);
3433     gtk_widget_show(w1);
3434
3435     dp.shortcuts = &scs;
3436     dp.lastfocus = NULL;
3437     dp.retval = 0;
3438     dp.window = window;
3439
3440     gtk_window_set_modal(GTK_WINDOW(window), TRUE);
3441     if (parentwin) {
3442         set_transient_window_pos(parentwin, window);
3443         gtk_window_set_transient_for(GTK_WINDOW(window),
3444                                      GTK_WINDOW(parentwin));
3445     } else
3446         gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
3447     gtk_widget_show(window);
3448
3449     g_signal_connect(G_OBJECT(window), "destroy",
3450                      G_CALLBACK(window_destroy), NULL);
3451     g_signal_connect(G_OBJECT(window), "key_press_event",
3452                      G_CALLBACK(win_key_press), &dp);
3453
3454     gtk_main();
3455     post_main();
3456
3457     dlg_cleanup(&dp);
3458     ctrl_free_box(ctrlbox);
3459
3460     return dp.retval;
3461 }
3462
3463 int string_width(const char *text)
3464 {
3465     int ret;
3466     get_label_text_dimensions(text, &ret, NULL);
3467     return ret;
3468 }
3469
3470 int reallyclose(void *frontend)
3471 {
3472     char *title = dupcat(appname, " Exit Confirmation", NULL);
3473     int ret = messagebox(GTK_WIDGET(get_window(frontend)),
3474                          title, "Are you sure you want to close this session?",
3475                          string_width("Most of the width of the above text"),
3476                          "Yes", 'y', +1, 1,
3477                          "No", 'n', -1, 0,
3478                          NULL);
3479     sfree(title);
3480     return ret;
3481 }
3482
3483 int verify_ssh_host_key(void *frontend, char *host, int port,
3484                         const char *keytype, char *keystr, char *fingerprint,
3485                         void (*callback)(void *ctx, int result), void *ctx)
3486 {
3487     static const char absenttxt[] =
3488         "The server's host key is not cached. You have no guarantee "
3489         "that the server is the computer you think it is.\n"
3490         "The server's %s key fingerprint is:\n"
3491         "%s\n"
3492         "If you trust this host, press \"Accept\" to add the key to "
3493         "PuTTY's cache and carry on connecting.\n"
3494         "If you want to carry on connecting just once, without "
3495         "adding the key to the cache, press \"Connect Once\".\n"
3496         "If you do not trust this host, press \"Cancel\" to abandon the "
3497         "connection.";
3498     static const char wrongtxt[] =
3499         "WARNING - POTENTIAL SECURITY BREACH!\n"
3500         "The server's host key does not match the one PuTTY has "
3501         "cached. This means that either the server administrator "
3502         "has changed the host key, or you have actually connected "
3503         "to another computer pretending to be the server.\n"
3504         "The new %s key fingerprint is:\n"
3505         "%s\n"
3506         "If you were expecting this change and trust the new key, "
3507         "press \"Accept\" to update PuTTY's cache and continue connecting.\n"
3508         "If you want to carry on connecting but without updating "
3509         "the cache, press \"Connect Once\".\n"
3510         "If you want to abandon the connection completely, press "
3511         "\"Cancel\" to cancel. Pressing \"Cancel\" is the ONLY guaranteed "
3512         "safe choice.";
3513     char *text;
3514     int ret;
3515
3516     /*
3517      * Verify the key.
3518      */
3519     ret = verify_host_key(host, port, keytype, keystr);
3520
3521     if (ret == 0)                      /* success - key matched OK */
3522         return 1;
3523
3524     text = dupprintf((ret == 2 ? wrongtxt : absenttxt), keytype, fingerprint);
3525
3526     ret = messagebox(GTK_WIDGET(get_window(frontend)),
3527                      "PuTTY Security Alert", text,
3528                      string_width(fingerprint),
3529                      "Accept", 'a', 0, 2,
3530                      "Connect Once", 'o', 0, 1,
3531                      "Cancel", 'c', -1, 0,
3532                      NULL);
3533
3534     sfree(text);
3535
3536     if (ret == 2) {
3537         store_host_key(host, port, keytype, keystr);
3538         return 1;                      /* continue with connection */
3539     } else if (ret == 1)
3540         return 1;                      /* continue with connection */
3541     return 0;                          /* do not continue with connection */
3542 }
3543
3544 /*
3545  * Ask whether the selected algorithm is acceptable (since it was
3546  * below the configured 'warn' threshold).
3547  */
3548 int askalg(void *frontend, const char *algtype, const char *algname,
3549            void (*callback)(void *ctx, int result), void *ctx)
3550 {
3551     static const char msg[] =
3552         "The first %s supported by the server is "
3553         "%s, which is below the configured warning threshold.\n"
3554         "Continue with connection?";
3555     char *text;
3556     int ret;
3557
3558     text = dupprintf(msg, algtype, algname);
3559     ret = messagebox(GTK_WIDGET(get_window(frontend)),
3560                      "PuTTY Security Alert", text,
3561                      string_width("Continue with connection?"),
3562                      "Yes", 'y', 0, 1,
3563                      "No", 'n', 0, 0,
3564                      NULL);
3565     sfree(text);
3566
3567     if (ret) {
3568         return 1;
3569     } else {
3570         return 0;
3571     }
3572 }
3573
3574 void old_keyfile_warning(void)
3575 {
3576     /*
3577      * This should never happen on Unix. We hope.
3578      */
3579 }
3580
3581 void fatal_message_box(void *window, const char *msg)
3582 {
3583     messagebox(window, "PuTTY Fatal Error", msg,
3584                string_width("REASONABLY LONG LINE OF TEXT FOR BASIC SANITY"),
3585                "OK", 'o', 1, 1, NULL);
3586 }
3587
3588 void nonfatal_message_box(void *window, const char *msg)
3589 {
3590     messagebox(window, "PuTTY Error", msg,
3591                string_width("REASONABLY LONG LINE OF TEXT FOR BASIC SANITY"),
3592                "OK", 'o', 1, 1, NULL);
3593 }
3594
3595 void fatalbox(const char *p, ...)
3596 {
3597     va_list ap;
3598     char *msg;
3599     va_start(ap, p);
3600     msg = dupvprintf(p, ap);
3601     va_end(ap);
3602     fatal_message_box(NULL, msg);
3603     sfree(msg);
3604     cleanup_exit(1);
3605 }
3606
3607 void nonfatal(const char *p, ...)
3608 {
3609     va_list ap;
3610     char *msg;
3611     va_start(ap, p);
3612     msg = dupvprintf(p, ap);
3613     va_end(ap);
3614     nonfatal_message_box(NULL, msg);
3615     sfree(msg);
3616 }
3617
3618 static GtkWidget *aboutbox = NULL;
3619
3620 static void about_close_clicked(GtkButton *button, gpointer data)
3621 {
3622     gtk_widget_destroy(aboutbox);
3623     aboutbox = NULL;
3624 }
3625
3626 static void licence_clicked(GtkButton *button, gpointer data)
3627 {
3628     char *title;
3629
3630     const char *licence =
3631         "Copyright 1997-2015 Simon Tatham.\n\n"
3632
3633         "Portions copyright Robert de Bath, Joris van Rantwijk, Delian "
3634         "Delchev, Andreas Schultz, Jeroen Massar, Wez Furlong, Nicolas "
3635         "Barry, Justin Bradford, Ben Harris, Malcolm Smith, Ahmad Khalifa, "
3636         "Markus Kuhn, Colin Watson, Christopher Staite, and CORE SDI S.A.\n\n"
3637
3638         "Permission is hereby granted, free of charge, to any person "
3639         "obtaining a copy of this software and associated documentation "
3640         "files (the ""Software""), to deal in the Software without restriction, "
3641         "including without limitation the rights to use, copy, modify, merge, "
3642         "publish, distribute, sublicense, and/or sell copies of the Software, "
3643         "and to permit persons to whom the Software is furnished to do so, "
3644         "subject to the following conditions:\n\n"
3645
3646         "The above copyright notice and this permission notice shall be "
3647         "included in all copies or substantial portions of the Software.\n\n"
3648
3649         "THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT "
3650         "WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, "
3651         "INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF "
3652         "MERCHANTABILITY, FITNESS FOR A PARTICULAR "
3653         "PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE "
3654         "COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES "
3655         "OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, "
3656         "TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN "
3657         "CONNECTION WITH THE SOFTWARE OR THE USE OR "
3658         "OTHER DEALINGS IN THE SOFTWARE.";
3659
3660     title = dupcat(appname, " Licence", NULL);
3661     assert(aboutbox != NULL);
3662     messagebox(aboutbox, title, licence,
3663                string_width("LONGISH LINE OF TEXT SO THE LICENCE"
3664                             " BOX ISN'T EXCESSIVELY TALL AND THIN"),
3665                "OK", 'o', 1, 1, NULL);
3666     sfree(title);
3667 }
3668
3669 void about_box(void *window)
3670 {
3671     GtkWidget *w;
3672     char *title;
3673
3674     if (aboutbox) {
3675         gtk_widget_grab_focus(aboutbox);
3676         return;
3677     }
3678
3679     aboutbox = gtk_dialog_new();
3680     gtk_container_set_border_width(GTK_CONTAINER(aboutbox), 10);
3681     title = dupcat("About ", appname, NULL);
3682     gtk_window_set_title(GTK_WINDOW(aboutbox), title);
3683     sfree(title);
3684
3685     w = gtk_button_new_with_label("Close");
3686     gtk_widget_set_can_default(w, TRUE);
3687     gtk_window_set_default(GTK_WINDOW(aboutbox), w);
3688     gtk_box_pack_end(GTK_BOX(gtk_dialog_get_action_area(GTK_DIALOG(aboutbox))),
3689                      w, FALSE, FALSE, 0);
3690     g_signal_connect(G_OBJECT(w), "clicked",
3691                      G_CALLBACK(about_close_clicked), NULL);
3692     gtk_widget_show(w);
3693
3694     w = gtk_button_new_with_label("View Licence");
3695     gtk_widget_set_can_default(w, TRUE);
3696     gtk_box_pack_end(GTK_BOX(gtk_dialog_get_action_area(GTK_DIALOG(aboutbox))),
3697                      w, FALSE, FALSE, 0);
3698     g_signal_connect(G_OBJECT(w), "clicked",
3699                      G_CALLBACK(licence_clicked), NULL);
3700     gtk_widget_show(w);
3701
3702     w = gtk_label_new(appname);
3703     gtk_box_pack_start
3704         (GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(aboutbox))),
3705          w, FALSE, FALSE, 0);
3706     gtk_widget_show(w);
3707
3708     w = gtk_label_new(ver);
3709     gtk_box_pack_start
3710         (GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(aboutbox))),
3711          w, FALSE, FALSE, 5);
3712     gtk_widget_show(w);
3713
3714     w = gtk_label_new("Copyright 1997-2015 Simon Tatham. All rights reserved");
3715     gtk_box_pack_start
3716         (GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(aboutbox))),
3717          w, FALSE, FALSE, 5);
3718     gtk_widget_show(w);
3719
3720     set_transient_window_pos(GTK_WIDGET(window), aboutbox);
3721     gtk_window_set_transient_for(GTK_WINDOW(aboutbox),
3722                                  GTK_WINDOW(window));
3723     gtk_widget_show(aboutbox);
3724 }
3725
3726 struct eventlog_stuff {
3727     GtkWidget *parentwin, *window;
3728     struct controlbox *eventbox;
3729     struct Shortcuts scs;
3730     struct dlgparam dp;
3731     union control *listctrl;
3732     char **events;
3733     int nevents, negsize;
3734     char *seldata;
3735     int sellen;
3736     int ignore_selchange;
3737 };
3738
3739 static void eventlog_destroy(GtkWidget *widget, gpointer data)
3740 {
3741     struct eventlog_stuff *es = (struct eventlog_stuff *)data;
3742
3743     es->window = NULL;
3744     sfree(es->seldata);
3745     es->seldata = NULL;
3746     dlg_cleanup(&es->dp);
3747     ctrl_free_box(es->eventbox);
3748 }
3749 static void eventlog_ok_handler(union control *ctrl, void *dlg,
3750                                 void *data, int event)
3751 {
3752     if (event == EVENT_ACTION)
3753         dlg_end(dlg, 0);
3754 }
3755 static void eventlog_list_handler(union control *ctrl, void *dlg,
3756                                   void *data, int event)
3757 {
3758     struct eventlog_stuff *es = (struct eventlog_stuff *)data;
3759
3760     if (event == EVENT_REFRESH) {
3761         int i;
3762
3763         dlg_update_start(ctrl, dlg);
3764         dlg_listbox_clear(ctrl, dlg);
3765         for (i = 0; i < es->nevents; i++) {
3766             dlg_listbox_add(ctrl, dlg, es->events[i]);
3767         }
3768         dlg_update_done(ctrl, dlg);
3769     } else if (event == EVENT_SELCHANGE) {
3770         int i;
3771         int selsize = 0;
3772
3773         /*
3774          * If this SELCHANGE event is happening as a result of
3775          * deliberate deselection because someone else has grabbed
3776          * the selection, the last thing we want to do is pre-empt
3777          * them.
3778          */
3779         if (es->ignore_selchange)
3780             return;
3781
3782         /*
3783          * Construct the data to use as the selection.
3784          */
3785         sfree(es->seldata);
3786         es->seldata = NULL;
3787         es->sellen = 0;
3788         for (i = 0; i < es->nevents; i++) {
3789             if (dlg_listbox_issel(ctrl, dlg, i)) {
3790                 int extralen = strlen(es->events[i]);
3791
3792                 if (es->sellen + extralen + 2 > selsize) {
3793                     selsize = es->sellen + extralen + 512;
3794                     es->seldata = sresize(es->seldata, selsize, char);
3795                 }
3796
3797                 strcpy(es->seldata + es->sellen, es->events[i]);
3798                 es->sellen += extralen;
3799                 es->seldata[es->sellen++] = '\n';
3800             }
3801         }
3802
3803         if (gtk_selection_owner_set(es->window, GDK_SELECTION_PRIMARY,
3804                                     GDK_CURRENT_TIME)) {
3805             extern GdkAtom compound_text_atom;
3806
3807             gtk_selection_add_target(es->window, GDK_SELECTION_PRIMARY,
3808                                      GDK_SELECTION_TYPE_STRING, 1);
3809             gtk_selection_add_target(es->window, GDK_SELECTION_PRIMARY,
3810                                      compound_text_atom, 1);
3811         }
3812
3813     }
3814 }
3815
3816 void eventlog_selection_get(GtkWidget *widget, GtkSelectionData *seldata,
3817                             guint info, guint time_stamp, gpointer data)
3818 {
3819     struct eventlog_stuff *es = (struct eventlog_stuff *)data;
3820
3821     gtk_selection_data_set(seldata, gtk_selection_data_get_target(seldata), 8,
3822                            (unsigned char *)es->seldata, es->sellen);
3823 }
3824
3825 gint eventlog_selection_clear(GtkWidget *widget, GdkEventSelection *seldata,
3826                               gpointer data)
3827 {
3828     struct eventlog_stuff *es = (struct eventlog_stuff *)data;
3829     struct uctrl *uc;
3830
3831     /*
3832      * Deselect everything in the list box.
3833      */
3834     uc = dlg_find_byctrl(&es->dp, es->listctrl);
3835     es->ignore_selchange = 1;
3836 #if !GTK_CHECK_VERSION(2,0,0)
3837     assert(uc->list);
3838     gtk_list_unselect_all(GTK_LIST(uc->list));
3839 #else
3840     assert(uc->treeview);
3841     gtk_tree_selection_unselect_all
3842         (gtk_tree_view_get_selection(GTK_TREE_VIEW(uc->treeview)));
3843 #endif
3844     es->ignore_selchange = 0;
3845
3846     sfree(es->seldata);
3847     es->sellen = 0;
3848     es->seldata = NULL;
3849     return TRUE;
3850 }
3851
3852 void showeventlog(void *estuff, void *parentwin)
3853 {
3854     struct eventlog_stuff *es = (struct eventlog_stuff *)estuff;
3855     GtkWidget *window, *w0, *w1;
3856     GtkWidget *parent = GTK_WIDGET(parentwin);
3857     struct controlset *s0, *s1;
3858     union control *c;
3859     int index;
3860     char *title;
3861
3862     if (es->window) {
3863         gtk_widget_grab_focus(es->window);
3864         return;
3865     }
3866
3867     dlg_init(&es->dp);
3868
3869     for (index = 0; index < lenof(es->scs.sc); index++) {
3870         es->scs.sc[index].action = SHORTCUT_EMPTY;
3871     }
3872
3873     es->eventbox = ctrl_new_box();
3874
3875     s0 = ctrl_getset(es->eventbox, "", "", "");
3876     ctrl_columns(s0, 3, 33, 34, 33);
3877     c = ctrl_pushbutton(s0, "Close", 'c', HELPCTX(no_help),
3878                         eventlog_ok_handler, P(NULL));
3879     c->button.column = 1;
3880     c->button.isdefault = TRUE;
3881
3882     s1 = ctrl_getset(es->eventbox, "x", "", "");
3883     es->listctrl = c = ctrl_listbox(s1, NULL, NO_SHORTCUT, HELPCTX(no_help),
3884                                     eventlog_list_handler, P(es));
3885     c->listbox.height = 10;
3886     c->listbox.multisel = 2;
3887     c->listbox.ncols = 3;
3888     c->listbox.percentages = snewn(3, int);
3889     c->listbox.percentages[0] = 25;
3890     c->listbox.percentages[1] = 10;
3891     c->listbox.percentages[2] = 65;
3892
3893     es->window = window = gtk_dialog_new();
3894     title = dupcat(appname, " Event Log", NULL);
3895     gtk_window_set_title(GTK_WINDOW(window), title);
3896     sfree(title);
3897     w0 = layout_ctrls(&es->dp, &es->scs, s0, GTK_WINDOW(window));
3898     set_dialog_action_area(GTK_DIALOG(window), w0);
3899     gtk_widget_show(w0);
3900     w1 = layout_ctrls(&es->dp, &es->scs, s1, GTK_WINDOW(window));
3901     gtk_container_set_border_width(GTK_CONTAINER(w1), 10);
3902     gtk_widget_set_size_request(w1, 20 + string_width
3903                                 ("LINE OF TEXT GIVING WIDTH OF EVENT LOG IS "
3904                                  "QUITE LONG 'COS SSH LOG ENTRIES ARE WIDE"),
3905                                 -1);
3906     gtk_box_pack_start
3907         (GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(window))),
3908          w1, TRUE, TRUE, 0);
3909     gtk_widget_show(w1);
3910
3911     es->dp.data = es;
3912     es->dp.shortcuts = &es->scs;
3913     es->dp.lastfocus = NULL;
3914     es->dp.retval = 0;
3915     es->dp.window = window;
3916
3917     dlg_refresh(NULL, &es->dp);
3918
3919     if (parent) {
3920         set_transient_window_pos(parent, window);
3921         gtk_window_set_transient_for(GTK_WINDOW(window),
3922                                      GTK_WINDOW(parent));
3923     } else
3924         gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
3925     gtk_widget_show(window);
3926
3927     g_signal_connect(G_OBJECT(window), "destroy",
3928                      G_CALLBACK(eventlog_destroy), es);
3929     g_signal_connect(G_OBJECT(window), "key_press_event",
3930                      G_CALLBACK(win_key_press), &es->dp);
3931     g_signal_connect(G_OBJECT(window), "selection_get",
3932                      G_CALLBACK(eventlog_selection_get), es);
3933     g_signal_connect(G_OBJECT(window), "selection_clear_event",
3934                      G_CALLBACK(eventlog_selection_clear), es);
3935 }
3936
3937 void *eventlogstuff_new(void)
3938 {
3939     struct eventlog_stuff *es;
3940     es = snew(struct eventlog_stuff);
3941     memset(es, 0, sizeof(*es));
3942     return es;
3943 }
3944
3945 void logevent_dlg(void *estuff, const char *string)
3946 {
3947     struct eventlog_stuff *es = (struct eventlog_stuff *)estuff;
3948
3949     char timebuf[40];
3950     struct tm tm;
3951
3952     if (es->nevents >= es->negsize) {
3953         es->negsize += 64;
3954         es->events = sresize(es->events, es->negsize, char *);
3955     }
3956
3957     tm=ltime();
3958     strftime(timebuf, sizeof(timebuf), "%Y-%m-%d %H:%M:%S\t", &tm);
3959
3960     es->events[es->nevents] = snewn(strlen(timebuf) + strlen(string) + 1, char);
3961     strcpy(es->events[es->nevents], timebuf);
3962     strcat(es->events[es->nevents], string);
3963     if (es->window) {
3964         dlg_listbox_add(es->listctrl, &es->dp, es->events[es->nevents]);
3965     }
3966     es->nevents++;
3967 }
3968
3969 int askappend(void *frontend, Filename *filename,
3970               void (*callback)(void *ctx, int result), void *ctx)
3971 {
3972     static const char msgtemplate[] =
3973         "The session log file \"%.*s\" already exists. "
3974         "You can overwrite it with a new session log, "
3975         "append your session log to the end of it, "
3976         "or disable session logging for this session.";
3977     char *message;
3978     char *mbtitle;
3979     int mbret;
3980
3981     message = dupprintf(msgtemplate, FILENAME_MAX, filename->path);
3982     mbtitle = dupprintf("%s Log to File", appname);
3983
3984     mbret = messagebox(get_window(frontend), mbtitle, message,
3985                        string_width("LINE OF TEXT SUITABLE FOR THE"
3986                                     " ASKAPPEND WIDTH"),
3987                        "Overwrite", 'o', 1, 2,
3988                        "Append", 'a', 0, 1,
3989                        "Disable", 'd', -1, 0,
3990                        NULL);
3991
3992     sfree(message);
3993     sfree(mbtitle);
3994
3995     return mbret;
3996 }