c643d64c3bfd5781506a41b6994faf764fb76fb6
[xboard.git] / gtk / xoptions.c
1 /*
2  * xoptions.c -- Move list window, part of X front end for XBoard
3  *
4  * Copyright 2000, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 Free Software Foundation, Inc.
5  * ------------------------------------------------------------------------
6  *
7  * GNU XBoard is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or (at
10  * your option) any later version.
11  *
12  * GNU XBoard is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program. If not, see http://www.gnu.org/licenses/.  *
19  *
20  *------------------------------------------------------------------------
21  ** See the file ChangeLog for a revision history.  */
22
23 // [HGM] this file is the counterpart of woptions.c, containing xboard popup menus
24 // similar to those of WinBoard, to set the most common options interactively.
25
26 #include "config.h"
27
28 #include <stdio.h>
29 #include <ctype.h>
30 #include <errno.h>
31 #include <sys/types.h>
32
33 #if STDC_HEADERS
34 # include <stdlib.h>
35 # include <string.h>
36 #else /* not STDC_HEADERS */
37 extern char *getenv();
38 # if HAVE_STRING_H
39 #  include <string.h>
40 # else /* not HAVE_STRING_H */
41 #  include <strings.h>
42 # endif /* not HAVE_STRING_H */
43 #endif /* not STDC_HEADERS */
44
45 #if HAVE_UNISTD_H
46 # include <unistd.h>
47 #endif
48 #include <stdint.h>
49
50 #include <cairo/cairo.h>
51 #include <gtk/gtk.h>
52 #include <gdk/gdkkeysyms.h>
53 #ifdef OSXAPP
54 #  include <gtkmacintegration/gtkosxapplication.h>
55 #endif
56
57 #include "common.h"
58 #include "backend.h"
59 #include "xboard.h"
60 #include "xboard2.h"
61 #include "dialogs.h"
62 #include "menus.h"
63 #include "gettext.h"
64
65 #ifdef ENABLE_NLS
66 # define  _(s) gettext (s)
67 # define N_(s) gettext_noop (s)
68 #else
69 # define  _(s) (s)
70 # define N_(s)  s
71 #endif
72
73 // [HGM] the following code for makng menu popups was cloned from the FileNamePopUp routines
74
75 #ifdef TODO_GTK
76 static Widget previous = NULL;
77 #endif
78 static Option *currentOption;
79 static Boolean browserUp;
80
81 void
82 UnCaret ()
83 {
84 #ifdef TODO_GTK
85     Arg args[2];
86
87     if(previous) {
88         XtSetArg(args[0], XtNdisplayCaret, False);
89         XtSetValues(previous, args, 1);
90     }
91     previous = NULL;
92 #endif
93 }
94
95 #ifdef TODO_GTK
96 void
97 SetFocus (Widget w, XtPointer data, XEvent *event, Boolean *b)
98 {
99     Arg args[2];
100     char *s;
101     int j;
102
103     UnCaret();
104     XtSetArg(args[0], XtNstring, &s);
105     XtGetValues(w, args, 1);
106     j = 1;
107     XtSetArg(args[0], XtNdisplayCaret, True);
108     if(!strchr(s, '\n') && strlen(s) < 80) XtSetArg(args[1], XtNinsertPosition, strlen(s)), j++;
109     XtSetValues(w, args, j);
110     XtSetKeyboardFocus((Widget) data, w);
111     previous = w;
112 }
113 #endif
114
115 void
116 BoardFocus ()
117 {
118 #ifdef TODO_GTK
119     XtSetKeyboardFocus(shellWidget, formWidget);
120 #endif
121 }
122
123 //--------------------------- Engine-specific options menu ----------------------------------
124
125 int dialogError;
126 Option *dialogOptions[NrOfDialogs];
127
128 #ifdef TODO_GTK
129 static Arg layoutArgs[] = {
130     { XtNborderWidth, 0 },
131     { XtNdefaultDistance, 0 },
132 };
133
134 static Arg formArgs[] = {
135     { XtNborderWidth, 0 },
136     { XtNresizable, (XtArgVal) True },
137 };
138 #endif
139
140 void GetWidgetTextGTK(GtkWidget *w, char **buf)
141 {
142     GtkTextIter start;
143     GtkTextIter end;
144
145     if (GTK_IS_ENTRY(w)) {
146         *buf = (char *) gtk_entry_get_text(GTK_ENTRY (w));
147     } else
148     if (GTK_IS_TEXT_BUFFER(w)) {
149         gtk_text_buffer_get_start_iter(GTK_TEXT_BUFFER(w), &start);
150         gtk_text_buffer_get_end_iter(GTK_TEXT_BUFFER(w), &end);
151         *buf = gtk_text_buffer_get_text(GTK_TEXT_BUFFER(w), &start, &end, FALSE);
152     }
153     else {
154         printf("error in GetWidgetText, invalid widget\n");
155         *buf = NULL;
156     }
157 }
158
159 void
160 GetWidgetText (Option *opt, char **buf)
161 {
162     int x;
163     static char val[12];
164     switch(opt->type) {
165       case Fractional:
166       case FileName:
167       case PathName:
168       case TextBox: GetWidgetTextGTK((GtkWidget *) opt->handle, buf); break;
169       case Spin:
170         x = gtk_spin_button_get_value (GTK_SPIN_BUTTON(opt->handle));
171         snprintf(val, 12, "%d", x); *buf = val;
172         break;
173       default:
174         printf("unexpected case (%d) in GetWidgetText\n", opt->type);
175         *buf = NULL;
176     }
177 }
178
179 void SetSpinValue(Option *opt, char *val, int n)
180 {
181     if (opt->type == Spin)
182       {
183         if (!strcmp(val, _("Unused")))
184            gtk_widget_set_sensitive(opt->handle, FALSE);
185         else
186           {
187             gtk_widget_set_sensitive(opt->handle, TRUE);
188             gtk_spin_button_set_value(opt->handle, atoi(val));
189           }
190       }
191     else
192       printf("error in SetSpinValue, unknown type %d\n", opt->type);
193 }
194
195 void SetWidgetTextGTK(GtkWidget *w, char *text)
196 {
197     if (GTK_IS_ENTRY(w)) {
198         gtk_entry_set_text (GTK_ENTRY (w), text);
199     } else
200     if (GTK_IS_TEXT_BUFFER(w)) {
201         gtk_text_buffer_set_text(GTK_TEXT_BUFFER(w), text, -1);
202     } else
203         printf("error: SetWidgetTextGTK arg is neitherGtkEntry nor GtkTextBuffer\n");
204 }
205
206 void
207 SetWidgetText (Option *opt, char *buf, int n)
208 {
209     switch(opt->type) {
210       case Fractional:
211       case FileName:
212       case PathName:
213       case TextBox: SetWidgetTextGTK((GtkWidget *) opt->handle, buf); break;
214       case Spin: SetSpinValue(opt, buf, n); break;
215       default:
216         printf("unexpected case (%d) in GetWidgetText\n", opt->type);
217     }
218 #ifdef TODO_GTK
219 // focus is automatic in GTK?
220     if(n >= 0) SetFocus(opt->handle, shells[n], NULL, False);
221 #endif
222 }
223
224 void
225 GetWidgetState (Option *opt, int *state)
226 {
227     *state = gtk_toggle_button_get_active(opt->handle);
228 }
229
230 void
231 SetWidgetState (Option *opt, int state)
232 {
233     gtk_toggle_button_set_active(opt->handle, state);
234 }
235
236 void
237 SetWidgetLabel (Option *opt, char *buf)
238 {
239     if(opt->type == Button) // Chat window uses this routine for changing button labels
240         gtk_button_set_label(opt->handle, buf);
241     else
242         gtk_label_set_text(opt->handle, buf);
243 }
244
245 void
246 SetComboChoice (Option *opt, int n)
247 {
248     gtk_combo_box_set_active(opt->handle, n);
249 }
250
251 void
252 SetDialogTitle (DialogClass dlg, char *title)
253 {
254     gtk_window_set_title(GTK_WINDOW(shells[dlg]), title);
255 }
256
257 void
258 WidgetEcho (Option *opt, int n)
259 {
260     gtk_entry_set_visibility(opt->handle, n);
261 }
262
263 void
264 SetWidgetFont (GtkWidget *w, char **s)
265 {
266     PangoFontDescription *pfd;
267     if (!s || !*s || !**s) return; // uses no font, no font spec or empty font spec
268     pfd = pango_font_description_from_string(*s);
269     gtk_widget_modify_font(w, pfd);
270 }
271
272 void
273 ApplyFont (Option *opt, char *font)
274 {
275     GtkWidget *w = NULL;
276     if(!font && opt->font) font = *opt->font;
277     if(!font) return;
278     switch(opt->type) {
279       case ListBox:
280       case Label:   w = opt->handle; break;
281       case Button:  if(opt->handle) w = gtk_bin_get_child(GTK_BIN(opt->handle)); break;
282       case TextBox: w = (GtkWidget *) opt->textValue; if(!w) w = opt->handle; break;
283       default: ;
284     }
285     if(w && font) SetWidgetFont(w, &font);
286 }
287
288 GtkWidget *fbutton;
289
290 void
291 FontCallback (GtkWidget *widget, gpointer gdata)
292 {
293     Option *opt = (Option *) gdata;
294     gchar *p = (char *) gtk_font_button_get_font_name(GTK_FONT_BUTTON(fbutton));
295     SetWidgetText(opt, p, TransientDlg);
296     ApplyFont(opt, p);
297 }
298
299 void
300 SetListBoxItem (GtkListStore *store, int n, char *msg)
301 {
302     GtkTreeIter iter;
303     GtkTreePath *path = gtk_tree_path_new_from_indices(n, -1);
304     gtk_tree_model_get_iter(GTK_TREE_MODEL (store), &iter, path);
305     gtk_tree_path_free(path);
306     gtk_list_store_set(store, &iter, 0, msg, -1);
307 }
308
309 void
310 LoadListBox (Option *opt, char *emptyText, int n1, int n2)
311 {
312     char **data = (char **) (opt->target);
313     GtkWidget *list = (GtkWidget *) (opt->handle);
314     GtkTreeModel *model = gtk_tree_view_get_model(GTK_TREE_VIEW(list));
315     GtkListStore *store = GTK_LIST_STORE(model);
316     GtkTreeIter iter;
317
318     if(n1 >= 0 && n2 >= 0) {
319         SetListBoxItem(store, n1, data[n1]);
320         SetListBoxItem(store, n2, data[n2]);
321         return;
322     }
323
324     if (gtk_tree_model_get_iter_first(model, &iter))
325         gtk_list_store_clear(store);
326
327     while(*data) { // add elements to listbox one by one
328         gtk_list_store_append(store, &iter);
329         gtk_list_store_set(store, &iter, 0, *data++, -1); // 0 = first column
330     }
331 }
332
333 void
334 HighlightItem (Option *opt, int index, int scroll)
335 {
336     GtkWidget *list = (GtkWidget *) (opt->handle);
337     GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(list));
338     GtkTreePath *path = gtk_tree_path_new_from_indices(index, -1);
339     gtk_tree_selection_select_path(selection, path);
340     if(scroll) gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(list), path, NULL, 0, 0, 0);
341     gtk_tree_path_free(path);
342 }
343
344 void
345 HighlightListBoxItem (Option *opt, int index)
346 {
347     HighlightItem (opt, index, FALSE);
348 }
349
350 void
351 HighlightWithScroll (Option *opt, int index, int max)
352 {
353     HighlightItem (opt, index, TRUE); // ignore max
354 }
355
356 void
357 ScrollToCursor (Option *opt, int caretPos)
358 {
359     static GtkTextIter iter;
360     GtkTextMark *mark = gtk_text_buffer_get_mark((GtkTextBuffer *) opt->handle, "scrollmark");
361     gtk_text_buffer_get_iter_at_offset((GtkTextBuffer *) opt->handle, &iter, caretPos);
362     gtk_text_buffer_move_mark((GtkTextBuffer *) opt->handle, mark, &iter);
363     gtk_text_view_scroll_to_mark((GtkTextView *) opt->textValue, mark, 0.0, 0, 0.5, 0.5);
364 }
365
366 int
367 SelectedListBoxItem (Option *opt)
368 {
369     int i;
370     char *value, **data = (char **) (opt->target);
371     GtkWidget *list = (GtkWidget *) (opt->handle);
372     GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(list));
373
374     GtkTreeModel *model;
375     GtkTreeIter iter;
376     if (!gtk_tree_selection_get_selected(GTK_TREE_SELECTION(selection), &model, &iter)) return -1;
377     gtk_tree_model_get(model, &iter, 0, &value,  -1);
378     for(i=0; data[i]; i++) if(!strcmp(data[i], value)) return i;
379     g_free(value);
380     return -1;
381 }
382
383 void
384 FocusOnWidget (Option *opt, DialogClass dlg)
385 {
386     UnCaret();
387 #ifdef TODO_GTK
388     XtSetKeyboardFocus(shells[dlg], opt->handle);
389 #endif
390     if(dlg) gtk_window_present(GTK_WINDOW(shells[dlg]));
391     gtk_widget_grab_focus(opt->handle);
392 }
393
394 void
395 SetIconName (DialogClass dlg, char *name)
396 {
397 #ifdef TODO_GTK
398         Arg args[16];
399         int j = 0;
400         XtSetArg(args[j], XtNiconName, (XtArgVal) name);  j++;
401 //      XtSetArg(args[j], XtNtitle, (XtArgVal) name);  j++;
402         XtSetValues(shells[dlg], args, j);
403 #endif
404 }
405
406 static int menuBlock;
407
408 static gboolean
409 HelpEvent(GtkWidget *widget, GdkEventButton *event, gpointer gdata)
410 {   // intercept button3 clicks to pop up help
411     char *msg = (char *) gdata;
412     int menu = (event->type == GDK_BUTTON_RELEASE); // only menu items trigger help on release
413     if(event->button != 3) return FALSE;
414     menuBlock = 2*menu; // prevent menu action is really excuted by default action
415     if(menu) gtk_menu_item_activate(GTK_MENU_ITEM(widget)); // hideous kludge: activate (blocked) menu item twice to prevent check-marking
416     DisplayHelp(msg);
417     return !menu; // in case of menu we have to execute default action to popdown and unfocus
418 }
419
420 void ComboSelect(GtkWidget *widget, gpointer addr)
421 {
422     Option *opt = dialogOptions[((intptr_t)addr)>>8]; // applicable option list
423     gint i = ((intptr_t)addr) & 255; // option number
424     gint g;
425
426     g = gtk_combo_box_get_active(GTK_COMBO_BOX(widget));
427     values[i] = g; // store in temporary, for transfer at OK
428
429 #if TODO_GTK
430 // Note: setting text on button is probably automatic
431 // Is this still needed? Could be all comboboxes that needed a callbak are now listboxes!
432 #endif
433     if(opt[i].type == Graph || opt[i].min & COMBO_CALLBACK && (!currentCps || shellUp[BrowserDlg])) {
434         ((ButtonCallback*) opt[i].target)(i);
435         return;
436     }
437 }
438
439 #ifdef TODO_GTK
440 Widget
441 CreateMenuItem (Widget menu, char *msg, XtCallbackProc CB, int n)
442 {
443     int j=0;
444     Widget entry;
445     Arg args[16];
446     XtSetArg(args[j], XtNleftMargin, 20);   j++;
447     XtSetArg(args[j], XtNrightMargin, 20);  j++;
448     if(!strcmp(msg, "----")) { XtCreateManagedWidget(msg, smeLineObjectClass, menu, args, j); return NULL; }
449     XtSetArg(args[j], XtNlabel, msg);
450     entry = XtCreateManagedWidget("item", smeBSBObjectClass, menu, args, j+1);
451     XtAddCallback(entry, XtNcallback, CB, (caddr_t)(intptr_t) n);
452     return entry;
453 }
454 #endif
455
456 static void
457 MenuSelect (gpointer addr) // callback for all combo items
458 {
459     Option *opt = dialogOptions[((intptr_t)addr)>>24]; // applicable option list
460     int i = ((intptr_t)addr)>>16 & 255; // option number
461     int j = 0xFFFF & (intptr_t) addr;
462
463     if(menuBlock) { menuBlock--; return; } // was help click only
464     values[i] = j; // store selected value in Option struct, for retrieval at OK
465     ((ButtonCallback*) opt[i].target)(i);
466 }
467
468 static GtkWidget *
469 CreateMenuPopup (Option *opt, int n, int def)
470 {   // fromList determines if the item texts are taken from a list of strings, or from a menu table
471     int i;
472     GtkWidget *menu, *entry;
473     MenuItem *mb = (MenuItem *) opt->choice;
474
475     menu = gtk_menu_new();
476 //    menu = XtCreatePopupShell(opt->name, simpleMenuWidgetClass, parent, NULL, 0);
477     for (i=0; 1; i++)
478       {
479         char *msg = mb[i].string;
480         if(!msg) break;
481 #ifdef OSXAPP
482         if(!strcmp(msg, "Quit ")) continue;             // Quit item will appear automatically in App menu
483         if(!strcmp(msg, "About XBoard")) msg = "About"; // 'XBoard' will be appended automatically when moved to App menu 1st item
484 #endif
485         if(!strcmp(msg, "ICS Input Box")) { mb[i].handle = NULL; continue; } // suppress ICS Input Box in GTK
486         if(strcmp(msg, "----")) { //
487           if(!(opt->min & NO_GETTEXT)) msg = _(msg);
488           if(mb[i].handle) {
489             entry = gtk_check_menu_item_new_with_label(msg); // should be used for items that can be checkmarked
490             if(mb[i].handle == RADIO) gtk_check_menu_item_set_draw_as_radio(GTK_CHECK_MENU_ITEM(entry), True);
491           } else
492             entry = gtk_menu_item_new_with_label(msg);
493           gtk_signal_connect_object (GTK_OBJECT (entry), "activate", GTK_SIGNAL_FUNC(MenuSelect), (gpointer) (intptr_t) ((n<<16)+i));
494           g_signal_connect(entry, "button-release-event", G_CALLBACK (HelpEvent), (gpointer) mb[i].string );
495           if(mb[i].accel) {
496             guint accelerator_key;
497             GdkModifierType accelerator_mods;
498
499             gtk_accelerator_parse(mb[i].accel, &accelerator_key, &accelerator_mods);
500 #ifdef OSXAPP
501           if(accelerator_mods & GDK_CONTROL_MASK &&
502              accelerator_key != 'v' &&          // don't use Cmd+V as this is a OS text edit command
503              accelerator_key != 'c' &&           // and Cmd+C
504              accelerator_key != 'x' &&          // and CMD+X
505              accelerator_key != 'a'           // and CMD+A
506              ) {  // in OSX use Meta (Cmd) where Linux uses Ctrl
507               accelerator_mods &= ~GDK_CONTROL_MASK; // clear Ctrl flag
508               accelerator_mods |= GDK_META_MASK;     // set Meta flag
509                   } else if (accelerator_mods & GDK_CONTROL_MASK &&
510                                          accelerator_key == 'v' ||
511                                          accelerator_key == 'c' ||
512                                          accelerator_key == 'x' ||
513                                          accelerator_key == 'a'
514                                          ) { // For these conflicting commands, lets make them alt-cmd
515                           accelerator_mods &= ~GDK_CONTROL_MASK; // clear Ctrl flag
516                           accelerator_mods |= GDK_META_MASK;
517                           accelerator_mods |= GDK_MOD1_MASK;
518                   } 
519 #endif
520             gtk_widget_add_accelerator (GTK_WIDGET(entry), "activate",GtkAccelerators,
521                                         accelerator_key, accelerator_mods, GTK_ACCEL_VISIBLE);
522           }
523         } else entry = gtk_separator_menu_item_new();
524         gtk_widget_show(entry);
525         gtk_menu_append(GTK_MENU (menu), entry);
526 //CreateMenuItem(menu, opt->min & NO_GETTEXT ? msg : _(msg), (XtCallbackProc) ComboSelect, (n<<16)+i);
527         mb[i].handle = (void*) entry; // save item ID, for enabling / checkmarking
528 //      if(i==def) {
529 //          XtSetArg(arg, XtNpopupOnEntry, entry);
530 //          XtSetValues(menu, &arg, 1);
531 //      }
532       }
533       return menu;
534 }
535
536 Option *icsBox; // kludge to distinguish type-in callback from input-box callback
537
538 void
539 CursorAtEnd (Option *opt)
540 {
541     gtk_editable_set_position(opt->handle, -1);
542 }
543
544 static gboolean
545 ICSKeyEvent (int keyval)
546 {   // TODO_GTK: arrow-handling should really be integrated in type-in proc, and this should be a backe-end OK handler
547     switch(keyval) {
548       case GDK_Return: IcsKey(0); return TRUE;
549       case GDK_Up:     IcsKey(1); return TRUE;
550       case GDK_Down:  IcsKey(-1); return TRUE;
551       default: return FALSE;
552     }
553 }
554
555 int shiftState, controlState;
556
557 static gboolean
558 TypeInProc (GtkWidget *widget, GdkEventKey *event, gpointer gdata)
559 {   // This callback catches key presses on text-entries, and uses <Enter> and <Esc> as synonyms for dialog OK or Cancel
560     // *** kludge alert *** If a dialog does want some other action, like sending the line typed in the text-entry to an ICS,
561     // it should define an OK handler that does so, and returns FALSE to suppress the popdown.
562     int n = (intptr_t) gdata;
563     int dlg = n >> 16;
564     Option *opt;
565     n &= 0xFFFF;
566     opt = &dialogOptions[dlg][n];
567
568     if(opt == icsBox) return ICSKeyEvent(event->keyval); // Intercept ICS Input Box, which needs special treatment
569
570     shiftState = event->state & GDK_SHIFT_MASK;
571     controlState = event->state & GDK_CONTROL_MASK;
572     switch(event->keyval) {
573       case 'e':       return (controlState && IcsHist( 5, opt, dlg));
574       case 'h':       return (controlState && IcsHist( 8, opt, dlg));
575       case 'n':       return (controlState && IcsHist(14, opt, dlg));
576       case 'o':       return (controlState && IcsHist(15, opt, dlg));
577       case GDK_Tab:   IcsHist(10, opt, dlg); break;
578       case GDK_Up:     IcsHist(1, opt, dlg); break;
579       case GDK_Down:  IcsHist(-1, opt, dlg); break;
580       case GDK_Return:
581         if(GenericReadout(dialogOptions[dlg], -1)) PopDown(dlg);
582         break;
583       case GDK_Escape:
584         if(!IcsHist(33, opt, dlg)) PopDown(dlg);
585         break;
586       default:
587         return FALSE;
588     }
589     return TRUE;
590 }
591
592 void
593 HighlightText (Option *opt, int from, int to, Boolean highlight)
594 {
595 #   define INIT 0x8000
596     static GtkTextIter start, end;
597
598     if(!(opt->min & INIT)) {
599         opt->min |= INIT; // each memo its own init flag!
600         gtk_text_buffer_create_tag(opt->handle, "highlight", "background", "yellow", NULL);
601     }
602     gtk_text_buffer_get_iter_at_offset(opt->handle, &start, from);
603     gtk_text_buffer_get_iter_at_offset(opt->handle, &end, to);
604     if(highlight) gtk_text_buffer_apply_tag_by_name(opt->handle, "highlight", &start, &end);
605     else gtk_text_buffer_remove_tag_by_name(opt->handle, "highlight", &start, &end);
606 }
607
608 static char **names;
609 static int curFG, curBG, curAttr;
610 static GdkColor backgroundColor;
611
612 void
613 SetTextColor(char **cnames, int fg, int bg, int attr)
614 {
615     if(fg < 0) fg = 0; if(bg < 0) bg = 7;
616     names = cnames; curFG = fg; curBG = bg, curAttr = attr;
617     if(attr == -2) { // background color of ICS console.
618         gdk_color_parse(cnames[bg&7], &backgroundColor);
619         curAttr = 0;
620     }
621 }
622
623 void
624 AppendColorized (Option *opt, char *s, int count)
625 {
626     static GtkTextIter end;
627     static GtkTextTag *fgTags[8], *bgTags[8], *font, *bold, *normal, *attr = NULL;
628
629     if(!s) {
630         font = NULL;
631         return;
632     }
633
634     if(!font) {
635         font = gtk_text_buffer_create_tag(opt->handle, NULL, "font", appData.icsFont, NULL);
636         gtk_widget_modify_base(GTK_WIDGET(opt->textValue), GTK_STATE_NORMAL, &backgroundColor);
637     }
638
639     gtk_text_buffer_get_end_iter(GTK_TEXT_BUFFER(opt->handle), &end);
640
641     if(names) {
642       if(curAttr == 1) {
643         if(!bold) bold = gtk_text_buffer_create_tag(opt->handle, NULL, "weight", PANGO_WEIGHT_BOLD, NULL);
644         attr = bold;
645       } else {
646         if(!normal) normal = gtk_text_buffer_create_tag(opt->handle, NULL, "weight", PANGO_WEIGHT_NORMAL, NULL);
647         attr = normal;
648       }
649       if(!fgTags[curFG]) {
650         fgTags[curFG] = gtk_text_buffer_create_tag(opt->handle, NULL, "foreground", names[curFG], NULL);
651       }
652       if(!bgTags[curBG]) {
653         bgTags[curBG] = gtk_text_buffer_create_tag(opt->handle, NULL, "background", names[curBG], NULL);
654       }
655       gtk_text_buffer_insert_with_tags(opt->handle, &end, s, count, fgTags[curFG], bgTags[curBG], font, attr, NULL);
656     } else
657       gtk_text_buffer_insert_with_tags(opt->handle, &end, s, count, font, NULL);
658
659 }
660
661 void
662 Show (Option *opt, int hide)
663 {
664     if(hide) gtk_widget_hide(opt->handle);
665     else     gtk_widget_show(opt->handle);
666 }
667
668 int
669 ShiftKeys ()
670 {   // bassic primitive for determining if modifier keys are pressed
671     return 3*(shiftState != 0) + 0xC*(controlState != 0); // rely on what last mouse button press left us
672 }
673
674 static gboolean
675 GameListEvent(GtkWidget *widget, GdkEvent *event, gpointer gdata)
676 {
677     int n = (intptr_t) gdata;
678
679     if(n == 4) {
680         if(((GdkEventKey *) event)->keyval != GDK_Return) return FALSE;
681         SetFilter();
682         return TRUE;
683     }
684
685     if(event->type == GDK_KEY_PRESS) {
686         int ctrl = (((GdkEventKey *) event)->state & GDK_CONTROL_MASK) != 0;
687         switch(((GdkEventKey *) event)->keyval) {
688           case GDK_Up: GameListClicks(-1 - 2*ctrl); return TRUE;
689           case GDK_Left: GameListClicks(-1); return TRUE;
690           case GDK_Down: GameListClicks(1 + 2*ctrl); return TRUE;
691           case GDK_Right: GameListClicks(1); return TRUE;
692           case GDK_Prior: GameListClicks(-4); return TRUE;
693           case GDK_Next: GameListClicks(4); return TRUE;
694           case GDK_Home: GameListClicks(-2); return TRUE;
695           case GDK_End: GameListClicks(2); return TRUE;
696           case GDK_Return: GameListClicks(0); return TRUE;
697           default: return FALSE;
698         }
699     }
700     if(event->type != GDK_2BUTTON_PRESS || ((GdkEventButton *) event)->button != 1) return FALSE;
701     GameListClicks(0);
702     return TRUE;
703 }
704
705 static gboolean
706 MemoEvent(GtkWidget *widget, GdkEvent *event, gpointer gdata)
707 {   // handle mouse clicks on text widgets that need it
708     int w, h;
709     int button=10, f=1;
710     Option *memo = (Option *) gdata;
711     MemoCallback *userHandler = (MemoCallback *) memo->choice;
712     GdkEventButton *bevent = (GdkEventButton *) event;
713     GdkEventMotion *mevent = (GdkEventMotion *) event;
714     GtkTextIter start, end;
715     String val = NULL;
716     gboolean res;
717     gint index = 0, x, y;
718
719     switch(event->type) { // figure out what's up
720         case GDK_MOTION_NOTIFY:
721             f = 0;
722             w = mevent->x; h = mevent->y;
723             break;
724         case GDK_BUTTON_RELEASE:
725             f = -1; // release indicated by negative button numbers
726             w = bevent->x; h = bevent->y;
727             button = bevent->button;
728             break;
729         case GDK_BUTTON_PRESS:
730             w = bevent->x; h = bevent->y;
731             button = bevent->button;
732             shiftState = bevent->state & GDK_SHIFT_MASK;
733             controlState = bevent->state & GDK_CONTROL_MASK;
734             if(memo->type == Label) { // only clock widgets use this
735                 ((ButtonCallback*) memo->target)(button == 1 ? memo->value : -memo->value);
736                 return TRUE;
737             }
738             if(memo->value == 250 // kludge to recognize ICS Console and Chat panes
739              && gtk_text_buffer_get_selection_bounds(memo->handle, NULL, NULL) ) {
740                 gtk_text_buffer_get_selection_bounds(memo->handle, &start, &end); // only return selected text
741                 index = -1; // kludge to indicate something was selected
742             } else {
743                 if(abs(button) == 3 && gtk_text_buffer_get_selection_bounds(memo->handle, NULL, NULL)) return FALSE; // normal context menu
744 // GTK_TODO: is this really the most efficient way to get the character at the mouse cursor???
745                 gtk_text_view_window_to_buffer_coords(GTK_TEXT_VIEW(widget), GTK_TEXT_WINDOW_WIDGET, w, h, &x, &y);
746                 gtk_text_view_get_iter_at_location(GTK_TEXT_VIEW(widget), &start, x, y);
747                 gtk_text_buffer_place_cursor(memo->handle, &start);
748                 /* get cursor position into index */
749                 g_object_get(memo->handle, "cursor-position", &index, NULL);
750                 /* take complete contents */
751                 gtk_text_buffer_get_start_iter (memo->handle, &start);
752                 gtk_text_buffer_get_end_iter (memo->handle, &end);
753             }
754             /* get text from textbuffer */
755             val = gtk_text_buffer_get_text (memo->handle, &start, &end, FALSE);
756             if(strlen(val) != index) break; // if we clicked behind all text, fall through to do default action
757         default:
758             return FALSE; // should not happen
759     }
760     button *= f;
761     // hand click parameters as well as text & location to user
762     res = (userHandler) (memo, button, w, h, val, index);
763     if(val) g_free(val);
764     return res;
765 }
766
767 void
768 AddHandler (Option *opt, DialogClass dlg, int nr)
769 {
770     switch(nr) {
771       case 0: // history (now uses generic textview callback)
772       case 1: // comment (likewise)
773         break;
774       case 3: // input box
775         icsBox = opt;
776       case 2: // move type-in
777         g_signal_connect(opt->handle, "key-press-event", G_CALLBACK (TypeInProc), (gpointer) (dlg<<16 | (opt - dialogOptions[dlg])));
778         break;
779       case 5: // game list
780         g_signal_connect(opt->handle, "button-press-event", G_CALLBACK (GameListEvent), (gpointer) 0 );
781       case 4: // game-list filter
782         g_signal_connect(opt->handle, "key-press-event", G_CALLBACK (GameListEvent), (gpointer) (intptr_t) nr );
783         break;
784       case 6: // engine output (uses generic textview callback)
785         break;
786     }
787 }
788
789 //----------------------------Generic dialog --------------------------------------------
790
791 // cloned from Engine Settings dialog (and later merged with it)
792
793 GtkWidget *shells[NrOfDialogs];
794 DialogClass parents[NrOfDialogs];
795 WindowPlacement *wp[NrOfDialogs] = { // Beware! Order must correspond to DialogClass enum
796     NULL, &wpComment, &wpTags, &wpTextMenu, NULL, &wpConsole, &wpDualBoard, &wpMoveHistory, &wpGameList, &wpEngineOutput, &wpEvalGraph,
797     NULL, NULL, NULL, NULL, &wpMain
798 };
799
800 int
801 DialogExists (DialogClass n)
802 {   // accessor for use in back-end
803     return shells[n] != NULL;
804 }
805
806 void
807 RaiseWindow (DialogClass dlg)
808 {
809 #ifdef TODO_GTK
810     static XEvent xev;
811     Window root = RootWindow(xDisplay, DefaultScreen(xDisplay));
812     Atom atom = XInternAtom (xDisplay, "_NET_ACTIVE_WINDOW", False);
813
814     xev.xclient.type = ClientMessage;
815     xev.xclient.serial = 0;
816     xev.xclient.send_event = True;
817     xev.xclient.display = xDisplay;
818     xev.xclient.window = XtWindow(shells[dlg]);
819     xev.xclient.message_type = atom;
820     xev.xclient.format = 32;
821     xev.xclient.data.l[0] = 1;
822     xev.xclient.data.l[1] = CurrentTime;
823
824     XSendEvent (xDisplay,
825           root, False,static gboolean
826 MemoEvent(GtkWidget *widget, GdkEvent *event, gpointer gdata)
827
828           SubstructureRedirectMask | SubstructureNotifyMask,
829           &xev);
830
831     XFlush(xDisplay);
832     XSync(xDisplay, False);
833 #endif
834 }
835
836 int
837 PopDown (DialogClass n)
838 {
839     //Arg args[10];
840
841     if (!shellUp[n] || !shells[n]) return 0;
842     if(n && wp[n]) { // remember position
843         GetActualPlacement(shells[n], wp[n]);
844     }
845
846     gtk_widget_hide(shells[n]);
847     shellUp[n]--; // count rather than clear
848
849     if(n == 0 || n >= PromoDlg) {
850         gtk_widget_destroy(shells[n]);
851         shells[n] = NULL;
852     }
853
854     if(marked[n]) {
855         MarkMenuItem(marked[n], False);
856         marked[n] = NULL;
857     }
858
859     if(!n) currentCps = NULL; // if an Engine Settings dialog was up, we must be popping it down now
860     currentOption = dialogOptions[TransientDlg]; // just in case a transient dialog was up (to allow its check and combo callbacks to work)
861 #ifdef TODO_GTK
862     RaiseWindow(parents[n]); // automatic in GTK?
863     if(parents[n] == BoardWindow) XtSetKeyboardFocus(shellWidget, formWidget); // also automatic???
864 #endif
865     return 1;
866 }
867
868 /* GTK callback used when OK/cancel clicked in genericpopup for non-modal dialog */
869 gboolean GenericPopDown(w, resptype, gdata)
870      GtkWidget *w;
871      GtkResponseType  resptype;
872      gpointer  gdata;
873 {
874     DialogClass dlg = (intptr_t) gdata; /* dialog number dlgnr */
875     GtkWidget *sh = shells[dlg];
876
877     currentOption = dialogOptions[dlg];
878
879 #ifdef TODO_GTK
880 // I guess BrowserDlg will be abandoned, as GTK has a better browser of its own
881     if(shellUp[BrowserDlg] && dlg != BrowserDlg || dialogError) return True; // prevent closing dialog when it has an open file-browse daughter
882 #else
883     if(browserUp || dialogError && dlg != FatalDlg || dlg == MasterDlg && shellUp[TransientDlg])
884         return True; // prevent closing dialog when it has an open file-browse, transient or error-popup daughter
885 #endif
886     shells[dlg] = w; // make sure we pop down the right one in case of multiple instances
887
888     /* OK pressed */
889     if (resptype == GTK_RESPONSE_ACCEPT) {
890         if (GenericReadout(currentOption, -1)) PopDown(dlg);
891         return TRUE;
892     } else
893     /* cancel pressed */
894     {
895         if(dlg == BoardWindow) ExitEvent(0);
896         if(dlg == FatalDlg) ErrorOK(1); else PopDown(dlg);
897     }
898     shells[dlg] = sh; // restore
899     return TRUE;
900 }
901
902 gboolean PopDownProxy(w, gdata)
903      GtkWidget *w;
904      gpointer  gdata;
905 {
906     GtkResponseType resp = GTK_RESPONSE_ACCEPT;
907     int dlg = (intptr_t) gdata;
908     if(dlg >= 3000) dlg -= 3000, resp = GTK_RESPONSE_REJECT;
909     return GenericPopDown(gtk_widget_get_toplevel(w), resp, (gpointer)(intptr_t)dlg);
910 }
911
912 int AppendText(Option *opt, char *s)
913 {
914     char *v;
915     int len;
916     GtkTextIter end;
917
918     GetWidgetTextGTK(opt->handle, &v);
919     len = strlen(v);
920     g_free(v);
921     gtk_text_buffer_get_end_iter(GTK_TEXT_BUFFER(opt->handle), &end);
922     gtk_text_buffer_insert(opt->handle, &end, s, -1);
923
924     return len;
925 }
926
927 void
928 SetColor (char *colorName, Option *box)
929 {       // sets the color of a widget
930     GdkColor color;
931
932     /* set the colour of the colour button to the colour that will be used */
933     gdk_color_parse( colorName, &color );
934     gtk_widget_modify_bg ( GTK_WIDGET(box->handle), GTK_STATE_NORMAL, &color );
935 }
936
937 #ifdef TODO_GTK
938 void
939 ColorChanged (Widget w, XtPointer data, XEvent *event, Boolean *b)
940 {   // for detecting a typed change in color
941     char buf[10];
942     if ( (XLookupString(&(event->xkey), buf, 2, NULL, NULL) == 1) && *buf == '\r' )
943         RefreshColor((int)(intptr_t) data, 0);
944 }
945 #endif
946
947 static void
948 ExposeDraw (Option *graph, GdkEventExpose *eevent)
949 {
950     int w = eevent->area.width;
951     cairo_t *cr;
952     if(eevent->area.x + w > graph->max) w--; // cut off fudge pixel
953     cr = gdk_cairo_create(((GtkWidget *) (graph->handle))->window);
954     cairo_set_source_surface(cr, (cairo_surface_t *) graph->choice, 0, 0);
955 //cairo_set_source_rgb(cr, 1, 0, 0);
956     cairo_set_antialias(cr, CAIRO_ANTIALIAS_NONE);
957     cairo_rectangle(cr, eevent->area.x, eevent->area.y, w, eevent->area.height);
958     cairo_fill(cr);
959     cairo_destroy(cr);
960 }
961
962 static void
963 GraphEventProc(GtkWidget *widget, GdkEvent *event, gpointer gdata)
964 {   // handle expose and mouse events on Graph widget
965     int w, h;
966     int button=10, f=1, sizing=0;
967     Option *opt, *graph = (Option *) gdata;
968     PointerCallback *userHandler = graph->target;
969     GdkEventExpose *eevent = (GdkEventExpose *) event;
970     GdkEventButton *bevent = (GdkEventButton *) event;
971     GdkEventMotion *mevent = (GdkEventMotion *) event;
972     GdkEventScroll *sevent = (GdkEventScroll *) event;
973     GtkAllocation a;
974
975 //    if (!XtIsRealized(widget)) return;
976
977     switch(event->type) {
978         case GDK_EXPOSE: // make handling of expose events generic, just copying from memory buffer (->choice) to display (->textValue)
979             /* Get window size */
980             gtk_widget_get_allocation(widget, &a);
981             w = a.width; h = a.height;
982 //printf("expose %dx%d @ (%d,%d): %dx%d @(%d,%d)\n", w, h, a.x, a.y, eevent->area.width, eevent->area.height, eevent->area.x, eevent->area.y);
983 #ifdef TODO_GTK
984             j = 0;
985             XtSetArg(args[j], XtNwidth, &w); j++;
986             XtSetArg(args[j], XtNheight, &h); j++;
987             XtGetValues(widget, args, j);
988 #endif
989             if(w < graph->max || w > graph->max + 1 || h != graph->value) { // use width fudge of 1 pixel
990                 if(eevent->count >= 0) { // suppress sizing on expose for ordered redraw in response to sizing.
991                     sizing = 1;
992                     graph->max = w; graph->value = h; // note: old values are kept if we we don't exceed width fudge
993                 }
994             } else w = graph->max;
995             if(sizing && eevent->count > 0) { graph->max = 0; return; } // don't bother if further exposure is pending during resize
996 #ifdef TODO_GTK
997             if(!graph->textValue || sizing) { // create surfaces of new size for display widget
998                 if(graph->textValue) cairo_surface_destroy((cairo_surface_t *)graph->textValue);
999                 graph->textValue = (char*) cairo_xlib_surface_create(xDisplay, XtWindow(widget), DefaultVisual(xDisplay, 0), w, h);
1000             }
1001 #endif
1002             if(sizing) { // the memory buffer was already created in GenericPopup(),
1003                          // to give drawing routines opportunity to use it before first expose event
1004                          // (which are only processed when main gets to the event loop, so after all init!)
1005                          // so only change when size is no longer good
1006 //              NewCanvas(graph);
1007                 graph->min |= REPLACE; // defer making new canvas
1008                 break;
1009             }
1010             ExposeDraw(graph, eevent);
1011         default:
1012             return;
1013         case GDK_SCROLL:
1014             if(sevent->direction == GDK_SCROLL_UP) button = 4;
1015             if(sevent->direction == GDK_SCROLL_DOWN) button = 5;
1016             break;
1017         case GDK_MOTION_NOTIFY:
1018             f = 0;
1019             w = mevent->x; h = mevent->y;
1020             break;
1021         case GDK_BUTTON_RELEASE:
1022             f = -1; // release indicated by negative button numbers
1023         case GDK_BUTTON_PRESS:
1024             w = bevent->x; h = bevent->y;
1025             button = bevent->button;
1026             shiftState = bevent->state & GDK_SHIFT_MASK;
1027             controlState = bevent->state & GDK_CONTROL_MASK;
1028     }
1029     button *= f;
1030
1031     opt = userHandler(button, w, h);
1032 #ifdef TODO_GTK
1033     if(opt) { // user callback specifies a context menu; pop it up
1034         XUngrabPointer(xDisplay, CurrentTime);
1035         XtCallActionProc(widget, "XawPositionSimpleMenu", event, &(opt->name), 1);
1036         XtPopupSpringLoaded(opt->handle);
1037     }
1038     XSync(xDisplay, False);
1039 #endif
1040 }
1041
1042 void
1043 GraphExpose (Option *opt, int x, int y, int w, int h)
1044 {
1045 #if 0
1046   GdkRectangle r;
1047   r.x = x; r.y = y; r.width = w; r.height = h;
1048   gdk_window_invalidate_rect(((GtkWidget *)(opt->handle))->window, &r, FALSE);
1049 #endif
1050   GdkEventExpose e;
1051   if(!opt->handle) return;
1052   e.area.x = x; e.area.y = y; e.area.width = w; e.area.height = h; e.count = -1; e.type = GDK_EXPOSE; // count = -1: kludge to suppress sizing
1053   ExposeDraw(opt, &e); // fake expose event
1054 }
1055
1056 void GenericCallback(GtkWidget *widget, gpointer gdata)
1057 {
1058     const gchar *name;
1059     char buf[MSG_SIZ];
1060     int data = (intptr_t) gdata;
1061     DialogClass dlg;
1062 #ifdef TODO_GTK
1063     GtkWidget *sh = XtParent(XtParent(XtParent(w))), *oldSh;
1064 #else
1065     GtkWidget *sh, *oldSh;
1066 #endif
1067
1068     currentOption = dialogOptions[dlg=data>>16]; data &= 0xFFFF;
1069 #ifndef TODO_GTK
1070     sh = shells[dlg]; // make following line a no-op, as we haven't found out what the real shell is yet (breaks multiple popups of same type!)
1071 #endif
1072     oldSh = shells[dlg]; shells[dlg] = sh; // bow to reality
1073
1074     if (data == 30000) { // cancel
1075         PopDown(dlg);
1076     } else
1077     if (data == 30001) { // save buttons imply OK
1078         if(GenericReadout(currentOption, -1)) PopDown(dlg); // calls OK-proc after full readout, but no popdown if it returns false
1079     } else
1080
1081     if(currentCps) {
1082         name = gtk_button_get_label (GTK_BUTTON(widget));
1083         if(currentOption[data].type == SaveButton) GenericReadout(currentOption, -1);
1084         snprintf(buf, MSG_SIZ,  "option %s\n", name);
1085         SendToProgram(buf, currentCps);
1086     } else ((ButtonCallback*) currentOption[data].target)(data);
1087
1088     shells[dlg] = oldSh; // in case of multiple instances, restore previous (as this one could be popped down now)
1089 }
1090
1091 void BrowseGTK(GtkWidget *widget, gpointer gdata)
1092 {
1093     GtkWidget *entry;
1094     GtkWidget *dialog;
1095     GtkFileFilter *gtkfilter;
1096     GtkFileFilter *gtkfilter_all;
1097     int opt_i = (intptr_t) gdata;
1098     GtkFileChooserAction fc_action;
1099
1100     gtkfilter     = gtk_file_filter_new();
1101     gtkfilter_all = gtk_file_filter_new();
1102
1103     char fileext[MSG_SIZ], *filter = currentOption[opt_i].textValue;
1104
1105     StartDir(filter, NULL); // change to start directory for this file type
1106
1107     /* select file or folder depending on option_type */
1108     if (currentOption[opt_i].type == PathName)
1109         fc_action = GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER;
1110     else
1111         fc_action = GTK_FILE_CHOOSER_ACTION_OPEN;
1112
1113     dialog = gtk_file_chooser_dialog_new ("Open File",
1114                       NULL,
1115                       fc_action,
1116                       GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
1117                       GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT,
1118                       NULL);
1119
1120     /* one filter to show everything */
1121     gtk_file_filter_add_pattern(gtkfilter_all, "*");
1122     gtk_file_filter_set_name   (gtkfilter_all, "All Files");
1123     gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog),gtkfilter_all);
1124
1125     /* filter for specific filetypes e.g. pgn or fen */
1126     if (currentOption[opt_i].textValue != NULL)
1127       {
1128         char *q, *p = currentOption[opt_i].textValue;
1129         gtk_file_filter_set_name (gtkfilter, p);
1130         while(*p) {
1131           snprintf(fileext, MSG_SIZ, "*%s", p);
1132           while(*p) if(*p++ == ' ')  break;
1133           for(q=fileext; *q; q++) if(*q == ' ') { *q = NULLCHAR; break; }
1134           gtk_file_filter_add_pattern(gtkfilter, fileext);
1135         }
1136         gtk_file_chooser_add_filter (GTK_FILE_CHOOSER(dialog),gtkfilter);
1137         /* activate filter */
1138         gtk_file_chooser_set_filter (GTK_FILE_CHOOSER(dialog),gtkfilter);
1139       }
1140     else
1141       gtk_file_chooser_set_filter (GTK_FILE_CHOOSER(dialog),gtkfilter_all);
1142
1143     if (gtk_dialog_run (GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT)
1144       {
1145         char *filename;
1146         filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog));
1147         entry = currentOption[opt_i].handle;
1148         gtk_entry_set_text (GTK_ENTRY (entry), filename);
1149         StartDir(filter, filename); // back to original, and remember this one
1150         g_free (filename);
1151       }
1152     else StartDir(filter, ""); // change back to original directory
1153     gtk_widget_destroy (dialog);
1154     dialog = NULL;
1155 }
1156
1157 gboolean
1158 ListCallback (GtkWidget *widget, GdkEventButton *event, gpointer gdata)
1159 {
1160     int n = (intptr_t) gdata & 0xFFFF;
1161     int dlg = (intptr_t) gdata >> 16;
1162     Option *opt = dialogOptions[dlg] + n;
1163
1164     if(event->type != GDK_2BUTTON_PRESS || event->button != 1) return FALSE;
1165     ((ListBoxCallback*) opt->textValue)(n, SelectedListBoxItem(opt));
1166     return TRUE;
1167 }
1168
1169 #ifdef TODO_GTK
1170 // This is needed for color pickers?
1171 static char *oneLiner  =
1172    "<Key>Return: redraw-display() \n \
1173     <Key>Tab: TabProc() \n ";
1174 #endif
1175
1176 #ifdef TODO_GTK
1177 static void
1178 SqueezeIntoBox (Option *opt, int nr, int width)
1179 {   // size buttons in bar to fit, clipping button names where necessary
1180     int i, wtot = 0;
1181     Dimension widths[20], oldWidths[20];
1182     Arg arg;
1183     for(i=1; i<nr; i++) {
1184         XtSetArg(arg, XtNwidth, &widths[i]);
1185         XtGetValues(opt[i].handle, &arg, 1);
1186         wtot +=  oldWidths[i] = widths[i];
1187     }
1188     opt->min = wtot;
1189     if(width <= 0) return;
1190     while(wtot > width) {
1191         int wmax=0, imax=0;
1192         for(i=1; i<nr; i++) if(widths[i] > wmax) wmax = widths[imax=i];
1193         widths[imax]--;
1194         wtot--;
1195     }
1196     for(i=1; i<nr; i++) if(widths[i] != oldWidths[i]) {
1197         XtSetArg(arg, XtNwidth, widths[i]);
1198         XtSetValues(opt[i].handle, &arg, 1);
1199     }
1200     opt->min = wtot;
1201 }
1202 #endif
1203
1204 #ifdef TODO_GTK
1205 int
1206 SetPositionAndSize (Arg *args, Widget leftNeigbor, Widget topNeigbor, int b, int w, int h, int chaining)
1207 {   // sizing and positioning most widgets have in common
1208     int j = 0;
1209     // first position the widget w.r.t. earlier ones
1210     if(chaining & 1) { // same row: position w.r.t. last (on current row) and lastrow
1211         XtSetArg(args[j], XtNfromVert, topNeigbor); j++;
1212         XtSetArg(args[j], XtNfromHoriz, leftNeigbor); j++;
1213     } else // otherwise it goes at left margin (which is default), below the previous element
1214         XtSetArg(args[j], XtNfromVert, leftNeigbor),  j++;
1215     // arrange chaining ('2'-bit indicates top and bottom chain the same)
1216     if((chaining & 14) == 6) XtSetArg(args[j], XtNtop,    XtChainBottom), j++;
1217     if((chaining & 14) == 10) XtSetArg(args[j], XtNbottom, XtChainTop ), j++;
1218     if(chaining & 4) XtSetArg(args[j], XtNbottom, XtChainBottom ), j++;
1219     if(chaining & 8) XtSetArg(args[j], XtNtop,    XtChainTop), j++;
1220     if(chaining & 0x10) XtSetArg(args[j], XtNright, XtChainRight), j++;
1221     if(chaining & 0x20) XtSetArg(args[j], XtNleft,  XtChainRight), j++;
1222     if(chaining & 0x40) XtSetArg(args[j], XtNright, XtChainLeft ), j++;
1223     if(chaining & 0x80) XtSetArg(args[j], XtNleft,  XtChainLeft ), j++;
1224     // set size (if given)
1225     if(w) XtSetArg(args[j], XtNwidth, w), j++;
1226     if(h) XtSetArg(args[j], XtNheight, h),  j++;
1227     // color
1228     if(!appData.monoMode) {
1229         if(!b && appData.dialogColor[0]) XtSetArg(args[j], XtNbackground, dialogColor),  j++;
1230         if(b == 3 && appData.buttonColor[0]) XtSetArg(args[j], XtNbackground, buttonColor),  j++;
1231     }
1232     if(b == 3) b = 1;
1233     // border
1234     XtSetArg(args[j], XtNborderWidth, b);  j++;
1235     return j;
1236 }
1237 #endif
1238
1239 static int
1240 TableWidth (Option *opt)
1241 {   // Hideous work-around! If the table is 3 columns, but 2 & 3 are always occupied together, the fixing of the width of column 1 does not work
1242     while(opt->type != EndMark && opt->type != Break)
1243         if(opt->type == FileName || opt->type == PathName || opt++->type == BarBegin) return 3; // This table needs browse button
1244     return 2; // no browse button;
1245 }
1246
1247 static int
1248 SameRow (Option *opt)
1249 {
1250     return (opt->min & SAME_ROW && (opt->type == Button || opt->type == SaveButton || opt->type == Label
1251                                  || opt->type == ListBox || opt->type == BoxBegin || opt->type == Icon || opt->type == Graph));
1252 }
1253
1254 static void
1255 Pack (GtkWidget *hbox, GtkWidget *table, GtkWidget *entry, int left, int right, int top, GtkAttachOptions vExpand)
1256 {
1257     if(hbox) gtk_box_pack_start(GTK_BOX (hbox), entry, TRUE, TRUE, 0);
1258     else     gtk_table_attach(GTK_TABLE(table), entry, left, right, top, top+1,
1259                                 GTK_FILL | GTK_EXPAND, GTK_FILL | vExpand, 2, 1);
1260 }
1261
1262 int
1263 GenericPopUp (Option *option, char *title, DialogClass dlgNr, DialogClass parent, int modal, int topLevel)
1264 {
1265     GtkWidget *dialog = NULL;
1266     gint       w;
1267     GtkWidget *label;
1268     GtkWidget *box;
1269     GtkWidget *checkbutton;
1270     GtkWidget *entry;
1271     GtkWidget *oldHbox = NULL, *hbox = NULL;
1272     GtkWidget *pane = NULL;
1273     GtkWidget *button;
1274     GtkWidget *table;
1275     GtkWidget *spinner;
1276     GtkAdjustment *spinner_adj;
1277     GtkWidget *combobox;
1278     GtkWidget *textview;
1279     GtkTextBuffer *textbuffer;
1280     GdkColor color;
1281     GtkWidget *actionarea;
1282     GtkWidget *sw;
1283     GtkWidget *list;
1284     GtkWidget *graph;
1285     GtkWidget *menuButton;
1286     GtkWidget *menuBar = NULL;
1287     GtkWidget *menu;
1288
1289     int i, j, arraysize, left, top, height=999, width=1, boxStart=0, breakType = 0, r;
1290     char def[MSG_SIZ], *msg, engineDlg = (currentCps != NULL && dlgNr != BrowserDlg);
1291     gboolean expandable = FALSE;
1292
1293     if(dlgNr < PromoDlg && shellUp[dlgNr]) return 0; // already up
1294
1295     if(dlgNr && dlgNr < PromoDlg && shells[dlgNr]) { // reusable, and used before (but popped down)
1296         gtk_widget_show(shells[dlgNr]);
1297         shellUp[dlgNr] = True;
1298         if(wp[dlgNr]) gtk_window_move(GTK_WINDOW(shells[dlgNr]), wp[dlgNr]->x, wp[dlgNr]->y);
1299         return 0;
1300     }
1301     if(dlgNr == TransientDlg && parent == BoardWindow && shellUp[MasterDlg]) parent = MasterDlg; // MasterDlg can always take role of main window
1302
1303     dialogOptions[dlgNr] = option; // make available to callback
1304     // post currentOption globally, so Spin and Combo callbacks can already use it
1305     // WARNING: this kludge does not work for persistent dialogs, so that these cannot have spin or combo controls!
1306     currentOption = option;
1307
1308     if(engineDlg) { // Settings popup for engine: format through heuristic
1309         int n = currentCps->nrOptions;
1310 //        if(n > 50) width = 4; else if(n>24) width = 2; else width = 1;
1311         width = n / 20 + 1;
1312         height = n / width + 1;
1313 if(appData.debugMode) printf("n=%d, h=%d, w=%d\n",n,height,width);
1314 //      if(n && (currentOption[n-1].type == Button || currentOption[n-1].type == SaveButton)) currentOption[n].min = SAME_ROW; // OK on same line
1315         currentOption[n].type = EndMark; currentOption[n].target = NULL; // delimit list by callback-less end mark
1316     }
1317
1318     parents[dlgNr] = parent;
1319 #ifdef TODO_GTK
1320     shells[BoardWindow] = shellWidget; parents[dlgNr] = parent;
1321
1322     if(dlgNr == BoardWindow) dialog = shellWidget; else
1323     dialog =
1324       XtCreatePopupShell(title, !top || !appData.topLevel ? transientShellWidgetClass : topLevelShellWidgetClass,
1325                                                            shells[parent], args, i);
1326 #endif
1327
1328     if(topLevel)
1329       {
1330         dialog = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1331         gtk_window_set_title(GTK_WINDOW(dialog), title);
1332         box = gtk_vbox_new(FALSE,0);
1333         gtk_container_add (GTK_CONTAINER (dialog), box);
1334       }
1335     else
1336       {
1337         dialog = gtk_dialog_new_with_buttons( title,
1338                                               GTK_WINDOW(shells[parent]),
1339                                               GTK_DIALOG_DESTROY_WITH_PARENT | GTK_DIALOG_NO_SEPARATOR |
1340                                               (modal ? GTK_DIALOG_MODAL : 0),
1341                                               GTK_STOCK_OK, GTK_RESPONSE_ACCEPT,
1342                                               GTK_STOCK_CANCEL, GTK_RESPONSE_REJECT,
1343                                               NULL );
1344         box = gtk_dialog_get_content_area( GTK_DIALOG( dialog ) );
1345       }
1346
1347     shells[dlgNr] = dialog;
1348 //    gtk_box_set_spacing(GTK_BOX(box), 5);
1349
1350     arraysize = 0;
1351     for (i=0;option[i].type != EndMark;i++) {
1352         arraysize++;
1353     }
1354
1355     table = gtk_table_new(arraysize, r=TableWidth(option), FALSE);
1356     left = 0;
1357     top = -1;
1358
1359     for (i=0;option[i].type != EndMark;i++) {
1360         if(option[i].type == Skip) continue;
1361         top++;
1362 //printf("option =%2d, top =%2d\n", i, top);
1363         if (top >= height || breakType) {
1364             gtk_table_resize(GTK_TABLE(table), top - (breakType != 0), r);
1365             if(!pane) { // multi-column: put tables in intermediate hbox
1366                 if(breakType & SAME_ROW || engineDlg)
1367                     pane =  gtk_hbox_new (FALSE, 0);
1368                 else
1369                     pane =  gtk_vbox_new (FALSE, 0);
1370                 gtk_box_set_spacing(GTK_BOX(pane), 5 + 5*breakType);
1371                 gtk_box_pack_start (GTK_BOX (/*GTK_DIALOG (dialog)->vbox*/box), pane, TRUE, TRUE, 0);
1372             }
1373             gtk_box_pack_start (GTK_BOX (pane), table, expandable, TRUE, 0);
1374             table = gtk_table_new(arraysize - i, r=TableWidth(option + i), FALSE);
1375             top = breakType = 0; expandable = FALSE;
1376         }
1377         if(!SameRow(&option[i])) {
1378             if(SameRow(&option[i+1]) || topLevel && option[i].type == Button && option[i+1].type == EndMark && option[i+1].min & SAME_ROW) {
1379                 GtkAttachOptions x = GTK_FILL;
1380                 // make sure hbox is always available when we have more options on same row
1381                 hbox = gtk_hbox_new (option[i].type == Button && option[i].textValue || option[i].type == Graph, 0);
1382                 if(!currentCps && option[i].value > 80) x |= GTK_EXPAND; // only vertically extended widgets should size vertically
1383                 if (strcmp(option[i].name, "") == 0 || option[i].type == Label || option[i].type == Button)
1384                     // for Label and Button name is contained inside option
1385                     gtk_table_attach(GTK_TABLE(table), hbox, left, left+r, top, top+1, GTK_FILL | GTK_EXPAND, x, 2, 1);
1386                 else
1387                     gtk_table_attach(GTK_TABLE(table), hbox, left+1, left+r, top, top+1, GTK_FILL | GTK_EXPAND, x, 2, 1);
1388             } else hbox = NULL; //and also make sure no hbox exists if only singl option on row
1389         } else top--;
1390         switch(option[i].type) {
1391           case Fractional:
1392             snprintf(def, MSG_SIZ,  "%.2f", *(float*)option[i].target);
1393             option[i].value = *(float*)option[i].target;
1394             goto tBox;
1395           case Spin:
1396             if(!currentCps) option[i].value = *(int*)option[i].target;
1397             snprintf(def, MSG_SIZ,  "%d", option[i].value);
1398           case TextBox:
1399           case FileName:
1400           case PathName:
1401           tBox:
1402             label = gtk_label_new(_(option[i].name));
1403             /* Left Justify */
1404             gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);
1405
1406             /* width */
1407             w = option[i].type == Spin || option[i].type == Fractional ? 70 : option[i].max ? option[i].max : 205;
1408             if(option[i].type == FileName || option[i].type == PathName) w -= 55;
1409
1410             if (option[i].type==TextBox && option[i].value > 80){
1411                 GtkTextIter iter;
1412                 expandable = TRUE;
1413                 textview = gtk_text_view_new();
1414                 gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(textview), option[i].min & T_WRAP ? GTK_WRAP_WORD : GTK_WRAP_NONE);
1415 #ifdef TODO_GTK
1416                 if(option[i].min & T_FILL)  { XtSetArg(args[j], XtNautoFill, True);  j++; }
1417                 if(option[i].min & T_TOP)   { XtSetArg(args[j], XtNtop, XtChainTop); j++;
1418 #endif
1419                 /* add textview to scrolled window so we have vertical scroll bar */
1420                 sw = gtk_scrolled_window_new(NULL, NULL);
1421                 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(sw),
1422                                                option[i].min & T_HSCRL ? GTK_POLICY_ALWAYS : GTK_POLICY_AUTOMATIC,
1423                                                option[i].min & T_VSCRL ? GTK_POLICY_ALWAYS : GTK_POLICY_NEVER);
1424                 gtk_container_add(GTK_CONTAINER(sw), textview);
1425                 gtk_widget_set_size_request(GTK_WIDGET(sw), w, -1);
1426                 gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(sw), GTK_SHADOW_OUT);
1427
1428                 textbuffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview));
1429                 /* check if label is empty */
1430                 if (strcmp(option[i].name,"") != 0) {
1431                     gtk_table_attach(GTK_TABLE(table), label, left, left+1, top, top+1, GTK_FILL, GTK_FILL, 2, 1);
1432                     Pack(hbox, table, sw, left+1, left+r, top, 0);
1433                 }
1434                 else {
1435                     /* no label so let textview occupy all columns */
1436                     Pack(hbox, table, sw, left, left+r, top, GTK_EXPAND);
1437                 }
1438                 SetWidgetFont(textview, option[i].font);
1439                 if ( *(char**)option[i].target != NULL )
1440                     gtk_text_buffer_set_text (textbuffer, *(char**)option[i].target, -1);
1441                 else
1442                     gtk_text_buffer_set_text (textbuffer, "", -1);
1443                 option[i].handle = (void*)textbuffer;
1444                 option[i].textValue = (char*)textview;
1445                 gtk_text_buffer_get_iter_at_offset(textbuffer, &iter, -1);
1446                 gtk_text_buffer_create_mark(textbuffer, "scrollmark", &iter, FALSE); // permanent mark
1447                 if(option[i].choice) { // textviews can request a handler for mouse events in the choice field
1448                     g_signal_connect(textview, "button-press-event", G_CALLBACK (MemoEvent), (gpointer) &option[i] );
1449                     g_signal_connect(textview, "button-release-event", G_CALLBACK (MemoEvent), (gpointer) &option[i] );
1450                     g_signal_connect(textview, "motion-notify-event", G_CALLBACK (MemoEvent), (gpointer) &option[i] );
1451                 }
1452                 break;
1453             }
1454
1455             entry = gtk_entry_new();
1456
1457             if (option[i].type==Spin || option[i].type==Fractional)
1458                 gtk_entry_set_text (GTK_ENTRY (entry), def);
1459             else if (currentCps)
1460                 gtk_entry_set_text (GTK_ENTRY (entry), option[i].textValue);
1461             else if ( *(char**)option[i].target != NULL )
1462                 gtk_entry_set_text (GTK_ENTRY (entry), *(char**)option[i].target);
1463
1464             //gtk_entry_set_width_chars (GTK_ENTRY (entry), 18);
1465             gtk_entry_set_max_length (GTK_ENTRY (entry), w);
1466
1467             // left, right, top, bottom
1468             if (strcmp(option[i].name, "") != 0) {
1469                 button = gtk_event_box_new();
1470                 gtk_container_add(GTK_CONTAINER(button), label);
1471                 label = button;
1472                 gtk_widget_add_events(GTK_WIDGET(label), GDK_BUTTON_PRESS_MASK);
1473                 g_signal_connect(label, "button-press-event", G_CALLBACK(HelpEvent), (gpointer) option[i].name);
1474                 gtk_widget_set_sensitive(label, TRUE);
1475                 gtk_table_attach(GTK_TABLE(table), label, left, left+1, top, top+1, GTK_FILL, GTK_FILL, 2, 1); // leading names do not expand
1476             }
1477
1478             if (option[i].type == Spin) {
1479                 spinner_adj = (GtkAdjustment *) gtk_adjustment_new (option[i].value, option[i].min, option[i].max, 1.0, 0.0, 0.0);
1480                 spinner = gtk_spin_button_new (spinner_adj, 1.0, 0);
1481                 gtk_table_attach(GTK_TABLE(table), spinner, left+1, left+r, top, top+1, GTK_FILL | GTK_EXPAND, GTK_FILL, 2, 1);
1482                 option[i].handle = (void*)spinner;
1483             }
1484             else if (option[i].type == FileName || option[i].type == PathName) {
1485                 gtk_table_attach(GTK_TABLE(table), entry, left+1, left+2, top, top+1, GTK_FILL | GTK_EXPAND, GTK_FILL, 2, 1);
1486                 button = gtk_button_new_with_label (_("Browse"));
1487                 gtk_table_attach(GTK_TABLE(table), button, left+2, left+r, top, top+1, GTK_FILL, GTK_FILL, 2, 1); // Browse button does not expand
1488                 g_signal_connect (button, "clicked", G_CALLBACK (BrowseGTK), (gpointer)(intptr_t) i);
1489                 option[i].handle = (void*)entry;
1490             }
1491             else {
1492                 Pack(hbox, table, entry, left + (strcmp(option[i].name, "") != 0), left+r, top, 0);
1493                 option[i].handle = (void*)entry;
1494             }
1495             break;
1496           case CheckBox:
1497             checkbutton = gtk_check_button_new_with_label(_(option[i].name));
1498             g_signal_connect(checkbutton, "button-press-event", G_CALLBACK (HelpEvent), (gpointer) option[i].name );
1499             if(!currentCps) option[i].value = *(Boolean*)option[i].target;
1500             gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbutton), option[i].value);
1501             gtk_table_attach(GTK_TABLE(table), checkbutton, left, left+r, top, top+1, GTK_FILL | GTK_EXPAND, GTK_FILL, 2, 0);
1502             option[i].handle = (void *)checkbutton;
1503             break;
1504           case Icon:
1505             option[i].handle = (void *) (label = gtk_image_new_from_pixbuf(NULL));
1506             gtk_widget_set_size_request(label, option[i].max ? option[i].max : -1, -1);
1507             Pack(hbox, table, label, left, left+2, top, 0);
1508             break;
1509           case Label:
1510             option[i].handle = (void *) (label = gtk_label_new(_(option[i].name)));
1511             /* Left Justify */
1512             gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);
1513             SetWidgetFont(label, option[i].font);
1514             if(option[i].min & BORDER) {
1515                 GtkWidget *frame = gtk_frame_new(NULL);
1516                 gtk_container_add(GTK_CONTAINER(frame), label);
1517                 label = frame;
1518             }
1519             gtk_widget_set_size_request(label, option[i].max ? option[i].max : -1, -1);
1520             if(option[i].target || dlgNr != ErrorDlg && option[i].name) { // allow user to specify event handler for button presses
1521                 button = gtk_event_box_new();
1522                 gtk_container_add(GTK_CONTAINER(button), label);
1523                 label = button;
1524                 gtk_widget_add_events(GTK_WIDGET(label), GDK_BUTTON_PRESS_MASK);
1525                 if(option[i].target)
1526                      g_signal_connect(label, "button-press-event", G_CALLBACK(MemoEvent), (gpointer) &option[i]);
1527                 else g_signal_connect(label, "button-press-event", G_CALLBACK(HelpEvent), (gpointer) option[i].name);
1528                 gtk_widget_set_sensitive(label, TRUE);
1529             }
1530             Pack(hbox, table, label, left, left+r, top, 0);
1531             break;
1532           case SaveButton:
1533           case Button:
1534             if(!strcmp(option[i].name, "fontsel")) {
1535                 option[i].handle = (void *) (fbutton = gtk_font_button_new());
1536                 Pack(hbox, table, fbutton, left, left+r, top, 0);
1537                 break;
1538             }
1539             button = gtk_button_new_with_label (_(option[i].name));
1540             SetWidgetFont(gtk_bin_get_child(GTK_BIN(button)), option[i].font);
1541
1542             /* set button color on view board dialog */
1543             if(option[i].choice && ((char*)option[i].choice)[0] == '#' && !currentCps) {
1544                 gdk_color_parse( *(char**) option[i-1].target, &color );
1545                 gtk_widget_modify_bg ( GTK_WIDGET(button), GTK_STATE_NORMAL, &color );
1546             }
1547
1548             /* set button color on new variant dialog */
1549             if(option[i].textValue) {
1550                 static char *b = "Bold";
1551                 char *v, *p = NULL, n = option[i].value;
1552                 if(n >= 0) v = VariantName(n), p = strstr(first.variants, v);
1553                 gdk_color_parse( option[i].textValue, &color );
1554                 gtk_widget_modify_bg ( GTK_WIDGET(button), GTK_STATE_NORMAL, &color );
1555                 gtk_widget_set_sensitive(button, option[i].value >= 0 && (appData.noChessProgram
1556                                          || p && (!*v || strlen(p) == strlen(v) || p[strlen(v)] == ',')));
1557                 if(engineVariant[100] ? !strcmp(engineVariant+100, option[i].name) : 
1558                    gameInfo.variant ? option[i].value == gameInfo.variant : !strcmp(option[i].name, "Normal"))
1559                     SetWidgetFont(gtk_bin_get_child(GTK_BIN(button)), &b);
1560             }
1561
1562             Pack(hbox, table, button, left, left+1, top, 0);
1563             if(option[i].value == 666 && !strcmp(option[i].name, "*")) // font-assignment buttons
1564             g_signal_connect (button, "clicked", G_CALLBACK (FontCallback), (gpointer) &option[i-5]);
1565             else
1566             g_signal_connect (button, "clicked", G_CALLBACK (GenericCallback), (gpointer)(intptr_t) i + (dlgNr<<16));
1567             g_signal_connect(button, "button-press-event", G_CALLBACK (HelpEvent), (gpointer) option[i].name );
1568             option[i].handle = (void*)button;
1569             break;
1570           case ComboBox:
1571             label = gtk_label_new(_(option[i].name));
1572             /* Left Justify */
1573             gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);
1574             button = gtk_event_box_new();
1575             gtk_container_add(GTK_CONTAINER(button), label);
1576             label = button;
1577             gtk_widget_add_events(GTK_WIDGET(label), GDK_BUTTON_PRESS_MASK);
1578             g_signal_connect(label, "button-press-event", G_CALLBACK(HelpEvent), (gpointer) option[i].name);
1579             gtk_widget_set_sensitive(label, TRUE);
1580             gtk_table_attach(GTK_TABLE(table), label, left, left+1, top, top+1, GTK_FILL, GTK_FILL, 2, 1);
1581
1582             combobox = gtk_combo_box_new_text();
1583
1584             for(j=0;;j++) {
1585                if (  ((char **) option[i].textValue)[j] == NULL) break;
1586                gtk_combo_box_append_text(GTK_COMBO_BOX(combobox), ((char **) option[i].choice)[j]);
1587             }
1588
1589             if(currentCps)
1590                 option[i].choice = (char**) option[i].textValue;
1591             else {
1592                 for(j=0; option[i].choice[j]; j++) {
1593                     if(*(char**)option[i].target && !strcmp(*(char**)option[i].target, ((char**)(option[i].textValue))[j])) break;
1594                 }
1595                 /* If choice is NULL set to first */
1596                 if (option[i].choice[j] == NULL)
1597                    option[i].value = 0;
1598                 else
1599                    option[i].value = j;
1600             }
1601
1602             //option[i].value = j + (option[i].choice[j] == NULL);
1603             gtk_combo_box_set_active(GTK_COMBO_BOX(combobox), option[i].value);
1604
1605             Pack(hbox, table, combobox, left+1, left+r, top, 0);
1606             g_signal_connect(G_OBJECT(combobox), "changed", G_CALLBACK(ComboSelect), (gpointer) (intptr_t) (i + 256*dlgNr));
1607
1608             option[i].handle = (void*)combobox;
1609             values[i] = option[i].value;
1610             break;
1611           case ListBox:
1612             {
1613                 GtkCellRenderer *renderer;
1614                 GtkTreeViewColumn *column;
1615                 GtkListStore *store;
1616
1617                 option[i].handle = (void *) (list = gtk_tree_view_new());
1618                 SetWidgetFont(option[i].handle, option[i].font);
1619                 gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(list), FALSE);
1620                 renderer = gtk_cell_renderer_text_new();
1621                 column = gtk_tree_view_column_new_with_attributes("List Items", renderer, "text", 0, NULL);
1622                 gtk_tree_view_append_column(GTK_TREE_VIEW(list), column);
1623                 store = gtk_list_store_new(1, G_TYPE_STRING); // 1 column of text
1624                 gtk_tree_view_set_model(GTK_TREE_VIEW(list), GTK_TREE_MODEL(store));
1625                 g_object_unref(store);
1626                 LoadListBox(&option[i], "?", -1, -1);
1627                 HighlightListBoxItem(&option[i], 0);
1628
1629                 /* add listbox to scrolled window so we have vertical scroll bar */
1630                 sw = gtk_scrolled_window_new(NULL, NULL);
1631                 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(sw), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
1632                 gtk_container_add(GTK_CONTAINER(sw), list);
1633                 gtk_widget_set_size_request(GTK_WIDGET(sw), option[i].max ? option[i].max : -1, option[i].value ? option[i].value : -1);
1634                 gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(sw), GTK_SHADOW_OUT);
1635
1636                 if(option[i].textValue) // generic callback for double-clicking listbox item
1637                     g_signal_connect(list, "button-press-event", G_CALLBACK(ListCallback), (gpointer) (intptr_t) (dlgNr<<16 | i) );
1638
1639                 /* never has label, so let listbox occupy all columns */
1640                 Pack(hbox, table, sw, left, left+r, top, GTK_EXPAND);
1641                 expandable = TRUE;
1642             }
1643             break;
1644           case Graph:
1645             option[i].handle = (void*) (graph = gtk_drawing_area_new());
1646             gtk_widget_set_size_request(graph, option[i].max, option[i].value);
1647             if(0){ GtkAllocation a;
1648                 a.x = 0; a.y = 0; a.width = option[i].max, a.height = option[i].value;
1649                 gtk_widget_set_allocation(graph, &a);
1650             }
1651             g_signal_connect (graph, "expose-event", G_CALLBACK (GraphEventProc), (gpointer) &option[i]);
1652             gtk_widget_add_events(GTK_WIDGET(graph), GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK);
1653             g_signal_connect (graph, "button-press-event", G_CALLBACK (GraphEventProc), (gpointer) &option[i]);
1654             g_signal_connect (graph, "button-release-event", G_CALLBACK (GraphEventProc), (gpointer) &option[i]);
1655             g_signal_connect (graph, "motion-notify-event", G_CALLBACK (GraphEventProc), (gpointer) &option[i]);
1656             g_signal_connect (graph, "scroll-event", G_CALLBACK (GraphEventProc), (gpointer) &option[i]);
1657             if(option[i].min & FIX_H) { // logo
1658                 GtkWidget *frame = gtk_aspect_frame_new(NULL, 0.5, 0.5, option[i].max/(float)option[i].value, FALSE);
1659                 gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_NONE);
1660                 gtk_container_add(GTK_CONTAINER(frame), graph);
1661                 graph = frame;
1662             }
1663             Pack(hbox, table, graph, left, left+r, top, GTK_EXPAND);
1664             expandable = TRUE;
1665
1666 #ifdef TODO_GTK
1667             if(option[i].min & SAME_ROW) last = forelast, forelast = lastrow;
1668 #endif
1669             option[i].choice = (char**) cairo_image_surface_create (CAIRO_FORMAT_ARGB32, option[i].max, option[i].value); // image buffer
1670             break;
1671 #ifdef TODO_GTK
1672           case PopUp: // note: used only after Graph, so 'last' refers to the Graph widget
1673             option[i].handle = (void*) CreateComboPopup(last, option + i, i + 256*dlgNr, TRUE, option[i].value);
1674             break;
1675 #endif
1676           case DropDown:
1677             top--;
1678             msg = _(option[i].name); // write name on the menu button
1679 #ifndef OSXAPP
1680             if(tinyLayout) { // clip menu text to keep menu bar small
1681                 int clip = tinyLayout + 1;
1682                 strcpy(def, msg + (msg[clip-1] == '_'));
1683                 def[clip] = NULLCHAR; msg = def;
1684             }
1685 #endif
1686 //          XtSetArg(args[j], XtNmenuName, XtNewString(option[i].name));  j++;
1687 //          XtSetArg(args[j], XtNlabel, msg);  j++;
1688             option[i].handle = (void*)
1689                 (menuButton = gtk_menu_item_new_with_mnemonic(msg));
1690             gtk_widget_show(menuButton);
1691             option[i].textValue = (char*) (menu = CreateMenuPopup(option + i, i + 256*dlgNr, -1));
1692             gtk_menu_item_set_submenu(GTK_MENU_ITEM (menuButton), menu);
1693             gtk_menu_bar_append (GTK_MENU_BAR (menuBar), menuButton);
1694             break;
1695           case BarBegin:
1696             menuBar = gtk_menu_bar_new ();
1697             gtk_widget_show (menuBar);
1698             boxStart = i;
1699             break;
1700           case BoxBegin:
1701             option[i+1].min |= SAME_ROW; // kludge to suppress allocation of new hbox
1702             oldHbox = hbox;
1703             option[i].handle = (void*) (hbox = gtk_hbox_new(FALSE, 0)); // hbox to collect buttons
1704             gtk_box_pack_start(GTK_BOX (oldHbox), hbox, FALSE, TRUE, 0); // *** Beware! Assumes button bar always on same row with other! ***
1705 //            gtk_table_attach(GTK_TABLE(table), hbox, left+2, left+3, top, top+1, GTK_FILL | GTK_SHRINK, GTK_FILL, 2, 1);
1706             boxStart = i;
1707             break;
1708           case BarEnd:
1709             top--;
1710 #ifndef OSXAPP
1711             gtk_table_attach(GTK_TABLE(table), menuBar, left, left+r, top, top+1, GTK_FILL | GTK_EXPAND, GTK_FILL, 2, 1);
1712
1713             if(option[i].target) ((ButtonCallback*)option[i].target)(boxStart); // callback that can make sizing decisions
1714 #else
1715             top--; // in OSX menu bar is not put in window, so also don't count it
1716             {   // in stead, offer it to OSX, and move About item to top of App menu
1717                 GtkosxApplication *theApp = g_object_new(GTKOSX_TYPE_APPLICATION, NULL);
1718                 extern MenuItem helpMenu[]; // oh, well... Adding items in help menu breaks this anyway
1719                 gtk_widget_hide (menuBar);
1720                 gtkosx_application_set_menu_bar(theApp, GTK_MENU_SHELL(menuBar));
1721                 gtkosx_application_insert_app_menu_item(theApp, GTK_MENU_ITEM(helpMenu[8].handle), 0); // hack
1722                 gtkosx_application_sync_menubar(theApp);
1723             }
1724 #endif
1725             break;
1726           case BoxEnd:
1727 //          XtManageChildren(&form, 1);
1728 //          SqueezeIntoBox(&option[boxStart], i-boxStart, option[boxStart].max);
1729             hbox = oldHbox; top--;
1730             if(option[i].target) ((ButtonCallback*)option[i].target)(boxStart); // callback that can make sizing decisions
1731             break;
1732           case Break:
1733             breakType = option[i].min & SAME_ROW | BORDER; // kludge to flag we must break
1734             option[i].handle = table;
1735             break;
1736
1737           case PopUp:
1738             top--;
1739             break;
1740         default:
1741             printf("GenericPopUp: unexpected case in switch. i=%d type=%d name=%s.\n", i, option[i].type, option[i].name);
1742             break;
1743         }
1744     }
1745
1746     if(topLevel && !(option[i].min & NO_OK)) { // buttons requested in top-level window
1747         button = gtk_button_new_with_label (_("OK"));
1748         g_signal_connect (button, "clicked", G_CALLBACK (PopDownProxy), (gpointer)(intptr_t) dlgNr);
1749         if(!(option[i].min & NO_CANCEL)) {
1750             GtkWidget *button2 = gtk_button_new_with_label (_("Cancel"));
1751             g_signal_connect (button2, "clicked", G_CALLBACK (PopDownProxy), (gpointer)(intptr_t) dlgNr + 3000);
1752             if(!hbox) {
1753                 hbox = gtk_hbox_new (False, 0);
1754                 gtk_table_attach(GTK_TABLE(table), hbox, left, left+r, top+1, top+2, GTK_FILL | GTK_EXPAND, GTK_FILL, 2, 1);
1755             }
1756             Pack(hbox, table, button, left, left+1, top+1, 0);
1757             Pack(hbox, table, button2, left, left+1, top+1, 0);
1758         } else Pack(hbox, table, button, left, left+1, ++top, 0);
1759     }
1760
1761     gtk_table_resize(GTK_TABLE(table), top+1, r);
1762     if(dlgNr == BoardWindow && appData.fixedSize) { // inhibit sizing
1763         GtkWidget *h = gtk_hbox_new(FALSE, 0);
1764         gtk_box_pack_start (GTK_BOX (h), table, TRUE, FALSE, 2);
1765         table = h;
1766     }
1767     if(pane)
1768         gtk_box_pack_start (GTK_BOX (pane), table, expandable, TRUE, 0);
1769     else
1770         gtk_box_pack_start (GTK_BOX (/*GTK_DIALOG (dialog)->vbox*/box), table, TRUE, TRUE, 0);
1771
1772     option[i].handle = (void *) table; // remember last table in EndMark handle (for hiding Engine-Output pane).
1773
1774     gtk_window_set_position(GTK_WINDOW(dialog), GTK_WIN_POS_NONE);
1775
1776     /* Show dialog */
1777     gtk_widget_show_all( dialog );
1778
1779     /* hide OK/cancel buttons */
1780     if(!topLevel)
1781       {
1782         if((option[i].min & NO_OK)) {
1783           actionarea = gtk_dialog_get_action_area(GTK_DIALOG(dialog));
1784           gtk_widget_hide(actionarea);
1785         } else if((option[i].min & NO_CANCEL)) {
1786           button = gtk_dialog_get_widget_for_response(GTK_DIALOG(dialog), GTK_RESPONSE_REJECT);
1787           gtk_widget_hide(button);
1788         }
1789         gtk_dialog_get_widget_for_response(GTK_DIALOG(dialog), GTK_RESPONSE_ACCEPT);
1790         g_signal_connect (dialog, "response",
1791                       G_CALLBACK (GenericPopDown),
1792                       (gpointer)(intptr_t) dlgNr);
1793       }
1794
1795     g_signal_connect (dialog, "delete-event",
1796                       G_CALLBACK (GenericPopDown),
1797                       (gpointer)(intptr_t) dlgNr);
1798     shellUp[dlgNr]++;
1799
1800     if(dlgNr && wp[dlgNr]) { // if persistent window-info available, reposition
1801       if(wp[dlgNr]->x > 0 && wp[dlgNr]->y > 0)
1802         gtk_window_move(GTK_WINDOW(dialog), wp[dlgNr]->x, wp[dlgNr]->y);
1803       if(wp[dlgNr]->width > 0 && wp[dlgNr]->height > 0)
1804         gtk_window_resize(GTK_WINDOW(dialog), wp[dlgNr]->width, wp[dlgNr]->height);
1805     }
1806
1807     for(i=0; option[i].type != EndMark; i++) if(option[i].type == Graph)
1808         gtk_widget_set_size_request(option[i].handle, -1, -1); // remove size requests after realization, so user can shrink
1809
1810     return 1; // tells caller he must do initialization (e.g. add specific event handlers)
1811 }
1812
1813 /* function called when the data to Paste is ready */
1814 #ifdef TODO_GTK
1815 static void
1816 SendTextCB (Widget w, XtPointer client_data, Atom *selection,
1817             Atom *type, XtPointer value, unsigned long *len, int *format)
1818 {
1819   char buf[MSG_SIZ], *p = (char*) textOptions[(int)(intptr_t) client_data].choice, *name = (char*) value, *q;
1820   if (value==NULL || *len==0) return; /* nothing selected, abort */
1821   name[*len]='\0';
1822   strncpy(buf, p, MSG_SIZ);
1823   q = strstr(p, "$name");
1824   snprintf(buf + (q-p), MSG_SIZ -(q-p), "%s%s", name, q+5);
1825   SendString(buf);
1826   XtFree(value);
1827 }
1828 #endif
1829
1830 void
1831 SendText (int n)
1832 {
1833     char *p = (char*) textOptions[n].choice;
1834 #ifdef TODO_GTK
1835     if(strstr(p, "$name")) {
1836         XtGetSelectionValue(menuBarWidget,
1837           XA_PRIMARY, XA_STRING,
1838           /* (XtSelectionCallbackProc) */ SendTextCB,
1839           (XtPointer) (intptr_t) n, /* client_data passed to PastePositionCB */
1840           CurrentTime
1841         );
1842     } else
1843 #endif
1844     SendString(p);
1845 }
1846
1847 void
1848 SetInsertPos (Option *opt, int pos)
1849 {
1850     if(opt->value > 80) ScrollToCursor(opt, pos);
1851     else gtk_editable_set_position(GTK_EDITABLE(opt->handle), pos);
1852 }
1853
1854 void
1855 HardSetFocus (Option *opt, DialogClass dlg)
1856 {
1857     FocusOnWidget(opt, dlg);
1858 }