9d4f122d78e60527e9fd1263c2078e141d961c4c
[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
53 #include "common.h"
54 #include "backend.h"
55 #include "xboard.h"
56 #include "xboard2.h"
57 #include "dialogs.h"
58 #include "menus.h"
59 #include "gettext.h"
60
61 #ifdef ENABLE_NLS
62 # define  _(s) gettext (s)
63 # define N_(s) gettext_noop (s)
64 #else
65 # define  _(s) (s)
66 # define N_(s)  s
67 #endif
68
69 // [HGM] the following code for makng menu popups was cloned from the FileNamePopUp routines
70
71 static Widget previous = NULL;
72 static Option *currentOption;
73
74 void
75 UnCaret ()
76 {
77 #ifdef TODO_GTK
78     Arg args[2];
79
80     if(previous) {
81         XtSetArg(args[0], XtNdisplayCaret, False);
82         XtSetValues(previous, args, 1);
83     }
84     previous = NULL;
85 #endif
86 }
87
88 void
89 SetFocus (Widget w, XtPointer data, XEvent *event, Boolean *b)
90 {
91 #ifdef TODO_GTK
92     Arg args[2];
93     char *s;
94     int j;
95
96     UnCaret();
97     XtSetArg(args[0], XtNstring, &s);
98     XtGetValues(w, args, 1);
99     j = 1;
100     XtSetArg(args[0], XtNdisplayCaret, True);
101     if(!strchr(s, '\n') && strlen(s) < 80) XtSetArg(args[1], XtNinsertPosition, strlen(s)), j++;
102     XtSetValues(w, args, j);
103     XtSetKeyboardFocus((Widget) data, w);
104     previous = w;
105 #endif
106 }
107
108 void
109 BoardFocus ()
110 {
111 #ifdef TODO_GTK
112     XtSetKeyboardFocus(shellWidget, formWidget);
113 #endif
114 }
115
116 //--------------------------- Engine-specific options menu ----------------------------------
117
118 int dialogError;
119 Option *dialogOptions[NrOfDialogs];
120
121 #ifdef TODO_GTK
122 static Arg layoutArgs[] = {
123     { XtNborderWidth, 0 },
124     { XtNdefaultDistance, 0 },
125 };
126
127 static Arg formArgs[] = {
128     { XtNborderWidth, 0 },
129     { XtNresizable, (XtArgVal) True },
130 };
131 #endif
132
133 void
134 MarkMenuItem (char *menuRef, int state)
135 {
136     MenuItem *item = MenuNameToItem(menuRef);
137
138 #ifdef TODO_GTK
139     if(item) {
140         Arg args[2];
141         XtSetArg(args[0], XtNleftBitmap, state ? xMarkPixmap : None);
142         XtSetValues(item->handle, args, 1);
143     }
144 #endif
145 }
146
147 void
148 GetWidgetText (Option *opt, char **buf)
149 {
150 #ifdef TODO_GTK
151     Arg arg;
152     XtSetArg(arg, XtNstring, buf);
153     XtGetValues(opt->handle, &arg, 1);
154 #endif
155 }
156
157 void
158 SetWidgetText (Option *opt, char *buf, int n)
159 {
160 #ifdef TODO_GTK
161     Arg arg;
162     XtSetArg(arg, XtNstring, buf);
163     XtSetValues(opt->handle, &arg, 1);
164     if(n >= 0) SetFocus(opt->handle, shells[n], NULL, False);
165 #endif
166 }
167
168 void
169 GetWidgetState (Option *opt, int *state)
170 {
171 #ifdef TODO_GTK
172     Arg arg;
173     XtSetArg(arg, XtNstate, state);
174     XtGetValues(opt->handle, &arg, 1);
175 #endif
176 }
177
178 void
179 SetWidgetState (Option *opt, int state)
180 {
181 #ifdef TODO_GTK
182     Arg arg;
183     XtSetArg(arg, XtNstate, state);
184     XtSetValues(opt->handle, &arg, 1);
185 #endif
186 }
187
188 void
189 SetWidgetLabel (Option *opt, char *buf)
190 {
191 #ifdef TODO_GTK
192     Arg arg;
193     XtSetArg(arg, XtNlabel, (XtArgVal) buf);
194     XtSetValues(opt->handle, &arg, 1);
195 #endif
196 }
197
198 void
199 SetDialogTitle (DialogClass dlg, char *title)
200 {
201 #ifdef TODO_GTK
202     Arg args[16];
203     XtSetArg(args[0], XtNtitle, title);
204     XtSetValues(shells[dlg], args, 1);
205 #endif
206 }
207
208 void
209 LoadListBox (Option *opt, char *emptyText, int n1, int n2)
210 {
211 #ifdef TODO_GTK
212     static char *dummyList[2];
213     dummyList[0] = emptyText; // empty listboxes tend to crash X, so display user-supplied warning string instead
214     XawListChange(opt->handle, *(char*)opt->target ? opt->target : dummyList, 0, 0, True);
215 #endif
216 }
217
218 int
219 ReadScroll (Option *opt, float *top, float *bottom)
220 {   // retreives fractions of top and bottom of thumb
221 #ifdef TODO_GTK
222     Arg args[16];
223     Widget w = XtParent(opt->handle); // viewport
224     Widget v = XtNameToWidget(w, "vertical");
225     int j=0;
226     float h;
227     if(!v) return FALSE; // no scroll bar
228     XtSetArg(args[j], XtNshown, &h); j++;
229     XtSetArg(args[j], XtNtopOfThumb, top); j++;
230     XtGetValues(v, args, j);
231     *bottom = *top + h;
232 #endif
233     return TRUE;
234 }
235
236 void
237 SetScroll (Option *opt, float f)
238 {   // sets top of thumb to given fraction
239 #ifdef TODO_GTK
240     static char *params[3] = { "", "Continuous", "Proportional" };
241     static XEvent event;
242     Widget w = XtParent(opt->handle); // viewport
243     Widget v = XtNameToWidget(w, "vertical");
244     if(!v) return; // no scroll bar
245     XtCallActionProc(v, "StartScroll", &event, params+1, 1);
246     XawScrollbarSetThumb(v, f, -1.0);
247     XtCallActionProc(v, "NotifyThumb", &event, params, 0);
248 //    XtCallActionProc(v, "NotifyScroll", &event, params+2, 1);
249     XtCallActionProc(v, "EndScroll", &event, params, 0);
250 #endif
251 }
252
253 void
254 HighlightListBoxItem (Option *opt, int nr)
255 {
256 #ifdef TODO_GTK
257     XawListHighlight(opt->handle, nr);
258 #endif
259 }
260
261 void
262 HighlightWithScroll (Option *opt, int sel, int max)
263 {
264 #ifdef TODO_GTK
265     float top, bottom, f, g;
266     HighlightListBoxItem(opt, sel);
267     if(!ReadScroll(opt, &top, &bottom)) return; // no scroll bar
268     bottom = bottom*max - 1.f;
269     f = g = top;
270     top *= max;
271     if(sel > (top + 3*bottom)/4) f = (sel - 0.75f*(bottom-top))/max; else
272     if(sel < (3*top + bottom)/4) f = (sel - 0.25f*(bottom-top))/max;
273     if(f < 0.f) f = 0.; if(f + 1.f/max > 1.f) f = 1. - 1./max;
274     if(f != g) SetScroll(opt, f);
275 #endif
276 }
277
278 int
279 SelectedListBoxItem (Option *opt)
280 {
281 #ifdef TODO_GTK
282     XawListReturnStruct *rs;
283     rs = XawListShowCurrent(opt->handle);
284     return rs->list_index;
285 #else
286     return 0;
287 #endif
288 }
289
290 void
291 FocusOnWidget (Option *opt, DialogClass dlg)
292 {
293     UnCaret();
294 #ifdef TODO_GTK
295     XtSetKeyboardFocus(shells[dlg], opt->handle);
296 #endif
297 }
298
299 void
300 SetIconName (DialogClass dlg, char *name)
301 {
302 #ifdef TODO_GTK
303         Arg args[16];
304         int j = 0;
305         XtSetArg(args[j], XtNiconName, (XtArgVal) name);  j++;
306 //      XtSetArg(args[j], XtNtitle, (XtArgVal) name);  j++;
307         XtSetValues(shells[dlg], args, j);
308 #endif
309 }
310
311 static void
312 CheckCallback (Widget ww, XtPointer client_data, XEvent *event, Boolean *b)
313 {
314     int s, data = (intptr_t) client_data;
315     Option *opt = dialogOptions[data >> 8] + (data & 255);
316
317     if(opt->type == Label) { ((ButtonCallback*) opt->target)(data&255); return; }
318
319     GetWidgetState(opt, &s);
320     SetWidgetState(opt, !s);
321 }
322
323 static void
324 SpinCallback (Widget w, XtPointer client_data, XtPointer call_data)
325 {
326 #ifdef TODO_GTK
327     String name, val;
328     Arg args[16];
329     char buf[MSG_SIZ], *p;
330     int j = 0; // Initialisation is necessary because the text value may be non-numeric causing the scanf conversion to fail
331     int data = (intptr_t) client_data;
332     Option *opt = dialogOptions[data >> 8] + (data & 255);
333
334     XtSetArg(args[0], XtNlabel, &name);
335     XtGetValues(w, args, 1);
336
337     GetWidgetText(opt, &val);
338     sscanf(val, "%d", &j);
339     if (strcmp(name, _("browse")) == 0) {
340         char *q=val, *r;
341         for(r = ""; *q; q++) if(*q == '.') r = q; else if(*q == '/') r = ""; // last dot after last slash
342         if(!strcmp(r, "") && !currentCps && opt->type == FileName && opt->textValue)
343                 r = opt->textValue;
344         Browse(data>>8, opt->name, NULL, r, opt->type == PathName, "", &p, (FILE**) opt);
345         return;
346     } else
347     if (strcmp(name, "+") == 0) {
348         if(++j > opt->max) return;
349     } else
350     if (strcmp(name, "-") == 0) {
351         if(--j < opt->min) return;
352     } else return;
353     snprintf(buf, MSG_SIZ,  "%d", j);
354     SetWidgetText(opt, buf, TransientDlg);
355 #endif
356 }
357
358 static void
359 ComboSelect (Widget w, caddr_t addr, caddr_t index) // callback for all combo items
360 {
361 #ifdef TODO_GTK
362     Arg args[16];
363     Option *opt = dialogOptions[((intptr_t)addr)>>24]; // applicable option list
364     int i = ((intptr_t)addr)>>16 & 255; // option number
365     int j = 0xFFFF & (intptr_t) addr;
366
367     values[i] = j; // store selected value in Option struct, for retrieval at OK
368
369     if(opt[i].type == Graph || opt[i].min & COMBO_CALLBACK && (!currentCps || shellUp[BrowserDlg])) {
370         ((ButtonCallback*) opt[i].target)(i);
371         return;
372     }
373
374     if(opt[i].min & NO_GETTEXT)
375       XtSetArg(args[0], XtNlabel, ((char**)opt[i].choice)[j]);
376     else
377       XtSetArg(args[0], XtNlabel, _(((char**)opt[i].choice)[j]));
378
379     XtSetValues(opt[i].handle, args, 1);
380 #endif
381 }
382
383 Widget
384 CreateMenuItem (Widget menu, char *msg, XtCallbackProc CB, int n)
385 {
386 #ifdef TODO_GTK
387     int j=0;
388     Widget entry;
389     Arg args[16];
390     XtSetArg(args[j], XtNleftMargin, 20);   j++;
391     XtSetArg(args[j], XtNrightMargin, 20);  j++;
392     if(!strcmp(msg, "----")) { XtCreateManagedWidget(msg, smeLineObjectClass, menu, args, j); return NULL; }
393     XtSetArg(args[j], XtNlabel, msg);
394     entry = XtCreateManagedWidget("item", smeBSBObjectClass, menu, args, j+1);
395     XtAddCallback(entry, XtNcallback, CB, (caddr_t)(intptr_t) n);
396     return entry;
397 #else
398     return NULL;
399 #endif
400 }
401
402 static Widget
403 CreateComboPopup (Widget parent, Option *opt, int n, int fromList, int def)
404 {   // fromList determines if the item texts are taken from a list of strings, or from a menu table
405 #ifdef TODO_GTK
406     int i;
407     Widget menu, entry;
408     Arg arg;
409     MenuItem *mb = (MenuItem *) opt->choice;
410     char **list = (char **) opt->choice;
411
412     if(list[0] == NULL) return NULL; // avoid empty menus, as they cause crash
413     menu = XtCreatePopupShell(opt->name, simpleMenuWidgetClass, parent, NULL, 0);
414
415     for (i=0; 1; i++) 
416       {
417         char *msg = fromList ? list[i] : mb[i].string;
418         if(!msg) break;
419         entry = CreateMenuItem(menu, opt->min & NO_GETTEXT ? msg : _(msg), (XtCallbackProc) ComboSelect, (n<<16)+i);
420         if(!fromList) mb[i].handle = (void*) entry; // save item ID, for enabling / checkmarking
421         if(i==def) {
422             XtSetArg(arg, XtNpopupOnEntry, entry);
423             XtSetValues(menu, &arg, 1);
424         }
425       }
426       return menu;
427 #else
428     return NULL;
429 #endif
430 }
431
432 char moveTypeInTranslations[] =
433     "<Key>Return: TypeInProc(1) \n"
434     "<Key>Escape: TypeInProc(0) \n";
435 extern char filterTranslations[];
436 extern char gameListTranslations[];
437 extern char memoTranslations[];
438
439
440 char *translationTable[] = { // beware: order is essential!
441    historyTranslations, commentTranslations, moveTypeInTranslations, ICSInputTranslations,
442    filterTranslations, gameListTranslations, memoTranslations
443 };
444
445 void * shells[NrOfDialogs];
446
447 AddHandler (Option *opt, int nr)
448 {
449 #ifdef TODO_GTK
450     XtOverrideTranslations(opt->handle, XtParseTranslationTable(translationTable[nr]));
451 #endif
452 }
453
454 //----------------------------Generic dialog --------------------------------------------
455
456 // cloned from Engine Settings dialog (and later merged with it)
457
458 #ifdef TODO_GTK
459 Widget shells[NrOfDialogs];
460 #else
461 void *shells[NrOfDialogs];
462 #endif
463 DialogClass parents[NrOfDialogs];
464 WindowPlacement *wp[NrOfDialogs] = { // Beware! Order must correspond to DialogClass enum
465     NULL, &wpComment, &wpTags, NULL, NULL, NULL, NULL, &wpMoveHistory, &wpGameList, &wpEngineOutput, &wpEvalGraph,
466     NULL, NULL, NULL, NULL, /*&wpMain*/ NULL
467 };
468
469 int
470 DialogExists (DialogClass n)
471 {   // accessor for use in back-end
472     return shells[n] != NULL;
473 }
474
475 void
476 RaiseWindow (DialogClass dlg)
477 {
478 #ifdef TODO_GTK
479     static XEvent xev;
480     Window root = RootWindow(xDisplay, DefaultScreen(xDisplay));
481     Atom atom = XInternAtom (xDisplay, "_NET_ACTIVE_WINDOW", False);
482
483     xev.xclient.type = ClientMessage;
484     xev.xclient.serial = 0;
485     xev.xclient.send_event = True;
486     xev.xclient.display = xDisplay;
487     xev.xclient.window = XtWindow(shells[dlg]);
488     xev.xclient.message_type = atom;
489     xev.xclient.format = 32;
490     xev.xclient.data.l[0] = 1;
491     xev.xclient.data.l[1] = CurrentTime;
492
493     XSendEvent (xDisplay,
494           root, False,
495           SubstructureRedirectMask | SubstructureNotifyMask,
496           &xev);
497
498     XFlush(xDisplay); 
499     XSync(xDisplay, False);
500 #endif
501 }
502
503 int
504 PopDown (DialogClass n)
505 {   // pops down any dialog created by GenericPopUp (or returns False if it wasn't up), unmarks any associated marked menu
506 #ifdef TODO_GTK
507     int j;
508     Arg args[10];
509     Dimension windowH, windowW; Position windowX, windowY;
510     if (!shellUp[n] || !shells[n]) return 0;
511     if(n && wp[n]) { // remember position
512         j = 0;
513         XtSetArg(args[j], XtNx, &windowX); j++;
514         XtSetArg(args[j], XtNy, &windowY); j++;
515         XtSetArg(args[j], XtNheight, &windowH); j++;
516         XtSetArg(args[j], XtNwidth, &windowW); j++;
517         XtGetValues(shells[n], args, j);
518         wp[n]->x = windowX;
519         wp[n]->x = windowY;
520         wp[n]->width  = windowW;
521         wp[n]->height = windowH;
522     }
523     previous = NULL;
524     XtPopdown(shells[n]);
525     shellUp[n]--; // count rather than clear
526     if(n == 0 || n >= PromoDlg) XtDestroyWidget(shells[n]), shells[n] = NULL;
527     if(marked[n]) {
528         MarkMenuItem(marked[n], False);
529         marked[n] = NULL;
530     }
531     if(!n && n != BrowserDlg) currentCps = NULL; // if an Engine Settings dialog was up, we must be popping it down now
532     currentOption = dialogOptions[TransientDlg]; // just in case a transient dialog was up (to allow its check and combo callbacks to work)
533     RaiseWindow(parents[n]);
534     if(parents[n] == BoardWindow) XtSetKeyboardFocus(shellWidget, formWidget);
535 #endif
536     return 1;
537 }
538
539 #ifdef TODO_GTK
540 void
541 GenericPopDown (Widget w, XEvent *event, String *prms, Cardinal *nprms)
542 {   // to cause popdown through a translation (Delete Window button!)
543     int dlg = atoi(prms[0]);
544     Widget sh = shells[dlg];
545     if(shellUp[BrowserDlg] && dlg != BrowserDlg || dialogError) return; // prevent closing dialog when it has an open file-browse daughter
546     shells[dlg] = w;
547     PopDown(dlg);
548     shells[dlg] = sh; // restore
549 }
550 #endif
551
552 int
553 AppendText (Option *opt, char *s)
554 {
555     int len;
556 #ifdef TODO_GTK
557     XawTextBlock t;
558     char *v;
559     GetWidgetText(opt, &v);
560     len = strlen(v);
561     t.ptr = s; t.firstPos = 0; t.length = strlen(s); t.format = XawFmt8Bit;
562     XawTextReplace(opt->handle, len, len, &t);
563 #endif
564     return len;
565 }
566
567 void
568 SetColor (char *colorName, Option *box)
569 {       // sets the color of a widget
570 #ifdef TODO_GTK
571         Arg args[5];
572         Pixel buttonColor;
573         XrmValue vFrom, vTo;
574         if (!appData.monoMode) {
575             vFrom.addr = (caddr_t) colorName;
576             vFrom.size = strlen(colorName);
577             XtConvert(shellWidget, XtRString, &vFrom, XtRPixel, &vTo);
578             if (vTo.addr == NULL) {
579                 buttonColor = (Pixel) -1;
580             } else {
581                 buttonColor = *(Pixel *) vTo.addr;
582             }
583         } else buttonColor = timerBackgroundPixel;
584         XtSetArg(args[0], XtNbackground, buttonColor);;
585         XtSetValues(box->handle, args, 1);
586 #endif
587 }
588
589 void
590 ColorChanged (Widget w, XtPointer data, XEvent *event, Boolean *b)
591 {   // for detecting a typed change in color
592     char buf[10];
593 #ifdef TODO_GTK
594     if ( (XLookupString(&(event->xkey), buf, 2, NULL, NULL) == 1) && *buf == '\r' )
595         RefreshColor((int)(intptr_t) data, 0);
596 #endif
597 }
598
599 static void
600 GraphEventProc(Widget widget, caddr_t client_data, XEvent *event)
601 {   // handle expose and mouse events on Graph widget
602 #ifdef TODO_GTK
603     Dimension w, h;
604     Arg args[16];
605     int j, button=10, f=1, sizing=0;
606     Option *opt, *graph = (Option *) client_data;
607     PointerCallback *userHandler = graph->target;
608
609     if (!XtIsRealized(widget)) return;
610
611     switch(event->type) {
612         case Expose: // make handling of expose events generic, just copying from memory buffer (->choice) to display (->textValue)
613             /* Get window size */
614             j = 0;
615             XtSetArg(args[j], XtNwidth, &w); j++;
616             XtSetArg(args[j], XtNheight, &h); j++;
617             XtGetValues(widget, args, j);
618
619             if(w < graph->max || w > graph->max + 1 || h != graph->value) { // use width fudge of 1 pixel
620                 if(((XExposeEvent*)event)->count >= 0) { // suppress sizing on expose for ordered redraw in response to sizing.
621                     sizing = 1;
622                     graph->max = w; graph->value = h; // note: old values are kept if we we don't exceed width fudge
623                 }
624             } else w = graph->max;
625
626             if(sizing && ((XExposeEvent*)event)->count > 0) { graph->max = 0; return; } // don't bother if further exposure is pending during resize
627             if(!graph->textValue || sizing) { // create surfaces of new size for display widget
628                 if(graph->textValue) cairo_surface_destroy((cairo_surface_t *)graph->textValue);
629                 graph->textValue = (char*) cairo_xlib_surface_create(xDisplay, XtWindow(widget), DefaultVisual(xDisplay, 0), w, h);
630             }
631             if(sizing) { // the memory buffer was already created in GenericPopup(),
632                          // to give drawing routines opportunity to use it before first expose event
633                          // (which are only processed when main gets to the event loop, so after all init!)
634                          // so only change when size is no longer good
635                 if(graph->choice) cairo_surface_destroy((cairo_surface_t *) graph->choice);
636                 graph->choice = (char**) cairo_image_surface_create (CAIRO_FORMAT_ARGB32, w, h);
637                 break;
638             }
639             w = ((XExposeEvent*)event)->width;
640             if(((XExposeEvent*)event)->x + w > graph->max) w--; // cut off fudge pixel
641             if(w) ExposeRedraw(graph, ((XExposeEvent*)event)->x, ((XExposeEvent*)event)->y, w, ((XExposeEvent*)event)->height);
642             return;
643         case MotionNotify:
644             f = 0;
645             w = ((XButtonEvent*)event)->x; h = ((XButtonEvent*)event)->y;
646             break;
647         case ButtonRelease:
648             f = -1; // release indicated by negative button numbers
649         case ButtonPress:
650             w = ((XButtonEvent*)event)->x; h = ((XButtonEvent*)event)->y;
651             switch(((XButtonEvent*)event)->button) {
652                 case Button1: button = 1; break;
653                 case Button2: button = 2; break;
654                 case Button3: button = 3; break;
655                 case Button4: button = 4; break;
656                 case Button5: button = 5; break;
657             }
658     }
659     button *= f;
660     opt = userHandler(button, w, h);
661     if(opt) { // user callback specifies a context menu; pop it up
662         XUngrabPointer(xDisplay, CurrentTime);
663         XtCallActionProc(widget, "XawPositionSimpleMenu", event, &(opt->name), 1);
664         XtPopupSpringLoaded(opt->handle);
665     }
666     XSync(xDisplay, False);
667 #endif
668 }
669
670 void
671 GraphExpose (Option *opt, int x, int y, int w, int h)
672 {
673 #ifdef TODO_GTK
674   XExposeEvent e;
675   if(!opt->handle) return;
676   e.x = x; e.y = y; e.width = w; e.height = h; e.count = -1; e.type = Expose; // count = -1: kludge to suppress sizing
677   GraphEventProc(opt->handle, (caddr_t) opt, (XEvent *) &e); // fake expose event
678 #endif
679 }
680
681 static void
682 GenericCallback (Widget w, XtPointer client_data, XtPointer call_data)
683 {   // all Buttons in a dialog (including OK, cancel) invoke this
684 #ifdef TODO_GTK
685     String name;
686     Arg args[16];
687     char buf[MSG_SIZ];
688     int data = (intptr_t) client_data;
689     DialogClass dlg;
690     Widget sh = XtParent(XtParent(XtParent(w))), oldSh;
691
692     currentOption = dialogOptions[dlg=data>>16]; data &= 0xFFFF;
693     oldSh = shells[dlg]; shells[dlg] = sh; // bow to reality
694     if (data == 30000) { // cancel
695         PopDown(dlg); 
696     } else
697     if (data == 30001) { // save buttons imply OK
698         if(GenericReadout(currentOption, -1)) PopDown(dlg); // calls OK-proc after full readout, but no popdown if it returns false
699     } else
700
701     if(currentCps && dlg != BrowserDlg) {
702         XtSetArg(args[0], XtNlabel, &name);
703         XtGetValues(w, args, 1);
704         if(currentOption[data].type == SaveButton) GenericReadout(currentOption, -1);
705         snprintf(buf, MSG_SIZ,  "option %s\n", name);
706         SendToProgram(buf, currentCps);
707     } else ((ButtonCallback*) currentOption[data].target)(data);
708
709     shells[dlg] = oldSh; // in case of multiple instances, restore previous (as this one could be popped down now)
710 #endif
711 }
712
713 void
714 TabProc (Widget w, XEvent *event, String *prms, Cardinal *nprms)
715 {   // for transfering focus to the next text-edit
716 #ifdef TODO_GTK
717     Option *opt;
718     for(opt = currentOption; opt->type != EndMark; opt++) {
719         if(opt->handle == w) {
720             while(++opt) {
721                 if(opt->type == EndMark) opt = currentOption; // wrap
722                 if(opt->handle == w) return; // full circle
723                 if(opt->type == TextBox || opt->type == Spin || opt->type == Fractional || opt->type == FileName || opt->type == PathName) {
724                     SetFocus(opt->handle, XtParent(XtParent(XtParent(w))), NULL, 0);
725                     return;
726                 }
727             }
728         }
729     }
730 #endif
731 }
732
733 void
734 WheelProc (Widget w, XEvent *event, String *prms, Cardinal *nprms)
735 {   // for scrolling a widget seen through a viewport with the mouse wheel (ListBox!)
736 #ifdef TODO_GTK
737     int j=0, n = atoi(prms[0]);
738     static char *params[3] = { "", "Continuous", "Proportional" };
739     Arg args[16];
740     float h, top;
741     Widget v;
742     if(!n) { // transient dialogs also use this for list-selection callback
743         n = prms[1][0]-'0';
744         Option *opt=dialogOptions[prms[2][0]-'A'] + n;
745         if(opt->textValue) ((ListBoxCallback*) opt->textValue)(n, SelectedListBoxItem(opt));
746         return;
747     }
748     v = XtNameToWidget(XtParent(w), "vertical");
749     if(!v) return;
750     XtSetArg(args[j], XtNshown, &h); j++;
751     XtSetArg(args[j], XtNtopOfThumb, &top); j++;
752     XtGetValues(v, args, j);
753     top += 0.1f*h*n; if(top < 0.f) top = 0.;
754     XtCallActionProc(v, "StartScroll", event, params+1, 1);
755     XawScrollbarSetThumb(v, top, -1.0);
756     XtCallActionProc(v, "NotifyThumb", event, params, 0);
757 //    XtCallActionProc(w, "NotifyScroll", event, params+2, 1);
758     XtCallActionProc(v, "EndScroll", event, params, 0);
759 #endif
760 }
761
762 static char *oneLiner  =
763    "<Key>Return: redraw-display() \n \
764     <Key>Tab: TabProc() \n ";
765 static char scrollTranslations[] =
766    "<Btn1Up>(2): WheelProc(0 0 A) \n \
767     <Btn4Down>: WheelProc(-1) \n \
768     <Btn5Down>: WheelProc(1) \n ";
769
770 static void
771 SqueezeIntoBox (Option *opt, int nr, int width)
772 {   // size buttons in bar to fit, clipping button names where necessary
773 #ifdef TODO_GTK
774     int i, wtot = 0;
775     Dimension widths[20], oldWidths[20];
776     Arg arg;
777     for(i=1; i<nr; i++) {
778         XtSetArg(arg, XtNwidth, &widths[i]);
779         XtGetValues(opt[i].handle, &arg, 1);
780         wtot +=  oldWidths[i] = widths[i];
781     }
782     opt->min = wtot;
783     if(width <= 0) return;
784     while(wtot > width) {
785         int wmax=0, imax=0;
786         for(i=1; i<nr; i++) if(widths[i] > wmax) wmax = widths[imax=i];
787         widths[imax]--;
788         wtot--;
789     }
790     for(i=1; i<nr; i++) if(widths[i] != oldWidths[i]) {
791         XtSetArg(arg, XtNwidth, widths[i]);
792         XtSetValues(opt[i].handle, &arg, 1);
793     }
794     opt->min = wtot;
795 #endif
796 }
797
798 int
799 SetPositionAndSize (Arg *args, Widget leftNeigbor, Widget topNeigbor, int b, int w, int h, int chaining)
800 {   // sizing and positioning most widgets have in common
801     int j = 0;
802 #ifdef TODO_GTK
803     // first position the widget w.r.t. earlier ones
804     if(chaining & 1) { // same row: position w.r.t. last (on current row) and lastrow
805         XtSetArg(args[j], XtNfromVert, topNeigbor); j++;
806         XtSetArg(args[j], XtNfromHoriz, leftNeigbor); j++;
807     } else // otherwise it goes at left margin (which is default), below the previous element
808         XtSetArg(args[j], XtNfromVert, leftNeigbor),  j++;
809     // arrange chaining ('2'-bit indicates top and bottom chain the same)
810     if((chaining & 14) == 6) XtSetArg(args[j], XtNtop,    XtChainBottom), j++;
811     if((chaining & 14) == 10) XtSetArg(args[j], XtNbottom, XtChainTop ), j++;
812     if(chaining & 4) XtSetArg(args[j], XtNbottom, XtChainBottom ), j++;
813     if(chaining & 8) XtSetArg(args[j], XtNtop,    XtChainTop), j++;
814     if(chaining & 0x10) XtSetArg(args[j], XtNright, XtChainRight), j++;
815     if(chaining & 0x20) XtSetArg(args[j], XtNleft,  XtChainRight), j++;
816     if(chaining & 0x40) XtSetArg(args[j], XtNright, XtChainLeft ), j++;
817     if(chaining & 0x80) XtSetArg(args[j], XtNleft,  XtChainLeft ), j++;
818     // set size (if given)
819     if(w) XtSetArg(args[j], XtNwidth, w), j++;
820     if(h) XtSetArg(args[j], XtNheight, h),  j++;
821     // color
822     if(!appData.monoMode) {
823         if(!b && appData.dialogColor[0]) XtSetArg(args[j], XtNbackground, dialogColor),  j++;
824         if(b == 3 && appData.buttonColor[0]) XtSetArg(args[j], XtNbackground, buttonColor),  j++;
825     }
826     if(b == 3) b = 1;
827     // border
828     XtSetArg(args[j], XtNborderWidth, b);  j++;
829 #endif
830     return j;
831 }
832
833 int
834 GenericPopUp (Option *option, char *title, DialogClass dlgNr, DialogClass parent, int modal, int top)
835 {
836 #ifdef TODO_GTK
837     Arg args[24];
838     Widget popup, layout, dialog=NULL, edit=NULL, form,  last, b_ok, b_cancel, previousPane = NULL, textField = NULL, oldForm, oldLastRow, oldForeLast;
839     Window root, child;
840     int x, y, i, j, height=999, width=1, h, c, w, shrink=FALSE, stack = 0, box, chain;
841     int win_x, win_y, maxWidth, maxTextWidth;
842     unsigned int mask;
843     char def[MSG_SIZ], *msg, engineDlg = (currentCps != NULL && dlgNr != BrowserDlg);
844     static char pane[6] = "paneX";
845     Widget texts[100], forelast = NULL, anchor, widest, lastrow = NULL, browse = NULL;
846     Dimension bWidth = 50;
847
848     if(dlgNr < PromoDlg && shellUp[dlgNr]) return 0; // already up
849     if(dlgNr && dlgNr < PromoDlg && shells[dlgNr]) { // reusable, and used before (but popped down)
850         XtPopup(shells[dlgNr], XtGrabNone);
851         shellUp[dlgNr] = True;
852         return 0;
853     }
854
855     dialogOptions[dlgNr] = option; // make available to callback
856     // post currentOption globally, so Spin and Combo callbacks can already use it
857     // WARNING: this kludge does not work for persistent dialogs, so that these cannot have spin or combo controls!
858     currentOption = option;
859
860     if(engineDlg) { // Settings popup for engine: format through heuristic
861         int n = currentCps->nrOptions;
862         if(n > 50) width = 4; else if(n>24) width = 2; else width = 1;
863         height = n / width + 1;
864         if(n && (currentOption[n-1].type == Button || currentOption[n-1].type == SaveButton)) currentOption[n].min = SAME_ROW; // OK on same line
865         currentOption[n].type = EndMark; currentOption[n].target = NULL; // delimit list by callback-less end mark
866     }
867      i = 0;
868     XtSetArg(args[i], XtNresizable, True); i++;
869     shells[BoardWindow] = shellWidget; parents[dlgNr] = parent;
870
871     if(dlgNr == BoardWindow) popup = shellWidget; else
872     popup = shells[dlgNr] =
873       XtCreatePopupShell(title, !top || !appData.topLevel ? transientShellWidgetClass : topLevelShellWidgetClass,
874                                                            shells[parent], args, i);
875
876     layout =
877       XtCreateManagedWidget(layoutName, formWidgetClass, popup,
878                             layoutArgs, XtNumber(layoutArgs));
879     if(!appData.monoMode && appData.dialogColor[0]) XtSetArg(args[0], XtNbackground, dialogColor);
880     XtSetValues(layout, args, 1);
881
882   for(c=0; c<width; c++) {
883     pane[4] = 'A'+c;
884     form =
885       XtCreateManagedWidget(pane, formWidgetClass, layout,
886                             formArgs, XtNumber(formArgs));
887     j=0;
888     XtSetArg(args[j], stack ? XtNfromVert : XtNfromHoriz, previousPane);  j++;
889     if(!appData.monoMode && appData.dialogColor[0]) XtSetArg(args[j], XtNbackground, dialogColor),  j++;
890     XtSetValues(form, args, j);
891     lastrow = forelast = NULL;
892     previousPane = form;
893
894     last = widest = NULL; anchor = lastrow;
895     for(h=0; h<height || c == width-1; h++) {
896         i = h + c*height;
897         if(option[i].type == EndMark) break;
898         if(option[i].type == -1) continue;
899         lastrow = forelast;
900         forelast = last;
901         switch(option[i].type) {
902           case Fractional:
903             snprintf(def, MSG_SIZ,  "%.2f", *(float*)option[i].target);
904             option[i].value = *(float*)option[i].target;
905             goto tBox;
906           case Spin:
907             if(!engineDlg) option[i].value = *(int*)option[i].target;
908             snprintf(def, MSG_SIZ,  "%d", option[i].value);
909           case TextBox:
910           case FileName:
911           case PathName:
912           tBox:
913             if(option[i].name[0]) { // prefixed by label with option name
914                 j = SetPositionAndSize(args, last, lastrow, 0 /* border */,
915                                        0 /* w */, textHeight /* h */, 0xC0 /* chain to left edge */);
916                 XtSetArg(args[j], XtNjustify, XtJustifyLeft);  j++;
917                 XtSetArg(args[j], XtNlabel, _(option[i].name));  j++;
918                 texts[h] = dialog = XtCreateManagedWidget(option[i].name, labelWidgetClass, form, args, j);
919             } else texts[h] = dialog = NULL; // kludge to position from left margin
920             w = option[i].type == Spin || option[i].type == Fractional ? 70 : option[i].max ? option[i].max : 205;
921             if(option[i].type == FileName || option[i].type == PathName) w -= 55;
922             j = SetPositionAndSize(args, dialog, last, 1 /* border */,
923                                    w /* w */, option[i].type == TextBox ? option[i].value : 0 /* h */, 0x91 /* chain full width */);
924             if(option[i].type == TextBox) { // decorations for multi-line text-edits
925                 if(option[i].min & T_VSCRL) { XtSetArg(args[j], XtNscrollVertical, XawtextScrollAlways);  j++; }
926                 if(option[i].min & T_HSCRL) { XtSetArg(args[j], XtNscrollHorizontal, XawtextScrollAlways);  j++; }
927                 if(option[i].min & T_FILL)  { XtSetArg(args[j], XtNautoFill, True);  j++; }
928                 if(option[i].min & T_WRAP)  { XtSetArg(args[j], XtNwrap, XawtextWrapWord); j++; }
929                 if(option[i].min & T_TOP)   { XtSetArg(args[j], XtNtop, XtChainTop); j++;
930                     if(!option[i].value) {    XtSetArg(args[j], XtNbottom, XtChainTop); j++;
931                                               XtSetValues(dialog, args+j-2, 2);
932                     }
933                 }
934             } else shrink = TRUE;
935             XtSetArg(args[j], XtNeditType, XawtextEdit);  j++;
936             XtSetArg(args[j], XtNuseStringInPlace, False);  j++;
937             XtSetArg(args[j], XtNdisplayCaret, False);  j++;
938             XtSetArg(args[j], XtNresizable, True);  j++;
939             XtSetArg(args[j], XtNinsertPosition, 9999);  j++;
940             XtSetArg(args[j], XtNstring, option[i].type==Spin || option[i].type==Fractional ? def : 
941                                 engineDlg ? option[i].textValue : *(char**)option[i].target);  j++;
942             edit = last;
943             option[i].handle = (void*)
944                 (textField = last = XtCreateManagedWidget("text", asciiTextWidgetClass, form, args, j));
945             XtAddEventHandler(last, ButtonPressMask, False, SetFocus, (XtPointer) popup); // gets focus on mouse click
946             if(option[i].min == 0 || option[i].type != TextBox)
947                 XtOverrideTranslations(last, XtParseTranslationTable(oneLiner)); // standard handler for <Enter> and <Tab>
948
949             if(option[i].type == TextBox || option[i].type == Fractional) break;
950
951             // add increment and decrement controls for spin
952             if(option[i].type == FileName || option[i].type == PathName) {
953                 msg = _("browse"); w = 0; // automatically scale to width of text
954                 j = textHeight ? textHeight : 0;
955             } else {
956                 w = 20; msg = "+"; j = textHeight/2; // spin button
957             }
958             j = SetPositionAndSize(args, last, edit, 3 /* border */,
959                                    w /* w */, j /* h */, 0x31 /* chain to right edge */);
960             edit = XtCreateManagedWidget(msg, commandWidgetClass, form, args, j);
961             XtAddCallback(edit, XtNcallback, SpinCallback, (XtPointer)(intptr_t) i + 256*dlgNr);
962             if(w == 0) browse = edit;
963
964             if(option[i].type != Spin) break;
965
966             j = SetPositionAndSize(args, last, edit, 3 /* border */,
967                                    20 /* w */, textHeight/2 /* h */, 0x31 /* chain to right edge */);
968             XtSetArg(args[j], XtNvertDistance, -1);  j++;
969             last = XtCreateManagedWidget("-", commandWidgetClass, form, args, j);
970             XtAddCallback(last, XtNcallback, SpinCallback, (XtPointer)(intptr_t) i + 256*dlgNr);
971             break;
972           case CheckBox:
973             if(!engineDlg) option[i].value = *(Boolean*)option[i].target; // where checkbox callback uses it
974             j = SetPositionAndSize(args, last, lastrow, 1 /* border */,
975                                    textHeight/2 /* w */, textHeight/2 /* h */, 0xC0 /* chain both to left edge */);
976             XtSetArg(args[j], XtNvertDistance, (textHeight+2)/4 + 3);  j++;
977             XtSetArg(args[j], XtNstate, option[i].value);  j++;
978             lastrow  = last;
979             option[i].handle = (void*)
980                 (last = XtCreateManagedWidget(" ", toggleWidgetClass, form, args, j));
981             j = SetPositionAndSize(args, last, lastrow, 0 /* border */,
982                                    option[i].max /* w */, textHeight /* h */, 0xC1 /* chain */);
983             XtSetArg(args[j], XtNjustify, XtJustifyLeft);  j++;
984             XtSetArg(args[j], XtNlabel, _(option[i].name));  j++;
985             last = XtCreateManagedWidget("label", commandWidgetClass, form, args, j);
986             // make clicking the text toggle checkbox
987             XtAddEventHandler(last, ButtonPressMask, False, CheckCallback, (XtPointer)(intptr_t) i + 256*dlgNr);
988             shrink = TRUE; // following buttons must get text height
989             break;
990           case Label:
991             msg = option[i].name;
992             if(!msg) break;
993             chain = option[i].min;
994             if(chain & SAME_ROW) forelast = lastrow; else shrink = FALSE;
995             j = SetPositionAndSize(args, last, lastrow, (chain & 2) != 0 /* border */,
996                                    option[i].max /* w */, shrink ? textHeight : 0 /* h */, chain | 2 /* chain */);
997 #if ENABLE_NLS
998             if(option[i].choice) XtSetArg(args[j], XtNfontSet, *(XFontSet*)option[i].choice), j++;
999 #else
1000             if(option[i].choice) XtSetArg(args[j], XtNfont, (XFontStruct*)option[i].choice), j++;
1001 #endif
1002             XtSetArg(args[j], XtNresizable, False);  j++;
1003             XtSetArg(args[j], XtNjustify, XtJustifyLeft);  j++;
1004             XtSetArg(args[j], XtNlabel, _(msg));  j++;
1005             option[i].handle = (void*) (last = XtCreateManagedWidget("label", labelWidgetClass, form, args, j));
1006             if(option[i].target) // allow user to specify event handler for button presses
1007                 XtAddEventHandler(last, ButtonPressMask, False, CheckCallback, (XtPointer)(intptr_t) i + 256*dlgNr);
1008             break;
1009           case SaveButton:
1010           case Button:
1011             if(option[i].min & SAME_ROW) {
1012                 chain = 0x31; // 0011.0001 = both left and right side to right edge
1013                 forelast = lastrow;
1014             } else chain = 0, shrink = FALSE;
1015             j = SetPositionAndSize(args, last, lastrow, 3 /* border */,
1016                                    option[i].max /* w */, shrink ? textHeight : 0 /* h */, option[i].min & 0xE | chain /* chain */);
1017             XtSetArg(args[j], XtNlabel, _(option[i].name));  j++;
1018             if(option[i].textValue) { // special for buttons of New Variant dialog
1019                 XtSetArg(args[j], XtNsensitive, appData.noChessProgram || option[i].value < 0
1020                                          || strstr(first.variants, VariantName(option[i].value))); j++;
1021                 XtSetArg(args[j], XtNborderWidth, (gameInfo.variant == option[i].value)+1); j++;
1022             }
1023             option[i].handle = (void*)
1024                 (dialog = last = XtCreateManagedWidget(option[i].name, commandWidgetClass, form, args, j));
1025             if(option[i].choice && ((char*)option[i].choice)[0] == '#' && !engineDlg) { // for the color picker default-reset
1026                 SetColor( *(char**) option[i-1].target, &option[i]);
1027                 XtAddEventHandler(option[i-1].handle, KeyReleaseMask, False, ColorChanged, (XtPointer)(intptr_t) i-1);
1028             }
1029             XtAddCallback(last, XtNcallback, GenericCallback, (XtPointer)(intptr_t) i + (dlgNr<<16)); // invokes user callback
1030             if(option[i].textValue) SetColor( option[i].textValue, &option[i]); // for new-variant buttons
1031             break;
1032           case ComboBox:
1033             j = SetPositionAndSize(args, last, lastrow, 0 /* border */,
1034                                    0 /* w */, textHeight /* h */, 0xC0 /* chain both sides to left edge */);
1035             XtSetArg(args[j], XtNjustify, XtJustifyLeft);  j++;
1036             XtSetArg(args[j], XtNlabel, _(option[i].name));  j++;
1037             texts[h] = dialog = XtCreateManagedWidget(option[i].name, labelWidgetClass, form, args, j);
1038
1039             if(option[i].min & COMBO_CALLBACK) msg = _(option[i].name); else {
1040               if(!engineDlg) SetCurrentComboSelection(option+i);
1041               msg=_(((char**)option[i].choice)[option[i].value]);
1042             }
1043
1044             j = SetPositionAndSize(args, dialog, last, (option[i].min & 2) == 0 /* border */,
1045                                    option[i].max && !engineDlg ? option[i].max : 100 /* w */,
1046                                    textHeight /* h */, 0x91 /* chain */); // same row as its label!
1047             XtSetArg(args[j], XtNmenuName, XtNewString(option[i].name));  j++;
1048             XtSetArg(args[j], XtNlabel, msg);  j++;
1049             shrink = TRUE;
1050             option[i].handle = (void*)
1051                 (last = XtCreateManagedWidget(" ", menuButtonWidgetClass, form, args, j));
1052             CreateComboPopup(last, option + i, i + 256*dlgNr, TRUE, -1);
1053             values[i] = option[i].value;
1054             break;
1055           case ListBox:
1056             // Listbox goes in viewport, as needed for game list
1057             if(option[i].min & SAME_ROW) forelast = lastrow;
1058             j = SetPositionAndSize(args, last, lastrow, 1 /* border */,
1059                                    option[i].max /* w */, option[i].value /* h */, option[i].min /* chain */);
1060             XtSetArg(args[j], XtNresizable, False);  j++;
1061             XtSetArg(args[j], XtNallowVert, True); j++; // scoll direction
1062             last =
1063               XtCreateManagedWidget("viewport", viewportWidgetClass, form, args, j);
1064             j = 0; // now list itself
1065             XtSetArg(args[j], XtNdefaultColumns, 1);  j++;
1066             XtSetArg(args[j], XtNforceColumns, True);  j++;
1067             XtSetArg(args[j], XtNverticalList, True);  j++;
1068             option[i].handle = (void*)
1069                 (edit = XtCreateManagedWidget("list", listWidgetClass, last, args, j));
1070             XawListChange(option[i].handle, option[i].target, 0, 0, True);
1071             XawListHighlight(option[i].handle, 0);
1072             scrollTranslations[25] = '0' + i;
1073             scrollTranslations[27] = 'A' + dlgNr;
1074             XtOverrideTranslations(edit, XtParseTranslationTable(scrollTranslations)); // for mouse-wheel
1075             break;
1076           case Graph:
1077             j = SetPositionAndSize(args, last, lastrow, 0 /* border */,
1078                                    option[i].max /* w */, option[i].value /* h */, option[i].min /* chain */);
1079             option[i].handle = (void*)
1080                 (last = XtCreateManagedWidget("graph", widgetClass, form, args, j));
1081             XtAddEventHandler(last, ExposureMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask, False,
1082                       (XtEventHandler) GraphEventProc, &option[i]); // mandatory user-supplied expose handler
1083             if(option[i].min & SAME_ROW) last = forelast, forelast = lastrow;
1084             option[i].choice = (char**) cairo_image_surface_create (CAIRO_FORMAT_ARGB32, option[i].max, option[i].value); // image buffer
1085             break;
1086           case PopUp: // note: used only after Graph, so 'last' refers to the Graph widget
1087             option[i].handle = (void*) CreateComboPopup(last, option + i, i + 256*dlgNr, TRUE, option[i].value);
1088             break;
1089           case BoxBegin:
1090             if(option[i].min & SAME_ROW) forelast = lastrow;
1091             j = SetPositionAndSize(args, last, lastrow, 0 /* border */,
1092                                    0 /* w */, 0 /* h */, option[i].min /* chain */);
1093             XtSetArg(args[j], XtNorientation, XtorientHorizontal);  j++;
1094             XtSetArg(args[j], XtNvSpace, 0);                        j++;
1095             option[box=i].handle = (void*)
1096                 (last = XtCreateWidget("box", boxWidgetClass, form, args, j));
1097             oldForm = form; form = last; oldLastRow = lastrow; oldForeLast = forelast;
1098             lastrow = NULL; last = NULL;
1099             break;
1100           case DropDown:
1101             j = SetPositionAndSize(args, last, lastrow, 0 /* border */,
1102                                    0 /* w */, 0 /* h */, 1 /* chain (always on same row) */);
1103             forelast = lastrow;
1104             msg = _(option[i].name); // write name on the menu button
1105             XtSetArg(args[j], XtNmenuName, XtNewString(option[i].name));  j++;
1106             XtSetArg(args[j], XtNlabel, msg);  j++;
1107             option[i].handle = (void*)
1108                 (last = XtCreateManagedWidget(option[i].name, menuButtonWidgetClass, form, args, j));
1109             option[i].textValue = (char*) CreateComboPopup(last, option + i, i + 256*dlgNr, FALSE, -1);
1110             break;
1111           case BoxEnd:
1112             XtManageChildren(&form, 1);
1113             SqueezeIntoBox(&option[box], i-box, option[box].max);
1114             if(option[i].target) ((ButtonCallback*)option[i].target)(box); // callback that can make sizing decisions
1115             last = form; lastrow = oldLastRow; form = oldForm; forelast = oldForeLast;
1116             break;
1117           case Break:
1118             width++;
1119             height = i+1;
1120             stack = !(option[i].min & SAME_ROW);
1121             break;
1122         default:
1123             printf("GenericPopUp: unexpected case in switch.\n");
1124             break;
1125         }
1126     }
1127
1128     // make an attempt to align all spins and textbox controls
1129     maxWidth = maxTextWidth = 0;
1130     if(browse != NULL) {
1131         j=0;
1132         XtSetArg(args[j], XtNwidth, &bWidth);  j++;
1133         XtGetValues(browse, args, j);
1134     }
1135     for(h=0; h<height || c == width-1; h++) {
1136         i = h + c*height;
1137         if(option[i].type == EndMark) break;
1138         if(option[i].type == Spin || option[i].type == TextBox || option[i].type == ComboBox
1139                                   || option[i].type == PathName || option[i].type == FileName) {
1140             Dimension w;
1141             if(!texts[h]) continue;
1142             j=0;
1143             XtSetArg(args[j], XtNwidth, &w);  j++;
1144             XtGetValues(texts[h], args, j);
1145             if(option[i].type == Spin) {
1146                 if(w > maxWidth) maxWidth = w;
1147                 widest = texts[h];
1148             } else {
1149                 if(w > maxTextWidth) maxTextWidth = w;
1150                 if(!widest) widest = texts[h];
1151             }
1152         }
1153     }
1154     if(maxTextWidth + 110 < maxWidth)
1155          maxTextWidth = maxWidth - 110;
1156     else maxWidth = maxTextWidth + 110;
1157     for(h=0; h<height || c == width-1; h++) {
1158         i = h + c*height;
1159         if(option[i].type == EndMark) break;
1160         if(!texts[h]) continue; // Note: texts[h] can be undefined (giving errors in valgrind), but then both if's below will be false.
1161         j=0;
1162         if(option[i].type == Spin) {
1163             XtSetArg(args[j], XtNwidth, maxWidth);  j++;
1164             XtSetValues(texts[h], args, j);
1165         } else
1166         if(option[i].type == TextBox || option[i].type == ComboBox || option[i].type == PathName || option[i].type == FileName) {
1167             XtSetArg(args[j], XtNwidth, maxTextWidth);  j++;
1168             XtSetValues(texts[h], args, j);
1169             if(bWidth != 50 && (option[i].type == FileName || option[i].type == PathName)) {
1170                 int tWidth = (option[i].max ? option[i].max : 205) - 5 - bWidth;
1171                 j = 0;
1172                 XtSetArg(args[j], XtNwidth, tWidth);  j++;
1173                 XtSetValues(option[i].handle, args, j);
1174             }
1175         }
1176     }
1177   }
1178
1179     if(option[i].min & SAME_ROW) { // even when OK suppressed this EndMark bit can request chaining of last row to bottom
1180         for(j=i-1; option[j+1].min & SAME_ROW; j--) {
1181             XtSetArg(args[0], XtNtop, XtChainBottom);
1182             XtSetArg(args[1], XtNbottom, XtChainBottom);
1183             XtSetValues(option[j].handle, args, 2);
1184         }
1185         if((option[j].type == TextBox || option[j].type == ListBox) && option[j].name[0] == NULLCHAR) {
1186             Widget w = option[j].handle;
1187             if(option[j].type == ListBox) w = XtParent(w); // for listbox we must chain viewport
1188             XtSetArg(args[0], XtNbottom, XtChainBottom);
1189             XtSetValues(w, args, 1);
1190         }
1191         lastrow = forelast;
1192     } else shrink = FALSE, lastrow = last, last = widest ? widest : dialog;
1193     j = SetPositionAndSize(args, last, anchor ? anchor : lastrow, 3 /* border */,
1194                            0 /* w */, shrink ? textHeight : 0 /* h */, 0x37 /* chain: right, bottom and use both neighbors */);
1195
1196   if(!(option[i].min & NO_OK)) {
1197     option[i].handle = b_ok = XtCreateManagedWidget(_("OK"), commandWidgetClass, form, args, j);
1198     XtAddCallback(b_ok, XtNcallback, GenericCallback, (XtPointer)(intptr_t) (30001 + (dlgNr<<16)));
1199     if(!(option[i].min & NO_CANCEL)) {
1200       XtSetArg(args[1], XtNfromHoriz, b_ok); // overwrites!
1201       b_cancel = XtCreateManagedWidget(_("cancel"), commandWidgetClass, form, args, j);
1202       XtAddCallback(b_cancel, XtNcallback, GenericCallback, (XtPointer)(intptr_t) (30000 + (dlgNr<<16)));
1203     }
1204   }
1205
1206     XtRealizeWidget(popup);
1207     if(dlgNr != BoardWindow) { // assign close button, and position w.r.t. pointer, if not main window
1208         XSetWMProtocols(xDisplay, XtWindow(popup), &wm_delete_window, 1);
1209         snprintf(def, MSG_SIZ, "<Message>WM_PROTOCOLS: GenericPopDown(\"%d\") \n", dlgNr);
1210         XtAugmentTranslations(popup, XtParseTranslationTable(def));
1211         XQueryPointer(xDisplay, xBoardWindow, &root, &child,
1212                         &x, &y, &win_x, &win_y, &mask);
1213
1214         XtSetArg(args[0], XtNx, x - 10);
1215         XtSetArg(args[1], XtNy, y - 30);
1216         XtSetValues(popup, args, 2);
1217     }
1218     XtPopup(popup, modal ? XtGrabExclusive : XtGrabNone);
1219     shellUp[dlgNr]++; // count rather than flag
1220     previous = NULL;
1221     if(textField) SetFocus(textField, popup, (XEvent*) NULL, False);
1222     if(dlgNr && wp[dlgNr] && wp[dlgNr]->width > 0) { // if persistent window-info available, reposition
1223         j = 0;
1224         XtSetArg(args[j], XtNheight, (Dimension) (wp[dlgNr]->height));  j++;
1225         XtSetArg(args[j], XtNwidth,  (Dimension) (wp[dlgNr]->width));  j++;
1226         XtSetArg(args[j], XtNx, (Position) (wp[dlgNr]->x));  j++;
1227         XtSetArg(args[j], XtNy, (Position) (wp[dlgNr]->y));  j++;
1228         XtSetValues(popup, args, j);
1229     }
1230     RaiseWindow(dlgNr);
1231 #endif
1232     return 1; // tells caller he must do initialization (e.g. add specific event handlers)
1233 }
1234
1235
1236 /* function called when the data to Paste is ready */
1237 #ifdef TODO_GTK
1238 static void
1239 SendTextCB (Widget w, XtPointer client_data, Atom *selection,
1240             Atom *type, XtPointer value, unsigned long *len, int *format)
1241 {
1242   char buf[MSG_SIZ], *p = (char*) textOptions[(int)(intptr_t) client_data].choice, *name = (char*) value, *q;
1243   if (value==NULL || *len==0) return; /* nothing selected, abort */
1244   name[*len]='\0';
1245   strncpy(buf, p, MSG_SIZ);
1246   q = strstr(p, "$name");
1247   snprintf(buf + (q-p), MSG_SIZ -(q-p), "%s%s", name, q+5);
1248   SendString(buf);
1249   XtFree(value);
1250 }
1251 #endif
1252
1253 void
1254 SendText (int n)
1255 {
1256 #ifdef TODO_GTK
1257     char *p = (char*) textOptions[n].choice;
1258     if(strstr(p, "$name")) {
1259         XtGetSelectionValue(menuBarWidget,
1260           XA_PRIMARY, XA_STRING,
1261           /* (XtSelectionCallbackProc) */ SendTextCB,
1262           (XtPointer) (intptr_t) n, /* client_data passed to PastePositionCB */
1263           CurrentTime
1264         );
1265     } else SendString(p);
1266 #endif
1267 }
1268
1269 void
1270 SetInsertPos (Option *opt, int pos)
1271 {
1272 #ifdef TODO_GTK
1273     Arg args[16];
1274     XtSetArg(args[0], XtNinsertPosition, pos);
1275     XtSetValues(opt->handle, args, 1);
1276 //    SetFocus(opt->handle, shells[InputBoxDlg], NULL, False); // No idea why this does not work, and the following is needed:
1277 //    XSetInputFocus(xDisplay, XtWindow(opt->handle), RevertToPointerRoot, CurrentTime);
1278 #endif
1279 }
1280
1281 #ifdef TODO_GTK
1282 void
1283 TypeInProc (Widget w, XEvent *event, String *prms, Cardinal *nprms)
1284 {   // can be used as handler for any text edit in any dialog (from GenericPopUp, that is)
1285     int n = prms[0][0] - '0';
1286     Widget sh = XtParent(XtParent(XtParent(w))); // popup shell
1287
1288     if(n<2) { // Enter or Esc typed from primed text widget: treat as if dialog OK or cancel button hit.
1289         int dlgNr; // figure out what the dialog number is by comparing shells (because we must pass it :( )
1290         for(dlgNr=0; dlgNr<NrOfDialogs; dlgNr++) if(shellUp[dlgNr] && shells[dlgNr] == sh)
1291             GenericCallback (w, (XtPointer)(intptr_t) (30000 + n + (dlgNr<<16)), NULL);
1292     }
1293 }
1294 #endif
1295
1296 void
1297 HardSetFocus (Option *opt)
1298 {
1299 #ifdef TODO_GTK
1300     XSetInputFocus(xDisplay, XtWindow(opt->handle), RevertToPointerRoot, CurrentTime);
1301 #endif
1302 }
1303
1304