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