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