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