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