Transfer most available gtk-xt code to xoptions.c
[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     XtOverrideTranslations(opt->handle, XtParseTranslationTable(translationTable[nr]));
549 #endif
550 }
551
552 //----------------------------Generic dialog --------------------------------------------
553
554 // cloned from Engine Settings dialog (and later merged with it)
555
556 GtkWidget *shells[NrOfDialogs];
557 DialogClass parents[NrOfDialogs];
558 WindowPlacement *wp[NrOfDialogs] = { // Beware! Order must correspond to DialogClass enum
559     NULL, &wpComment, &wpTags, NULL, NULL, NULL, NULL, &wpMoveHistory, &wpGameList, &wpEngineOutput, &wpEvalGraph,
560     NULL, NULL, NULL, NULL, /*&wpMain*/ NULL
561 };
562
563 int
564 DialogExists (DialogClass n)
565 {   // accessor for use in back-end
566     return shells[n] != NULL;
567 }
568
569 void
570 RaiseWindow (DialogClass dlg)
571 {
572 #ifdef TODO_GTK
573     static XEvent xev;
574     Window root = RootWindow(xDisplay, DefaultScreen(xDisplay));
575     Atom atom = XInternAtom (xDisplay, "_NET_ACTIVE_WINDOW", False);
576
577     xev.xclient.type = ClientMessage;
578     xev.xclient.serial = 0;
579     xev.xclient.send_event = True;
580     xev.xclient.display = xDisplay;
581     xev.xclient.window = XtWindow(shells[dlg]);
582     xev.xclient.message_type = atom;
583     xev.xclient.format = 32;
584     xev.xclient.data.l[0] = 1;
585     xev.xclient.data.l[1] = CurrentTime;
586
587     XSendEvent (xDisplay,
588           root, False,
589           SubstructureRedirectMask | SubstructureNotifyMask,
590           &xev);
591
592     XFlush(xDisplay); 
593     XSync(xDisplay, False);
594 #endif
595 }
596
597 /* Sets a check box on (True) or off (False) in the menu */
598 void SetCheckMenuItemActive(gchar *name, int menuDlgNr, gboolean active)
599 {
600 #ifdef TODO_GTK
601 // This doesn't work anymore, as we don't use builder
602     gchar menuItemName[50];
603
604     if (name != NULL)
605         strcpy(menuItemName, name);
606     else
607         GetMenuItemName(menuDlgNr, menuItemName);
608     
609     if (strcmp(menuItemName, "") == 0) return;
610
611     GtkCheckMenuItem *chk;
612     chk = GTK_CHECK_MENU_ITEM(gtk_builder_get_object(GTK_BUILDER(builder), menuItemName));
613     if (chk == NULL) {
614         printf("Error: failed to get check menu item %s from builder\n", menuItemName);
615         return;        
616     }
617     chk->active = active;   // set the check box without emitting any signals
618 #endif
619 }
620
621 int
622 PopDown (DialogClass n)
623 {
624     //Arg args[10];    
625     
626     if (!shellUp[n] || !shells[n]) return 0;    
627 #ifdef TODO_GTK
628 // Not sure this is still used
629     if(n && wp[n]) { // remember position
630         j = 0;
631         XtSetArg(args[j], XtNx, &windowX); j++;
632         XtSetArg(args[j], XtNy, &windowY); j++;
633         XtSetArg(args[j], XtNheight, &windowH); j++;
634         XtSetArg(args[j], XtNwidth, &windowW); j++;
635         XtGetValues(shells[n], args, j);
636         wp[n]->x = windowX;
637         wp[n]->x = windowY;
638         wp[n]->width  = windowW;
639         wp[n]->height = windowH;
640     }
641 #endif
642     
643     gtk_widget_hide(shells[n]);
644     shellUp[n]--; // count rather than clear
645     if(n == 0 || n >= PromoDlg) {
646         gtk_widget_destroy(shells[n]);
647         shells[n] = NULL;
648     }    
649 #ifdef TODO_GTK
650     if(marked[n]) {
651         MarkMenuItem(marked[n], False);
652         marked[n] = NULL;
653     }
654 #else
655     // when popping down uncheck the check box of the menu item
656     SetCheckMenuItemActive(NULL, n, False);    
657 #endif
658     if(!n) currentCps = NULL; // if an Engine Settings dialog was up, we must be popping it down now
659     currentOption = dialogOptions[TransientDlg]; // just in case a transient dialog was up (to allow its check and combo callbacks to work)
660 #ifdef TODO_GTK
661     RaiseWindow(parents[n]); // automatic in GTK?
662     if(parents[n] == BoardWindow) XtSetKeyboardFocus(shellWidget, formWidget); // also automatic???
663 #endif
664     return 1;
665 }
666
667 gboolean GenericPopDown(w, event, gdata)
668      GtkWidget *w;
669      GdkEvent  *event;
670      gpointer  gdata; 
671 {
672     int dlg = (intptr_t) gdata; /* dialog number dlgnr */
673     
674 #ifdef TODO_GTK
675 // I guess BrowserDlg will be abandoned, as GTK has a better browser of its own
676     if(shellUp[BrowserDlg] && dlg != BrowserDlg || dialogError) return; // prevent closing dialog when it has an open file-browse daughter
677 #else
678     if(browserUp || dialogError) return True; // prevent closing dialog when it has an open file-browse daughter
679 #endif
680     GtkWidget *sh = shells[dlg];
681 printf("popdown %d\n", dlg);
682     shells[dlg] = w; // make sure we pop down the right one in case of multiple instances
683     PopDown(dlg);
684     shells[dlg] = sh; // restore
685     if(dlg == BoardWindow) ExitEvent(0);
686     return True; /* don't propagate to default handler */
687 }
688
689 int AppendText(Option *opt, char *s)
690 {    
691     char *v;
692     int len;
693     GtkTextIter end;    
694   
695     GetWidgetTextGTK(opt->handle, &v);
696     len = strlen(v);
697     g_free(v);
698     gtk_text_buffer_get_end_iter(GTK_TEXT_BUFFER(opt->handle), &end);
699     gtk_text_buffer_insert(opt->handle, &end, s, -1);
700
701     return len;
702 }
703
704 void
705 SetColor (char *colorName, Option *box)
706 {       // sets the color of a widget
707 #ifdef TODO_GTK
708         Arg args[5];
709         Pixel buttonColor;
710         XrmValue vFrom, vTo;
711         if (!appData.monoMode) {
712             vFrom.addr = (caddr_t) colorName;
713             vFrom.size = strlen(colorName);
714             XtConvert(shellWidget, XtRString, &vFrom, XtRPixel, &vTo);
715             if (vTo.addr == NULL) {
716                 buttonColor = (Pixel) -1;
717             } else {
718                 buttonColor = *(Pixel *) vTo.addr;
719             }
720         } else buttonColor = timerBackgroundPixel;
721         XtSetArg(args[0], XtNbackground, buttonColor);;
722         XtSetValues(box->handle, args, 1);
723 #endif
724 }
725
726 #ifdef TODO_GTK
727 void
728 ColorChanged (Widget w, XtPointer data, XEvent *event, Boolean *b)
729 {   // for detecting a typed change in color
730     char buf[10];
731     if ( (XLookupString(&(event->xkey), buf, 2, NULL, NULL) == 1) && *buf == '\r' )
732         RefreshColor((int)(intptr_t) data, 0);
733 }
734 #endif
735
736 #ifdef TODO_GTK
737 static void
738 GraphEventProc(Widget widget, caddr_t client_data, XEvent *event)
739 {   // handle expose and mouse events on Graph widget
740     Dimension w, h;
741     Arg args[16];
742     int j, button=10, f=1, sizing=0;
743     Option *opt, *graph = (Option *) client_data;
744     PointerCallback *userHandler = graph->target;
745
746     if (!XtIsRealized(widget)) return;
747
748     switch(event->type) {
749         case Expose: // make handling of expose events generic, just copying from memory buffer (->choice) to display (->textValue)
750             /* Get window size */
751             j = 0;
752             XtSetArg(args[j], XtNwidth, &w); j++;
753             XtSetArg(args[j], XtNheight, &h); j++;
754             XtGetValues(widget, args, j);
755
756             if(w < graph->max || w > graph->max + 1 || h != graph->value) { // use width fudge of 1 pixel
757                 if(((XExposeEvent*)event)->count >= 0) { // suppress sizing on expose for ordered redraw in response to sizing.
758                     sizing = 1;
759                     graph->max = w; graph->value = h; // note: old values are kept if we we don't exceed width fudge
760                 }
761             } else w = graph->max;
762
763             if(sizing && ((XExposeEvent*)event)->count > 0) { graph->max = 0; return; } // don't bother if further exposure is pending during resize
764             if(!graph->textValue || sizing) { // create surfaces of new size for display widget
765                 if(graph->textValue) cairo_surface_destroy((cairo_surface_t *)graph->textValue);
766                 graph->textValue = (char*) cairo_xlib_surface_create(xDisplay, XtWindow(widget), DefaultVisual(xDisplay, 0), w, h);
767             }
768             if(sizing) { // the memory buffer was already created in GenericPopup(),
769                          // to give drawing routines opportunity to use it before first expose event
770                          // (which are only processed when main gets to the event loop, so after all init!)
771                          // so only change when size is no longer good
772                 if(graph->choice) cairo_surface_destroy((cairo_surface_t *) graph->choice);
773                 graph->choice = (char**) cairo_image_surface_create (CAIRO_FORMAT_ARGB32, w, h);
774                 break;
775             }
776             w = ((XExposeEvent*)event)->width;
777             if(((XExposeEvent*)event)->x + w > graph->max) w--; // cut off fudge pixel
778             if(w) ExposeRedraw(graph, ((XExposeEvent*)event)->x, ((XExposeEvent*)event)->y, w, ((XExposeEvent*)event)->height);
779             return;
780         case MotionNotify:
781             f = 0;
782             w = ((XButtonEvent*)event)->x; h = ((XButtonEvent*)event)->y;
783             break;
784         case ButtonRelease:
785             f = -1; // release indicated by negative button numbers
786         case ButtonPress:
787             w = ((XButtonEvent*)event)->x; h = ((XButtonEvent*)event)->y;
788             switch(((XButtonEvent*)event)->button) {
789                 case Button1: button = 1; break;
790                 case Button2: button = 2; break;
791                 case Button3: button = 3; break;
792                 case Button4: button = 4; break;
793                 case Button5: button = 5; break;
794             }
795     }
796     button *= f;
797     opt = userHandler(button, w, h);
798     if(opt) { // user callback specifies a context menu; pop it up
799         XUngrabPointer(xDisplay, CurrentTime);
800         XtCallActionProc(widget, "XawPositionSimpleMenu", event, &(opt->name), 1);
801         XtPopupSpringLoaded(opt->handle);
802     }
803     XSync(xDisplay, False);
804 }
805 #endif
806
807 void
808 GraphExpose (Option *opt, int x, int y, int w, int h)
809 {
810 #ifdef TODO_GTK
811   XExposeEvent e;
812   if(!opt->handle) return;
813   e.x = x; e.y = y; e.width = w; e.height = h; e.count = -1; e.type = Expose; // count = -1: kludge to suppress sizing
814   GraphEventProc(opt->handle, (caddr_t) opt, (XEvent *) &e); // fake expose event
815 #endif
816 }
817
818 /* GTK callback used when OK/cancel clicked in genericpopup for non-modal dialog */
819 void GenericPopUpCallback(w, resptype, gdata)
820      GtkWidget *w;
821      GtkResponseType  resptype;
822      gpointer  gdata;
823 {
824     int data = (intptr_t) gdata; /* dialog number dlgnr */
825     DialogClass dlg;
826
827     currentOption = dialogOptions[dlg=data>>16]; data &= 0xFFFF;
828
829     /* OK pressed */    
830     if (resptype == GTK_RESPONSE_ACCEPT) {
831         if (GenericReadout(currentOption, -1)) PopDown(data);
832         return;
833     }
834
835     /* cancel pressed */
836     PopDown(dlg);    
837 }
838
839 void GenericCallback(GtkWidget *widget, gpointer gdata)
840 {
841     const gchar *name;
842     char buf[MSG_SIZ];    
843     int data = (intptr_t) gdata;   
844     DialogClass dlg;
845 #ifdef TODO_GTK
846     GtkWidget *sh = XtParent(XtParent(XtParent(w))), *oldSh;
847 #else
848     GtkWidget *sh, *oldSh;
849 #endif
850
851     currentOption = dialogOptions[dlg=data>>16]; data &= 0xFFFF;
852 #ifndef TODO_GTK
853     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!)
854 #endif
855     oldSh = shells[dlg]; shells[dlg] = sh; // bow to reality
856     
857 #ifdef TODO_GTK
858     if (data == 30000) { // cancel
859         PopDown(dlg); 
860     } else
861     if (data == 30001) { // save buttons imply OK
862         if(GenericReadout(currentOption, -1)) PopDown(dlg); // calls OK-proc after full readout, but no popdown if it returns false
863     } else
864 #endif
865
866     if(currentCps) {
867         name = gtk_button_get_label (GTK_BUTTON(widget));         
868         if(currentOption[data].type == SaveButton) GenericReadout(currentOption, -1);
869         snprintf(buf, MSG_SIZ,  "option %s\n", name);
870         SendToProgram(buf, currentCps);
871     } else ((ButtonCallback*) currentOption[data].target)(data);   
872
873     shells[dlg] = oldSh; // in case of multiple instances, restore previous (as this one could be popped down now)
874 }
875
876 #ifdef TODO_GTK
877 void
878 TabProc (Widget w, XEvent *event, String *prms, Cardinal *nprms)
879 {   // for transfering focus to the next text-edit
880     Option *opt;
881     for(opt = currentOption; opt->type != EndMark; opt++) {
882         if(opt->handle == w) {
883             while(++opt) {
884                 if(opt->type == EndMark) opt = currentOption; // wrap
885                 if(opt->handle == w) return; // full circle
886                 if(opt->type == TextBox || opt->type == Spin || opt->type == Fractional || opt->type == FileName || opt->type == PathName) {
887                     SetFocus(opt->handle, XtParent(XtParent(XtParent(w))), NULL, 0);
888                     return;
889                 }
890             }
891         }
892     }
893 }
894 #endif
895
896 #ifdef TODO_GTK
897 void
898 WheelProc (Widget w, XEvent *event, String *prms, Cardinal *nprms)
899 {   // for scrolling a widget seen through a viewport with the mouse wheel (ListBox!)
900     int j=0, n = atoi(prms[0]);
901     static char *params[3] = { "", "Continuous", "Proportional" };
902     Arg args[16];
903     float h, top;
904     Widget v;
905     if(!n) { // transient dialogs also use this for list-selection callback
906         n = prms[1][0]-'0';
907         Option *opt=dialogOptions[prms[2][0]-'A'] + n;
908         if(opt->textValue) ((ListBoxCallback*) opt->textValue)(n, SelectedListBoxItem(opt));
909         return;
910     }
911     v = XtNameToWidget(XtParent(w), "vertical");
912     if(!v) return;
913     XtSetArg(args[j], XtNshown, &h); j++;
914     XtSetArg(args[j], XtNtopOfThumb, &top); j++;
915     XtGetValues(v, args, j);
916     top += 0.1f*h*n; if(top < 0.f) top = 0.;
917     XtCallActionProc(v, "StartScroll", event, params+1, 1);
918     XawScrollbarSetThumb(v, top, -1.0);
919     XtCallActionProc(v, "NotifyThumb", event, params, 0);
920 //    XtCallActionProc(w, "NotifyScroll", event, params+2, 1);
921     XtCallActionProc(v, "EndScroll", event, params, 0);
922 }
923 #endif
924
925 static char *oneLiner  =
926    "<Key>Return: redraw-display() \n \
927     <Key>Tab: TabProc() \n ";
928 static char scrollTranslations[] =
929    "<Btn1Up>(2): WheelProc(0 0 A) \n \
930     <Btn4Down>: WheelProc(-1) \n \
931     <Btn5Down>: WheelProc(1) \n ";
932
933 static void
934 SqueezeIntoBox (Option *opt, int nr, int width)
935 {   // size buttons in bar to fit, clipping button names where necessary
936 #ifdef TODO_GTK
937     int i, wtot = 0;
938     Dimension widths[20], oldWidths[20];
939     Arg arg;
940     for(i=1; i<nr; i++) {
941         XtSetArg(arg, XtNwidth, &widths[i]);
942         XtGetValues(opt[i].handle, &arg, 1);
943         wtot +=  oldWidths[i] = widths[i];
944     }
945     opt->min = wtot;
946     if(width <= 0) return;
947     while(wtot > width) {
948         int wmax=0, imax=0;
949         for(i=1; i<nr; i++) if(widths[i] > wmax) wmax = widths[imax=i];
950         widths[imax]--;
951         wtot--;
952     }
953     for(i=1; i<nr; i++) if(widths[i] != oldWidths[i]) {
954         XtSetArg(arg, XtNwidth, widths[i]);
955         XtSetValues(opt[i].handle, &arg, 1);
956     }
957     opt->min = wtot;
958 #endif
959 }
960
961 #ifdef TODO_GTK
962 int
963 SetPositionAndSize (Arg *args, Widget leftNeigbor, Widget topNeigbor, int b, int w, int h, int chaining)
964 {   // sizing and positioning most widgets have in common
965     int j = 0;
966     // first position the widget w.r.t. earlier ones
967     if(chaining & 1) { // same row: position w.r.t. last (on current row) and lastrow
968         XtSetArg(args[j], XtNfromVert, topNeigbor); j++;
969         XtSetArg(args[j], XtNfromHoriz, leftNeigbor); j++;
970     } else // otherwise it goes at left margin (which is default), below the previous element
971         XtSetArg(args[j], XtNfromVert, leftNeigbor),  j++;
972     // arrange chaining ('2'-bit indicates top and bottom chain the same)
973     if((chaining & 14) == 6) XtSetArg(args[j], XtNtop,    XtChainBottom), j++;
974     if((chaining & 14) == 10) XtSetArg(args[j], XtNbottom, XtChainTop ), j++;
975     if(chaining & 4) XtSetArg(args[j], XtNbottom, XtChainBottom ), j++;
976     if(chaining & 8) XtSetArg(args[j], XtNtop,    XtChainTop), j++;
977     if(chaining & 0x10) XtSetArg(args[j], XtNright, XtChainRight), j++;
978     if(chaining & 0x20) XtSetArg(args[j], XtNleft,  XtChainRight), j++;
979     if(chaining & 0x40) XtSetArg(args[j], XtNright, XtChainLeft ), j++;
980     if(chaining & 0x80) XtSetArg(args[j], XtNleft,  XtChainLeft ), j++;
981     // set size (if given)
982     if(w) XtSetArg(args[j], XtNwidth, w), j++;
983     if(h) XtSetArg(args[j], XtNheight, h),  j++;
984     // color
985     if(!appData.monoMode) {
986         if(!b && appData.dialogColor[0]) XtSetArg(args[j], XtNbackground, dialogColor),  j++;
987         if(b == 3 && appData.buttonColor[0]) XtSetArg(args[j], XtNbackground, buttonColor),  j++;
988     }
989     if(b == 3) b = 1;
990     // border
991     XtSetArg(args[j], XtNborderWidth, b);  j++;
992     return j;
993 }
994 #endif
995
996 int
997 GenericPopUp (Option *option, char *title, DialogClass dlgNr, DialogClass parent, int modal, int topLevel)
998 {    
999     GtkWidget *dialog = NULL;
1000     gint       w;
1001     GtkWidget *label;
1002     GtkWidget *box;
1003     GtkWidget *checkbutton;
1004     GtkWidget *entry;
1005     GtkWidget *hbox;    
1006     GtkWidget *button;
1007     GtkWidget *table;
1008     GtkWidget *spinner;    
1009     GtkAdjustment *spinner_adj;
1010     GtkWidget *combobox;
1011     GtkWidget *textview;
1012     GtkTextBuffer *textbuffer;           
1013     GdkColor color;     
1014     GtkWidget *actionarea;
1015     GtkWidget *sw;    
1016     GtkWidget *list;    
1017     GtkWidget *graph;    
1018     GtkWidget *menuButton;    
1019     GtkWidget *menuBar;    
1020     GtkWidget *menu;    
1021
1022     int i, j, arraysize, left, top, height=999, width=1, boxStart;    
1023     char def[MSG_SIZ], *msg, engineDlg = (currentCps != NULL && dlgNr != BrowserDlg);
1024     
1025     if(dlgNr < PromoDlg && shellUp[dlgNr]) return 0; // already up
1026
1027     if(dlgNr && dlgNr < PromoDlg && shells[dlgNr]) { // reusable, and used before (but popped down)
1028         gtk_widget_show(shells[dlgNr]);
1029         shellUp[dlgNr] = True;
1030         return 0;
1031     }
1032
1033     dialogOptions[dlgNr] = option; // make available to callback
1034     // post currentOption globally, so Spin and Combo callbacks can already use it
1035     // WARNING: this kludge does not work for persistent dialogs, so that these cannot have spin or combo controls!
1036     currentOption = option;
1037
1038     if(engineDlg) { // Settings popup for engine: format through heuristic
1039         int n = currentCps->nrOptions;
1040         if(n > 50) width = 4; else if(n>24) width = 2; else width = 1;
1041         height = n / width + 1;
1042 //      if(n && (currentOption[n-1].type == Button || currentOption[n-1].type == SaveButton)) currentOption[n].min = SAME_ROW; // OK on same line
1043         currentOption[n].type = EndMark; currentOption[n].target = NULL; // delimit list by callback-less end mark
1044     }    
1045
1046 #ifdef TODO_GTK
1047      i = 0;
1048     XtSetArg(args[i], XtNresizable, True); i++;
1049     shells[BoardWindow] = shellWidget; parents[dlgNr] = parent;
1050
1051     if(dlgNr == BoardWindow) dialog = shellWidget; else
1052     dialog =
1053       XtCreatePopupShell(title, !top || !appData.topLevel ? transientShellWidgetClass : topLevelShellWidgetClass,
1054                                                            shells[parent], args, i);
1055 #endif
1056     dialog = gtk_dialog_new_with_buttons( title,
1057                                       NULL,
1058                                       GTK_DIALOG_DESTROY_WITH_PARENT | GTK_DIALOG_NO_SEPARATOR |
1059                                           (modal ? GTK_DIALOG_MODAL : 0),
1060                                       GTK_STOCK_OK, GTK_RESPONSE_ACCEPT,
1061                                       GTK_STOCK_CANCEL, GTK_RESPONSE_REJECT,
1062                                       NULL );      
1063
1064     shells[dlgNr] = dialog;
1065     box = gtk_dialog_get_content_area( GTK_DIALOG( dialog ) );
1066     gtk_box_set_spacing(GTK_BOX(box), 5);    
1067
1068     arraysize = 0;
1069     for (i=0;option[i].type != EndMark;i++) {
1070         arraysize++;   
1071     }
1072
1073     table = gtk_table_new(arraysize, 3, FALSE);
1074     gtk_table_set_col_spacings(GTK_TABLE(table), 20);
1075     left = 0;
1076     top = -1;    
1077
1078     for (i=0;option[i].type != EndMark;i++) {
1079         if(option[i].type == -1) continue;
1080         top++;
1081         if (top >= height) {
1082             top = 0;
1083             left = left + 3;
1084             gtk_table_resize(GTK_TABLE(table), height, left + 3);   
1085         }                
1086         switch(option[i].type) {
1087           case Fractional:           
1088             snprintf(def, MSG_SIZ,  "%.2f", *(float*)option[i].target);
1089             option[i].value = *(float*)option[i].target;
1090             goto tBox;
1091           case Spin:
1092             if(!currentCps) option[i].value = *(int*)option[i].target;
1093             snprintf(def, MSG_SIZ,  "%d", option[i].value);
1094           case TextBox:
1095           case FileName:            
1096           case PathName:
1097           tBox:
1098             label = gtk_label_new(option[i].name);
1099             /* Left Justify */
1100             gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);
1101
1102             /* width */
1103             w = option[i].type == Spin || option[i].type == Fractional ? 70 : option[i].max ? option[i].max : 205;
1104             if(option[i].type == FileName || option[i].type == PathName) w -= 55;
1105
1106             if (option[i].type==TextBox && option[i].min > 80){                
1107                 textview = gtk_text_view_new();                
1108                 gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(textview), GTK_WRAP_WORD);                                
1109                 /* add textview to scrolled window so we have vertical scroll bar */
1110                 sw = gtk_scrolled_window_new(NULL, NULL);
1111                 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(sw), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS);
1112                 gtk_container_add(GTK_CONTAINER(sw), textview);
1113                 gtk_widget_set_size_request(GTK_WIDGET(sw), w, -1);
1114  
1115                 textbuffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview));                
1116                 gtk_widget_set_size_request(textview, -1, option[i].min);
1117                 /* check if label is empty */ 
1118                 if (strcmp(option[i].name,"") != 0) {
1119                     gtk_table_attach_defaults(GTK_TABLE(table), label, left, left+1, top, top+1);
1120                     gtk_table_attach_defaults(GTK_TABLE(table), sw, left+1, left+3, top, top+1);
1121                 }
1122                 else {
1123                     /* no label so let textview occupy all columns */
1124                     gtk_table_attach_defaults(GTK_TABLE(table), sw, left, left+3, top, top+1);
1125                 } 
1126                 if ( *(char**)option[i].target != NULL )
1127                     gtk_text_buffer_set_text (textbuffer, *(char**)option[i].target, -1);
1128                 else
1129                     gtk_text_buffer_set_text (textbuffer, "", -1); 
1130                 option[i].handle = (void*)textbuffer;
1131                 break; 
1132             }
1133
1134             entry = gtk_entry_new();
1135
1136             if (option[i].type==Spin || option[i].type==Fractional)
1137                 gtk_entry_set_text (GTK_ENTRY (entry), def);
1138             else if (currentCps)
1139                 gtk_entry_set_text (GTK_ENTRY (entry), option[i].textValue);
1140             else if ( *(char**)option[i].target != NULL )
1141                 gtk_entry_set_text (GTK_ENTRY (entry), *(char**)option[i].target);            
1142
1143             //gtk_entry_set_width_chars (GTK_ENTRY (entry), 18);
1144             gtk_entry_set_max_length (GTK_ENTRY (entry), w);
1145
1146             // left, right, top, bottom
1147             if (strcmp(option[i].name, "") != 0) gtk_table_attach_defaults(GTK_TABLE(table), label, left, left+1, top, top+1);
1148             //gtk_table_attach_defaults(GTK_TABLE(table), entry, 1, 2, i, i+1);            
1149
1150             if (option[i].type == Spin) {                
1151                 spinner_adj = (GtkAdjustment *) gtk_adjustment_new (option[i].value, option[i].min, option[i].max, 1.0, 0.0, 0.0);
1152                 spinner = gtk_spin_button_new (spinner_adj, 1.0, 0);
1153                 gtk_table_attach_defaults(GTK_TABLE(table), spinner, left+1, left+3, top, top+1);
1154                 option[i].handle = (void*)spinner;
1155             }
1156             else if (option[i].type == FileName || option[i].type == PathName) {
1157                 gtk_table_attach_defaults(GTK_TABLE(table), entry, left+1, left+2, top, top+1);
1158                 button = gtk_button_new_with_label ("Browse");
1159                 gtk_table_attach_defaults(GTK_TABLE(table), button, left+2, left+3, top, top+1);
1160                 g_signal_connect (button, "clicked", G_CALLBACK (Browse), (gpointer)(intptr_t) i);
1161                 option[i].handle = (void*)entry;                 
1162             }
1163             else {
1164                 hbox = gtk_hbox_new (FALSE, 0);
1165                 if (strcmp(option[i].name, "") == 0)
1166                     gtk_table_attach_defaults(GTK_TABLE(table), hbox, left, left+3, top, top+1);
1167                 else
1168                     gtk_table_attach_defaults(GTK_TABLE(table), hbox, left+1, left+3, top, top+1);
1169                 gtk_box_pack_start (GTK_BOX (hbox), entry, TRUE, TRUE, 0);
1170                 //gtk_table_attach_defaults(GTK_TABLE(table), entry, left+1, left+3, top, top+1); 
1171                 option[i].handle = (void*)entry;
1172             }                                   
1173             break;
1174           case CheckBox:
1175             checkbutton = gtk_check_button_new_with_label(option[i].name);            
1176             if(!currentCps) option[i].value = *(Boolean*)option[i].target;
1177             gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbutton), option[i].value);
1178             gtk_table_attach_defaults(GTK_TABLE(table), checkbutton, left, left+3, top, top+1);                            
1179             option[i].handle = (void *)checkbutton;            
1180             break; 
1181           case Label:            
1182             label = gtk_label_new(option[i].name);
1183             /* Left Justify */
1184             gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);
1185             gtk_table_attach_defaults(GTK_TABLE(table), label, left, left+3, top, top+1);                       
1186             break;
1187           case SaveButton:
1188           case Button:
1189             button = gtk_button_new_with_label (option[i].name);
1190
1191             /* set button color on view board dialog */
1192             if(option[i].choice && ((char*)option[i].choice)[0] == '#' && !currentCps) {
1193                 gdk_color_parse( *(char**) option[i-1].target, &color );
1194                 gtk_widget_modify_bg ( GTK_WIDGET(button), GTK_STATE_NORMAL, &color );
1195             }
1196
1197             /* set button color on new variant dialog */
1198             if(option[i].textValue) {
1199                 gdk_color_parse( option[i].textValue, &color );
1200                 gtk_widget_modify_bg ( GTK_WIDGET(button), GTK_STATE_NORMAL, &color );
1201                 gtk_widget_set_sensitive(button, appData.noChessProgram || option[i].value < 0
1202                                          || strstr(first.variants, VariantName(option[i].value)));                 
1203             }
1204             
1205             if (!(option[i].min & 1)) {
1206                if(option[i].textValue) // for new variant dialog give buttons equal space so they line up nicely
1207                    hbox = gtk_hbox_new (TRUE, 0);
1208                else
1209                    hbox = gtk_hbox_new (FALSE, 0);
1210                // if only 1 button then put it in 1st column of table only
1211                if ( (arraysize >= (i+1)) && option[i+1].type != Button )
1212                    gtk_table_attach_defaults(GTK_TABLE(table), hbox, left, left+1, top, top+1);
1213                else
1214                    gtk_table_attach_defaults(GTK_TABLE(table), hbox, left, left+3, top, top+1);
1215             }            
1216             gtk_box_pack_start (GTK_BOX (hbox), button, TRUE, TRUE, 0);           
1217             g_signal_connect (button, "clicked", G_CALLBACK (GenericCallback), (gpointer)(intptr_t) i + (dlgNr<<16));           
1218             option[i].handle = (void*)button;            
1219             break;  
1220           case ComboBox:
1221             label = gtk_label_new(option[i].name);
1222             /* Left Justify */
1223             gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);
1224             gtk_table_attach_defaults(GTK_TABLE(table), label, left, left+1, top, top+1);
1225
1226             combobox = gtk_combo_box_new_text();            
1227
1228             for(j=0;;j++) {
1229                if (  ((char **) option[i].textValue)[j] == NULL) break;
1230                gtk_combo_box_append_text(GTK_COMBO_BOX(combobox), ((char **) option[i].textValue)[j]);                          
1231             }
1232
1233             if(currentCps)
1234                 option[i].choice = (char**) option[i].textValue;
1235             else {            
1236                 for(j=0; option[i].choice[j]; j++) {                
1237                     if(*(char**)option[i].target && !strcmp(*(char**)option[i].target, option[i].choice[j])) break;
1238                 }
1239                 /* If choice is NULL set to first */
1240                 if (option[i].choice[j] == NULL)
1241                    option[i].value = 0;
1242                 else 
1243                    option[i].value = j;
1244             }
1245
1246             //option[i].value = j + (option[i].choice[j] == NULL);            
1247             gtk_combo_box_set_active(GTK_COMBO_BOX(combobox), option[i].value); 
1248             
1249
1250             hbox = gtk_hbox_new (FALSE, 0);
1251             gtk_table_attach_defaults(GTK_TABLE(table), hbox, left+1, left+3, top, top+1);
1252             gtk_box_pack_start (GTK_BOX (hbox), combobox, TRUE, TRUE, 0);
1253             //gtk_table_attach_defaults(GTK_TABLE(table), combobox, 1, 2, i, i+1);
1254
1255             g_signal_connect(G_OBJECT(combobox), "changed", G_CALLBACK(ComboSelect), (gpointer) (intptr_t) (i + 256*dlgNr));
1256
1257             option[i].handle = (void*)combobox;
1258             values[i] = option[i].value;            
1259             break;
1260           case ListBox:
1261             {
1262                 GtkCellRenderer *renderer;
1263                 GtkTreeViewColumn *column;
1264                 GtkListStore *store;
1265
1266                 option[i].handle = (void *) (list = gtk_tree_view_new());
1267                 gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(list), FALSE);
1268                 renderer = gtk_cell_renderer_text_new();
1269                 column = gtk_tree_view_column_new_with_attributes("List Items", renderer, "text", 0, NULL);
1270                 gtk_tree_view_append_column(GTK_TREE_VIEW(list), column);
1271                 store = gtk_list_store_new(1, G_TYPE_STRING); // 1 column of text
1272                 gtk_tree_view_set_model(GTK_TREE_VIEW(list), GTK_TREE_MODEL(store));
1273                 g_object_unref(store);
1274                 LoadListBox(&option[i], "?", -1, -1);
1275                 HighlightListBoxItem(&option[i], 0);
1276
1277                 /* add listbox to scrolled window so we have vertical scroll bar */
1278                 sw = gtk_scrolled_window_new(NULL, NULL);
1279                 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(sw), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
1280                 gtk_container_add(GTK_CONTAINER(sw), list);
1281                 gtk_widget_set_size_request(GTK_WIDGET(sw), w, 300);
1282  
1283                 /* never has label, so let listbox occupy all columns */
1284                 gtk_table_attach_defaults(GTK_TABLE(table), sw, left, left+3, top, top+1);
1285             }
1286             break;
1287           case Graph:
1288             option[i].handle = (void*) (graph = gtk_drawing_area_new());
1289             gtk_widget_set_size_request(graph, option[i].max, option[i].value);
1290             gtk_table_attach_defaults(GTK_TABLE(table), graph, left, left+3, top, top+1);
1291
1292 #ifdef TODO_GTK
1293             XtAddEventHandler(last, ExposureMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask, False,
1294                       (XtEventHandler) GraphEventProc, &option[i]); // mandatory user-supplied expose handler
1295             if(option[i].min & SAME_ROW) last = forelast, forelast = lastrow;
1296 #endif
1297             option[i].choice = (char**) cairo_image_surface_create (CAIRO_FORMAT_ARGB32, option[i].max, option[i].value); // image buffer
1298             break;
1299 #ifdef TODO_GTK
1300           case Graph:
1301             j = SetPositionAndSize(args, last, lastrow, 0 /* border */,
1302                                    option[i].max /* w */, option[i].value /* h */, option[i].min /* chain */);
1303             option[i].handle = (void*)
1304                 (last = XtCreateManagedWidget("graph", widgetClass, form, args, j));
1305             XtAddEventHandler(last, ExposureMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask, False,
1306                       (XtEventHandler) GraphEventProc, &option[i]); // mandatory user-supplied expose handler
1307             if(option[i].min & SAME_ROW) last = forelast, forelast = lastrow;
1308             option[i].choice = (char**) cairo_image_surface_create (CAIRO_FORMAT_ARGB32, option[i].max, option[i].value); // image buffer
1309             break;
1310           case PopUp: // note: used only after Graph, so 'last' refers to the Graph widget
1311             option[i].handle = (void*) CreateComboPopup(last, option + i, i + 256*dlgNr, TRUE, option[i].value);
1312             break;
1313           case BoxBegin:
1314             if(option[i].min & SAME_ROW) forelast = lastrow;
1315             j = SetPositionAndSize(args, last, lastrow, 0 /* border */,
1316                                    0 /* w */, 0 /* h */, option[i].min /* chain */);
1317             XtSetArg(args[j], XtNorientation, XtorientHorizontal);  j++;
1318             XtSetArg(args[j], XtNvSpace, 0);                        j++;
1319             option[box=i].handle = (void*)
1320                 (last = XtCreateWidget("box", boxWidgetClass, form, args, j));
1321             oldForm = form; form = last; oldLastRow = lastrow; oldForeLast = forelast;
1322             lastrow = NULL; last = NULL;
1323             break;
1324 #endif
1325           case DropDown:
1326             msg = _(option[i].name); // write name on the menu button
1327 //          XtSetArg(args[j], XtNmenuName, XtNewString(option[i].name));  j++;
1328 //          XtSetArg(args[j], XtNlabel, msg);  j++;
1329             option[i].handle = (void*)
1330                 (menuButton = gtk_menu_item_new_with_label(msg));
1331             gtk_widget_show(menuButton);
1332             option[i].textValue = (char*) (menu = CreateMenuPopup(option + i, i + 256*dlgNr, -1));
1333             gtk_menu_item_set_submenu(GTK_MENU_ITEM (menuButton), menu);
1334             gtk_menu_bar_append (GTK_MENU_BAR (menuBar), menuButton);
1335
1336             break;
1337           case BarBegin:
1338             menuBar = gtk_menu_bar_new ();
1339             gtk_widget_show (menuBar);
1340           case BoxBegin:
1341             boxStart = i;
1342             break;
1343           case BarEnd:
1344             gtk_table_attach_defaults(GTK_TABLE(table), menuBar, left, left+1, top, top+1);
1345           case BoxEnd:
1346 //          XtManageChildren(&form, 1);
1347 //          SqueezeIntoBox(&option[boxStart], i-boxStart, option[boxStart].max);
1348             if(option[i].target) ((ButtonCallback*)option[i].target)(boxStart); // callback that can make sizing decisions
1349             break;
1350           case Break:
1351             top = height; // force next option to start in a new column
1352             break; 
1353         default:
1354             printf("GenericPopUp: unexpected case in switch. i=%d type=%d name=%s.\n", i, option[i].type, option[i].name);
1355             break;
1356         }        
1357     }
1358
1359     gtk_box_pack_start (GTK_BOX (GTK_DIALOG (dialog)->vbox),
1360                         table, TRUE, TRUE, 0);    
1361
1362     /* Show dialog */
1363     gtk_widget_show_all( dialog );    
1364
1365     /* hide OK/cancel buttons */
1366     if((option[i].min & 2)) {
1367         actionarea = gtk_dialog_get_action_area(GTK_DIALOG(dialog));
1368         gtk_widget_hide(actionarea);
1369     }
1370
1371     g_signal_connect (dialog, "response",
1372                       G_CALLBACK (GenericPopUpCallback),
1373                       (gpointer)(intptr_t) (dlgNr<<16 | i));
1374     g_signal_connect (dialog, "delete-event",
1375                       G_CALLBACK (GenericPopDown),
1376                       (gpointer)(intptr_t) dlgNr);
1377     shellUp[dlgNr]++;
1378
1379 #ifdef TODO_GTK
1380     Arg args[24];
1381     Widget popup, layout, dialog=NULL, edit=NULL, form,  last, b_ok, b_cancel, previousPane = NULL, textField = NULL, oldForm, oldLastRow, oldForeLast;
1382     Window root, child;
1383     int x, y, i, j, height=999, width=1, h, c, w, shrink=FALSE, stack = 0, box, chain;
1384     int win_x, win_y, maxWidth, maxTextWidth;
1385     unsigned int mask;
1386     char def[MSG_SIZ], *msg, engineDlg = (currentCps != NULL && dlgNr != BrowserDlg);
1387     static char pane[6] = "paneX";
1388     Widget texts[100], forelast = NULL, anchor, widest, lastrow = NULL, browse = NULL;
1389     Dimension bWidth = 50;
1390
1391     if(dlgNr < PromoDlg && shellUp[dlgNr]) return 0; // already up
1392     if(dlgNr && dlgNr < PromoDlg && shells[dlgNr]) { // reusable, and used before (but popped down)
1393         XtPopup(shells[dlgNr], XtGrabNone);
1394         shellUp[dlgNr] = True;
1395         return 0;
1396     }
1397
1398     dialogOptions[dlgNr] = option; // make available to callback
1399     // post currentOption globally, so Spin and Combo callbacks can already use it
1400     // WARNING: this kludge does not work for persistent dialogs, so that these cannot have spin or combo controls!
1401     currentOption = option;
1402
1403     if(engineDlg) { // Settings popup for engine: format through heuristic
1404         int n = currentCps->nrOptions;
1405         if(n > 50) width = 4; else if(n>24) width = 2; else width = 1;
1406         height = n / width + 1;
1407         if(n && (currentOption[n-1].type == Button || currentOption[n-1].type == SaveButton)) currentOption[n].min = SAME_ROW; // OK on same line
1408         currentOption[n].type = EndMark; currentOption[n].target = NULL; // delimit list by callback-less end mark
1409     }
1410      i = 0;
1411     XtSetArg(args[i], XtNresizable, True); i++;
1412     shells[BoardWindow] = shellWidget; parents[dlgNr] = parent;
1413
1414     if(dlgNr == BoardWindow) popup = shellWidget; else
1415     popup = shells[dlgNr] =
1416       XtCreatePopupShell(title, !top || !appData.topLevel ? transientShellWidgetClass : topLevelShellWidgetClass,
1417                                                            shells[parent], args, i);
1418
1419     layout =
1420       XtCreateManagedWidget(layoutName, formWidgetClass, popup,
1421                             layoutArgs, XtNumber(layoutArgs));
1422     if(!appData.monoMode && appData.dialogColor[0]) XtSetArg(args[0], XtNbackground, dialogColor);
1423     XtSetValues(layout, args, 1);
1424
1425   for(c=0; c<width; c++) {
1426     pane[4] = 'A'+c;
1427     form =
1428       XtCreateManagedWidget(pane, formWidgetClass, layout,
1429                             formArgs, XtNumber(formArgs));
1430     j=0;
1431     XtSetArg(args[j], stack ? XtNfromVert : XtNfromHoriz, previousPane);  j++;
1432     if(!appData.monoMode && appData.dialogColor[0]) XtSetArg(args[j], XtNbackground, dialogColor),  j++;
1433     XtSetValues(form, args, j);
1434     lastrow = forelast = NULL;
1435     previousPane = form;
1436
1437     last = widest = NULL; anchor = lastrow;
1438     for(h=0; h<height || c == width-1; h++) {
1439         i = h + c*height;
1440         if(option[i].type == EndMark) break;
1441         if(option[i].type == -1) continue;
1442         lastrow = forelast;
1443         forelast = last;
1444         switch(option[i].type) {
1445           case Fractional:
1446             snprintf(def, MSG_SIZ,  "%.2f", *(float*)option[i].target);
1447             option[i].value = *(float*)option[i].target;
1448             goto tBox;
1449           case Spin:
1450             if(!engineDlg) option[i].value = *(int*)option[i].target;
1451             snprintf(def, MSG_SIZ,  "%d", option[i].value);
1452           case TextBox:
1453           case FileName:
1454           case PathName:
1455           tBox:
1456             if(option[i].name[0]) { // prefixed by label with option name
1457                 j = SetPositionAndSize(args, last, lastrow, 0 /* border */,
1458                                        0 /* w */, textHeight /* h */, 0xC0 /* chain to left edge */);
1459                 XtSetArg(args[j], XtNjustify, XtJustifyLeft);  j++;
1460                 XtSetArg(args[j], XtNlabel, _(option[i].name));  j++;
1461                 texts[h] = dialog = XtCreateManagedWidget(option[i].name, labelWidgetClass, form, args, j);
1462             } else texts[h] = dialog = NULL; // kludge to position from left margin
1463             w = option[i].type == Spin || option[i].type == Fractional ? 70 : option[i].max ? option[i].max : 205;
1464             if(option[i].type == FileName || option[i].type == PathName) w -= 55;
1465             j = SetPositionAndSize(args, dialog, last, 1 /* border */,
1466                                    w /* w */, option[i].type == TextBox ? option[i].value : 0 /* h */, 0x91 /* chain full width */);
1467             if(option[i].type == TextBox) { // decorations for multi-line text-edits
1468                 if(option[i].min & T_VSCRL) { XtSetArg(args[j], XtNscrollVertical, XawtextScrollAlways);  j++; }
1469                 if(option[i].min & T_HSCRL) { XtSetArg(args[j], XtNscrollHorizontal, XawtextScrollAlways);  j++; }
1470                 if(option[i].min & T_FILL)  { XtSetArg(args[j], XtNautoFill, True);  j++; }
1471                 if(option[i].min & T_WRAP)  { XtSetArg(args[j], XtNwrap, XawtextWrapWord); j++; }
1472                 if(option[i].min & T_TOP)   { XtSetArg(args[j], XtNtop, XtChainTop); j++;
1473                     if(!option[i].value) {    XtSetArg(args[j], XtNbottom, XtChainTop); j++;
1474                                               XtSetValues(dialog, args+j-2, 2);
1475                     }
1476                 }
1477             } else shrink = TRUE;
1478             XtSetArg(args[j], XtNeditType, XawtextEdit);  j++;
1479             XtSetArg(args[j], XtNuseStringInPlace, False);  j++;
1480             XtSetArg(args[j], XtNdisplayCaret, False);  j++;
1481             XtSetArg(args[j], XtNresizable, True);  j++;
1482             XtSetArg(args[j], XtNinsertPosition, 9999);  j++;
1483             XtSetArg(args[j], XtNstring, option[i].type==Spin || option[i].type==Fractional ? def : 
1484                                 engineDlg ? option[i].textValue : *(char**)option[i].target);  j++;
1485             edit = last;
1486             option[i].handle = (void*)
1487                 (textField = last = XtCreateManagedWidget("text", asciiTextWidgetClass, form, args, j));
1488             XtAddEventHandler(last, ButtonPressMask, False, SetFocus, (XtPointer) popup); // gets focus on mouse click
1489             if(option[i].min == 0 || option[i].type != TextBox)
1490                 XtOverrideTranslations(last, XtParseTranslationTable(oneLiner)); // standard handler for <Enter> and <Tab>
1491
1492             if(option[i].type == TextBox || option[i].type == Fractional) break;
1493
1494             // add increment and decrement controls for spin
1495             if(option[i].type == FileName || option[i].type == PathName) {
1496                 msg = _("browse"); w = 0; // automatically scale to width of text
1497                 j = textHeight ? textHeight : 0;
1498             } else {
1499                 w = 20; msg = "+"; j = textHeight/2; // spin button
1500             }
1501             j = SetPositionAndSize(args, last, edit, 3 /* border */,
1502                                    w /* w */, j /* h */, 0x31 /* chain to right edge */);
1503             edit = XtCreateManagedWidget(msg, commandWidgetClass, form, args, j);
1504             XtAddCallback(edit, XtNcallback, SpinCallback, (XtPointer)(intptr_t) i + 256*dlgNr);
1505             if(w == 0) browse = edit;
1506
1507             if(option[i].type != Spin) break;
1508
1509             j = SetPositionAndSize(args, last, edit, 3 /* border */,
1510                                    20 /* w */, textHeight/2 /* h */, 0x31 /* chain to right edge */);
1511             XtSetArg(args[j], XtNvertDistance, -1);  j++;
1512             last = XtCreateManagedWidget("-", commandWidgetClass, form, args, j);
1513             XtAddCallback(last, XtNcallback, SpinCallback, (XtPointer)(intptr_t) i + 256*dlgNr);
1514             break;
1515           case CheckBox:
1516             if(!engineDlg) option[i].value = *(Boolean*)option[i].target; // where checkbox callback uses it
1517             j = SetPositionAndSize(args, last, lastrow, 1 /* border */,
1518                                    textHeight/2 /* w */, textHeight/2 /* h */, 0xC0 /* chain both to left edge */);
1519             XtSetArg(args[j], XtNvertDistance, (textHeight+2)/4 + 3);  j++;
1520             XtSetArg(args[j], XtNstate, option[i].value);  j++;
1521             lastrow  = last;
1522             option[i].handle = (void*)
1523                 (last = XtCreateManagedWidget(" ", toggleWidgetClass, form, args, j));
1524             j = SetPositionAndSize(args, last, lastrow, 0 /* border */,
1525                                    option[i].max /* w */, textHeight /* h */, 0xC1 /* chain */);
1526             XtSetArg(args[j], XtNjustify, XtJustifyLeft);  j++;
1527             XtSetArg(args[j], XtNlabel, _(option[i].name));  j++;
1528             last = XtCreateManagedWidget("label", commandWidgetClass, form, args, j);
1529             // make clicking the text toggle checkbox
1530             XtAddEventHandler(last, ButtonPressMask, False, CheckCallback, (XtPointer)(intptr_t) i + 256*dlgNr);
1531             shrink = TRUE; // following buttons must get text height
1532             break;
1533           case Label:
1534             msg = option[i].name;
1535             if(!msg) break;
1536             chain = option[i].min;
1537             if(chain & SAME_ROW) forelast = lastrow; else shrink = FALSE;
1538             j = SetPositionAndSize(args, last, lastrow, (chain & 2) != 0 /* border */,
1539                                    option[i].max /* w */, shrink ? textHeight : 0 /* h */, chain | 2 /* chain */);
1540 #if ENABLE_NLS
1541             if(option[i].choice) XtSetArg(args[j], XtNfontSet, *(XFontSet*)option[i].choice), j++;
1542 #else
1543             if(option[i].choice) XtSetArg(args[j], XtNfont, (XFontStruct*)option[i].choice), j++;
1544 #endif
1545             XtSetArg(args[j], XtNresizable, False);  j++;
1546             XtSetArg(args[j], XtNjustify, XtJustifyLeft);  j++;
1547             XtSetArg(args[j], XtNlabel, _(msg));  j++;
1548             option[i].handle = (void*) (last = XtCreateManagedWidget("label", labelWidgetClass, form, args, j));
1549             if(option[i].target) // allow user to specify event handler for button presses
1550                 XtAddEventHandler(last, ButtonPressMask, False, CheckCallback, (XtPointer)(intptr_t) i + 256*dlgNr);
1551             break;
1552           case SaveButton:
1553           case Button:
1554             if(option[i].min & SAME_ROW) {
1555                 chain = 0x31; // 0011.0001 = both left and right side to right edge
1556                 forelast = lastrow;
1557             } else chain = 0, shrink = FALSE;
1558             j = SetPositionAndSize(args, last, lastrow, 3 /* border */,
1559                                    option[i].max /* w */, shrink ? textHeight : 0 /* h */, option[i].min & 0xE | chain /* chain */);
1560             XtSetArg(args[j], XtNlabel, _(option[i].name));  j++;
1561             if(option[i].textValue) { // special for buttons of New Variant dialog
1562                 XtSetArg(args[j], XtNsensitive, appData.noChessProgram || option[i].value < 0
1563                                          || strstr(first.variants, VariantName(option[i].value))); j++;
1564                 XtSetArg(args[j], XtNborderWidth, (gameInfo.variant == option[i].value)+1); j++;
1565             }
1566             option[i].handle = (void*)
1567                 (dialog = last = XtCreateManagedWidget(option[i].name, commandWidgetClass, form, args, j));
1568             if(option[i].choice && ((char*)option[i].choice)[0] == '#' && !engineDlg) { // for the color picker default-reset
1569                 SetColor( *(char**) option[i-1].target, &option[i]);
1570                 XtAddEventHandler(option[i-1].handle, KeyReleaseMask, False, ColorChanged, (XtPointer)(intptr_t) i-1);
1571             }
1572             XtAddCallback(last, XtNcallback, GenericCallback, (XtPointer)(intptr_t) i + (dlgNr<<16)); // invokes user callback
1573             if(option[i].textValue) SetColor( option[i].textValue, &option[i]); // for new-variant buttons
1574             break;
1575           case ComboBox:
1576             j = SetPositionAndSize(args, last, lastrow, 0 /* border */,
1577                                    0 /* w */, textHeight /* h */, 0xC0 /* chain both sides to left edge */);
1578             XtSetArg(args[j], XtNjustify, XtJustifyLeft);  j++;
1579             XtSetArg(args[j], XtNlabel, _(option[i].name));  j++;
1580             texts[h] = dialog = XtCreateManagedWidget(option[i].name, labelWidgetClass, form, args, j);
1581
1582             if(option[i].min & COMBO_CALLBACK) msg = _(option[i].name); else {
1583               if(!engineDlg) SetCurrentComboSelection(option+i);
1584               msg=_(((char**)option[i].choice)[option[i].value]);
1585             }
1586
1587             j = SetPositionAndSize(args, dialog, last, (option[i].min & 2) == 0 /* border */,
1588                                    option[i].max && !engineDlg ? option[i].max : 100 /* w */,
1589                                    textHeight /* h */, 0x91 /* chain */); // same row as its label!
1590             XtSetArg(args[j], XtNmenuName, XtNewString(option[i].name));  j++;
1591             XtSetArg(args[j], XtNlabel, msg);  j++;
1592             shrink = TRUE;
1593             option[i].handle = (void*)
1594                 (last = XtCreateManagedWidget(" ", menuButtonWidgetClass, form, args, j));
1595             CreateComboPopup(last, option + i, i + 256*dlgNr, TRUE, -1);
1596             values[i] = option[i].value;
1597             break;
1598           case ListBox:
1599             // Listbox goes in viewport, as needed for game list
1600             if(option[i].min & SAME_ROW) forelast = lastrow;
1601             j = SetPositionAndSize(args, last, lastrow, 1 /* border */,
1602                                    option[i].max /* w */, option[i].value /* h */, option[i].min /* chain */);
1603             XtSetArg(args[j], XtNresizable, False);  j++;
1604             XtSetArg(args[j], XtNallowVert, True); j++; // scoll direction
1605             last =
1606               XtCreateManagedWidget("viewport", viewportWidgetClass, form, args, j);
1607             j = 0; // now list itself
1608             XtSetArg(args[j], XtNdefaultColumns, 1);  j++;
1609             XtSetArg(args[j], XtNforceColumns, True);  j++;
1610             XtSetArg(args[j], XtNverticalList, True);  j++;
1611             option[i].handle = (void*)
1612                 (edit = XtCreateManagedWidget("list", listWidgetClass, last, args, j));
1613             XawListChange(option[i].handle, option[i].target, 0, 0, True);
1614             XawListHighlight(option[i].handle, 0);
1615             scrollTranslations[25] = '0' + i;
1616             scrollTranslations[27] = 'A' + dlgNr;
1617             XtOverrideTranslations(edit, XtParseTranslationTable(scrollTranslations)); // for mouse-wheel
1618             break;
1619           case Graph:
1620             j = SetPositionAndSize(args, last, lastrow, 0 /* border */,
1621                                    option[i].max /* w */, option[i].value /* h */, option[i].min /* chain */);
1622             option[i].handle = (void*)
1623                 (last = XtCreateManagedWidget("graph", widgetClass, form, args, j));
1624             XtAddEventHandler(last, ExposureMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask, False,
1625                       (XtEventHandler) GraphEventProc, &option[i]); // mandatory user-supplied expose handler
1626             if(option[i].min & SAME_ROW) last = forelast, forelast = lastrow;
1627             option[i].choice = (char**) cairo_image_surface_create (CAIRO_FORMAT_ARGB32, option[i].max, option[i].value); // image buffer
1628             break;
1629           case PopUp: // note: used only after Graph, so 'last' refers to the Graph widget
1630             option[i].handle = (void*) CreateComboPopup(last, option + i, i + 256*dlgNr, TRUE, option[i].value);
1631             break;
1632           case BoxBegin:
1633             if(option[i].min & SAME_ROW) forelast = lastrow;
1634             j = SetPositionAndSize(args, last, lastrow, 0 /* border */,
1635                                    0 /* w */, 0 /* h */, option[i].min /* chain */);
1636             XtSetArg(args[j], XtNorientation, XtorientHorizontal);  j++;
1637             XtSetArg(args[j], XtNvSpace, 0);                        j++;
1638             option[box=i].handle = (void*)
1639                 (last = XtCreateWidget("box", boxWidgetClass, form, args, j));
1640             oldForm = form; form = last; oldLastRow = lastrow; oldForeLast = forelast;
1641             lastrow = NULL; last = NULL;
1642             break;
1643           case DropDown:
1644             j = SetPositionAndSize(args, last, lastrow, 0 /* border */,
1645                                    0 /* w */, 0 /* h */, 1 /* chain (always on same row) */);
1646             forelast = lastrow;
1647             msg = _(option[i].name); // write name on the menu button
1648             XtSetArg(args[j], XtNmenuName, XtNewString(option[i].name));  j++;
1649             XtSetArg(args[j], XtNlabel, msg);  j++;
1650             option[i].handle = (void*)
1651                 (last = XtCreateManagedWidget(option[i].name, menuButtonWidgetClass, form, args, j));
1652             option[i].textValue = (char*) CreateComboPopup(last, option + i, i + 256*dlgNr, FALSE, -1);
1653             break;
1654           case BoxEnd:
1655             XtManageChildren(&form, 1);
1656             SqueezeIntoBox(&option[box], i-box, option[box].max);
1657             if(option[i].target) ((ButtonCallback*)option[i].target)(box); // callback that can make sizing decisions
1658             last = form; lastrow = oldLastRow; form = oldForm; forelast = oldForeLast;
1659             break;
1660           case Break:
1661             width++;
1662             height = i+1;
1663             stack = !(option[i].min & SAME_ROW);
1664             break;
1665         default:
1666             printf("GenericPopUp: unexpected case in switch.\n");
1667             break;
1668         }
1669     }
1670
1671     // make an attempt to align all spins and textbox controls
1672     maxWidth = maxTextWidth = 0;
1673     if(browse != NULL) {
1674         j=0;
1675         XtSetArg(args[j], XtNwidth, &bWidth);  j++;
1676         XtGetValues(browse, args, j);
1677     }
1678     for(h=0; h<height || c == width-1; h++) {
1679         i = h + c*height;
1680         if(option[i].type == EndMark) break;
1681         if(option[i].type == Spin || option[i].type == TextBox || option[i].type == ComboBox
1682                                   || option[i].type == PathName || option[i].type == FileName) {
1683             Dimension w;
1684             if(!texts[h]) continue;
1685             j=0;
1686             XtSetArg(args[j], XtNwidth, &w);  j++;
1687             XtGetValues(texts[h], args, j);
1688             if(option[i].type == Spin) {
1689                 if(w > maxWidth) maxWidth = w;
1690                 widest = texts[h];
1691             } else {
1692                 if(w > maxTextWidth) maxTextWidth = w;
1693                 if(!widest) widest = texts[h];
1694             }
1695         }
1696     }
1697     if(maxTextWidth + 110 < maxWidth)
1698          maxTextWidth = maxWidth - 110;
1699     else maxWidth = maxTextWidth + 110;
1700     for(h=0; h<height || c == width-1; h++) {
1701         i = h + c*height;
1702         if(option[i].type == EndMark) break;
1703         if(!texts[h]) continue; // Note: texts[h] can be undefined (giving errors in valgrind), but then both if's below will be false.
1704         j=0;
1705         if(option[i].type == Spin) {
1706             XtSetArg(args[j], XtNwidth, maxWidth);  j++;
1707             XtSetValues(texts[h], args, j);
1708         } else
1709         if(option[i].type == TextBox || option[i].type == ComboBox || option[i].type == PathName || option[i].type == FileName) {
1710             XtSetArg(args[j], XtNwidth, maxTextWidth);  j++;
1711             XtSetValues(texts[h], args, j);
1712             if(bWidth != 50 && (option[i].type == FileName || option[i].type == PathName)) {
1713                 int tWidth = (option[i].max ? option[i].max : 205) - 5 - bWidth;
1714                 j = 0;
1715                 XtSetArg(args[j], XtNwidth, tWidth);  j++;
1716                 XtSetValues(option[i].handle, args, j);
1717             }
1718         }
1719     }
1720   }
1721
1722     if(option[i].min & SAME_ROW) { // even when OK suppressed this EndMark bit can request chaining of last row to bottom
1723         for(j=i-1; option[j+1].min & SAME_ROW; j--) {
1724             XtSetArg(args[0], XtNtop, XtChainBottom);
1725             XtSetArg(args[1], XtNbottom, XtChainBottom);
1726             XtSetValues(option[j].handle, args, 2);
1727         }
1728         if((option[j].type == TextBox || option[j].type == ListBox) && option[j].name[0] == NULLCHAR) {
1729             Widget w = option[j].handle;
1730             if(option[j].type == ListBox) w = XtParent(w); // for listbox we must chain viewport
1731             XtSetArg(args[0], XtNbottom, XtChainBottom);
1732             XtSetValues(w, args, 1);
1733         }
1734         lastrow = forelast;
1735     } else shrink = FALSE, lastrow = last, last = widest ? widest : dialog;
1736     j = SetPositionAndSize(args, last, anchor ? anchor : lastrow, 3 /* border */,
1737                            0 /* w */, shrink ? textHeight : 0 /* h */, 0x37 /* chain: right, bottom and use both neighbors */);
1738
1739   if(!(option[i].min & NO_OK)) {
1740     option[i].handle = b_ok = XtCreateManagedWidget(_("OK"), commandWidgetClass, form, args, j);
1741     XtAddCallback(b_ok, XtNcallback, GenericCallback, (XtPointer)(intptr_t) (30001 + (dlgNr<<16)));
1742     if(!(option[i].min & NO_CANCEL)) {
1743       XtSetArg(args[1], XtNfromHoriz, b_ok); // overwrites!
1744       b_cancel = XtCreateManagedWidget(_("cancel"), commandWidgetClass, form, args, j);
1745       XtAddCallback(b_cancel, XtNcallback, GenericCallback, (XtPointer)(intptr_t) (30000 + (dlgNr<<16)));
1746     }
1747   }
1748
1749     XtRealizeWidget(popup);
1750     if(dlgNr != BoardWindow) { // assign close button, and position w.r.t. pointer, if not main window
1751         XSetWMProtocols(xDisplay, XtWindow(popup), &wm_delete_window, 1);
1752         snprintf(def, MSG_SIZ, "<Message>WM_PROTOCOLS: GenericPopDown(\"%d\") \n", dlgNr);
1753         XtAugmentTranslations(popup, XtParseTranslationTable(def));
1754         XQueryPointer(xDisplay, xBoardWindow, &root, &child,
1755                         &x, &y, &win_x, &win_y, &mask);
1756
1757         XtSetArg(args[0], XtNx, x - 10);
1758         XtSetArg(args[1], XtNy, y - 30);
1759         XtSetValues(popup, args, 2);
1760     }
1761     XtPopup(popup, modal ? XtGrabExclusive : XtGrabNone);
1762     shellUp[dlgNr]++; // count rather than flag
1763     previous = NULL;
1764     if(textField) SetFocus(textField, popup, (XEvent*) NULL, False);
1765     if(dlgNr && wp[dlgNr] && wp[dlgNr]->width > 0) { // if persistent window-info available, reposition
1766         j = 0;
1767         XtSetArg(args[j], XtNheight, (Dimension) (wp[dlgNr]->height));  j++;
1768         XtSetArg(args[j], XtNwidth,  (Dimension) (wp[dlgNr]->width));  j++;
1769         XtSetArg(args[j], XtNx, (Position) (wp[dlgNr]->x));  j++;
1770         XtSetArg(args[j], XtNy, (Position) (wp[dlgNr]->y));  j++;
1771         XtSetValues(popup, args, j);
1772     }
1773     RaiseWindow(dlgNr);
1774 #endif
1775     return 1; // tells caller he must do initialization (e.g. add specific event handlers)
1776 }
1777
1778 /* function called when the data to Paste is ready */
1779 #ifdef TODO_GTK
1780 static void
1781 SendTextCB (Widget w, XtPointer client_data, Atom *selection,
1782             Atom *type, XtPointer value, unsigned long *len, int *format)
1783 {
1784   char buf[MSG_SIZ], *p = (char*) textOptions[(int)(intptr_t) client_data].choice, *name = (char*) value, *q;
1785   if (value==NULL || *len==0) return; /* nothing selected, abort */
1786   name[*len]='\0';
1787   strncpy(buf, p, MSG_SIZ);
1788   q = strstr(p, "$name");
1789   snprintf(buf + (q-p), MSG_SIZ -(q-p), "%s%s", name, q+5);
1790   SendString(buf);
1791   XtFree(value);
1792 }
1793 #endif
1794
1795 void
1796 SendText (int n)
1797 {
1798 #ifdef TODO_GTK
1799     char *p = (char*) textOptions[n].choice;
1800     if(strstr(p, "$name")) {
1801         XtGetSelectionValue(menuBarWidget,
1802           XA_PRIMARY, XA_STRING,
1803           /* (XtSelectionCallbackProc) */ SendTextCB,
1804           (XtPointer) (intptr_t) n, /* client_data passed to PastePositionCB */
1805           CurrentTime
1806         );
1807     } else SendString(p);
1808 #endif
1809 }
1810
1811 void
1812 SetInsertPos (Option *opt, int pos)
1813 {
1814 #ifdef TODO_GTK
1815     Arg args[16];
1816     XtSetArg(args[0], XtNinsertPosition, pos);
1817     XtSetValues(opt->handle, args, 1);
1818 //    SetFocus(opt->handle, shells[InputBoxDlg], NULL, False); // No idea why this does not work, and the following is needed:
1819 //    XSetInputFocus(xDisplay, XtWindow(opt->handle), RevertToPointerRoot, CurrentTime);
1820 #endif
1821 }
1822
1823 #ifdef TODO_GTK
1824 void
1825 TypeInProc (Widget w, XEvent *event, String *prms, Cardinal *nprms)
1826 {   // can be used as handler for any text edit in any dialog (from GenericPopUp, that is)
1827     int n = prms[0][0] - '0';
1828     Widget sh = XtParent(XtParent(XtParent(w))); // popup shell
1829
1830     if(n<2) { // Enter or Esc typed from primed text widget: treat as if dialog OK or cancel button hit.
1831         int dlgNr; // figure out what the dialog number is by comparing shells (because we must pass it :( )
1832         for(dlgNr=0; dlgNr<NrOfDialogs; dlgNr++) if(shellUp[dlgNr] && shells[dlgNr] == sh)
1833             GenericCallback (w, (XtPointer)(intptr_t) (30000 + n + (dlgNr<<16)), NULL);
1834     }
1835 }
1836 #endif
1837
1838 void
1839 HardSetFocus (Option *opt)
1840 {
1841 #ifdef TODO_GTK
1842     XSetInputFocus(xDisplay, XtWindow(opt->handle), RevertToPointerRoot, CurrentTime);
1843 #endif
1844 }
1845
1846