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