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