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