Prepare xoptions.c for middle-end changes
[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 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)
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 }
271
272 void
273 FocusOnWidget (Option *opt, DialogClass dlg)
274 {
275     UnCaret();
276     XtSetKeyboardFocus(shells[dlg], opt->handle);
277 }
278
279 void
280 SetIconName (DialogClass dlg, char *name)
281 {
282         Arg args[16];
283         int j = 0;
284         XtSetArg(args[j], XtNiconName, (XtArgVal) name);  j++;
285 //      XtSetArg(args[j], XtNtitle, (XtArgVal) name);  j++;
286         XtSetValues(shells[dlg], args, j);
287 }
288
289 static void
290 CheckCallback (Widget ww, XtPointer client_data, XEvent *event, Boolean *b)
291 {
292     int s, data = (intptr_t) client_data;
293     Option *opt = dialogOptions[data >> 8] + (data & 255);
294
295     if(opt->type == Label) { ((ButtonCallback*) opt->target)(data&255); return; }
296
297     GetWidgetState(opt, &s);
298     SetWidgetState(opt, !s);
299 }
300
301 static void
302 SpinCallback (Widget w, XtPointer client_data, XtPointer call_data)
303 {
304     String name, val;
305     Arg args[16];
306     char buf[MSG_SIZ], *p;
307     int j = 0; // Initialisation is necessary because the text value may be non-numeric causing the scanf conversion to fail
308     int data = (intptr_t) client_data;
309     Option *opt = dialogOptions[data >> 8] + (data & 255);
310
311     XtSetArg(args[0], XtNlabel, &name);
312     XtGetValues(w, args, 1);
313
314     GetWidgetText(opt, &val);
315     sscanf(val, "%d", &j);
316     if (strcmp(name, _("browse")) == 0) {
317         char *q=val, *r;
318         for(r = ""; *q; q++) if(*q == '.') r = q; else if(*q == '/') r = ""; // last dot after last slash
319         if(!strcmp(r, "") && !currentCps && opt->type == FileName && opt->textValue)
320                 r = opt->textValue;
321         Browse(data>>8, opt->name, NULL, r, opt->type == PathName, "", &p, (FILE**) opt);
322         return;
323     } else
324     if (strcmp(name, "+") == 0) {
325         if(++j > opt->max) return;
326     } else
327     if (strcmp(name, "-") == 0) {
328         if(--j < opt->min) return;
329     } else return;
330     snprintf(buf, MSG_SIZ,  "%d", j);
331     SetWidgetText(opt, buf, TransientDlg);
332 }
333
334 static void
335 ComboSelect (Widget w, caddr_t addr, caddr_t index) // callback for all combo items
336 {
337     Arg args[16];
338     Option *opt = dialogOptions[((intptr_t)addr)>>24]; // applicable option list
339     int i = ((intptr_t)addr)>>16 & 255; // option number
340     int j = 0xFFFF & (intptr_t) addr;
341
342     values[i] = j; // store selected value in Option struct, for retrieval at OK
343
344     if(opt[i].type == Graph || opt[i].min & COMBO_CALLBACK && (!currentCps || shellUp[BrowserDlg])) {
345         ((ButtonCallback*) opt[i].target)(i);
346         return;
347     }
348
349     if(opt[i].min & NO_GETTEXT)
350       XtSetArg(args[0], XtNlabel, ((char**)opt[i].choice)[j]);
351     else
352       XtSetArg(args[0], XtNlabel, _(((char**)opt[i].choice)[j]));
353
354     XtSetValues(opt[i].handle, args, 1);
355 }
356
357 Widget
358 CreateMenuItem (Widget menu, char *msg, XtCallbackProc CB, int n)
359 {
360     int j=0;
361     Widget entry;
362     Arg args[16];
363     XtSetArg(args[j], XtNleftMargin, 20);   j++;
364     XtSetArg(args[j], XtNrightMargin, 20);  j++;
365     if(!strcmp(msg, "----")) { XtCreateManagedWidget(msg, smeLineObjectClass, menu, args, j); return NULL; }
366     XtSetArg(args[j], XtNlabel, msg);
367     entry = XtCreateManagedWidget("item", smeBSBObjectClass, menu, args, j+1);
368     XtAddCallback(entry, XtNcallback, CB, (caddr_t)(intptr_t) n);
369     return entry;
370 }
371
372 static Widget
373 CreateComboPopup (Widget parent, Option *opt, int n, int fromList, int def)
374 {   // fromList determines if the item texts are taken from a list of strings, or from a menu table
375     int i;
376     Widget menu, entry;
377     Arg arg;
378     MenuItem *mb = (MenuItem *) opt->choice;
379     char **list = (char **) opt->choice;
380
381     if(list[0] == NULL) return NULL; // avoid empty menus, as they cause crash
382     menu = XtCreatePopupShell(opt->name, simpleMenuWidgetClass, parent, NULL, 0);
383
384     for (i=0; 1; i++) 
385       {
386         char *msg = fromList ? list[i] : mb[i].string;
387         if(!msg) break;
388         entry = CreateMenuItem(menu, opt->min & NO_GETTEXT ? msg : _(msg), (XtCallbackProc) ComboSelect, (n<<16)+i);
389         if(!fromList) mb[i].handle = (void*) entry; // save item ID, for enabling / checkmarking
390         if(i==def) {
391             XtSetArg(arg, XtNpopupOnEntry, entry);
392             XtSetValues(menu, &arg, 1);
393         }
394       }
395       return menu;
396 }
397
398 char moveTypeInTranslations[] =
399     "<Key>Return: TypeInProc(1) \n"
400     "<Key>Escape: TypeInProc(0) \n";
401 extern char filterTranslations[];
402 extern char gameListTranslations[];
403 extern char memoTranslations[];
404
405
406 char *translationTable[] = { // beware: order is essential!
407    historyTranslations, commentTranslations, moveTypeInTranslations, ICSInputTranslations,
408    filterTranslations, gameListTranslations, memoTranslations
409 };
410
411 void
412 AddHandler (Option *opt, int nr)
413 {
414     XtOverrideTranslations(opt->handle, XtParseTranslationTable(translationTable[nr]));
415 }
416
417 //----------------------------Generic dialog --------------------------------------------
418
419 // cloned from Engine Settings dialog (and later merged with it)
420
421 Widget shells[NrOfDialogs];
422 DialogClass parents[NrOfDialogs];
423 WindowPlacement *wp[NrOfDialogs] = { // Beware! Order must correspond to DialogClass enum
424     NULL, &wpComment, &wpTags, NULL, NULL, NULL, NULL, &wpMoveHistory, &wpGameList, &wpEngineOutput, &wpEvalGraph,
425     NULL, NULL, NULL, NULL, /*&wpMain*/ NULL
426 };
427
428 int
429 DialogExists (DialogClass n)
430 {   // accessor for use in back-end
431     return shells[n] != NULL;
432 }
433
434 void
435 RaiseWindow (DialogClass dlg)
436 {
437     static XEvent xev;
438     Window root = RootWindow(xDisplay, DefaultScreen(xDisplay));
439     Atom atom = XInternAtom (xDisplay, "_NET_ACTIVE_WINDOW", False);
440
441     xev.xclient.type = ClientMessage;
442     xev.xclient.serial = 0;
443     xev.xclient.send_event = True;
444     xev.xclient.display = xDisplay;
445     xev.xclient.window = XtWindow(shells[dlg]);
446     xev.xclient.message_type = atom;
447     xev.xclient.format = 32;
448     xev.xclient.data.l[0] = 1;
449     xev.xclient.data.l[1] = CurrentTime;
450
451     XSendEvent (xDisplay,
452           root, False,
453           SubstructureRedirectMask | SubstructureNotifyMask,
454           &xev);
455
456     XFlush(xDisplay); 
457     XSync(xDisplay, False);
458 }
459
460 int
461 PopDown (DialogClass n)
462 {   // pops down any dialog created by GenericPopUp (or returns False if it wasn't up), unmarks any associated marked menu
463     int j;
464     Arg args[10];
465     Dimension windowH, windowW; Position windowX, windowY;
466     if (!shellUp[n] || !shells[n]) return 0;
467     if(n && wp[n]) { // remember position
468         j = 0;
469         XtSetArg(args[j], XtNx, &windowX); j++;
470         XtSetArg(args[j], XtNy, &windowY); j++;
471         XtSetArg(args[j], XtNheight, &windowH); j++;
472         XtSetArg(args[j], XtNwidth, &windowW); j++;
473         XtGetValues(shells[n], args, j);
474         wp[n]->x = windowX;
475         wp[n]->x = windowY;
476         wp[n]->width  = windowW;
477         wp[n]->height = windowH;
478     }
479     previous = NULL;
480     XtPopdown(shells[n]);
481     shellUp[n]--; // count rather than clear
482     if(n == 0 || n >= PromoDlg) XtDestroyWidget(shells[n]), shells[n] = NULL;
483     if(marked[n]) {
484         MarkMenuItem(marked[n], False);
485         marked[n] = NULL;
486     }
487     if(!n && n != BrowserDlg) currentCps = NULL; // if an Engine Settings dialog was up, we must be popping it down now
488     currentOption = dialogOptions[TransientDlg]; // just in case a transient dialog was up (to allow its check and combo callbacks to work)
489     RaiseWindow(parents[n]);
490     if(parents[n] == BoardWindow) XtSetKeyboardFocus(shellWidget, formWidget);
491     return 1;
492 }
493
494 void
495 GenericPopDown (Widget w, XEvent *event, String *prms, Cardinal *nprms)
496 {   // to cause popdown through a translation (Delete Window button!)
497     int dlg = atoi(prms[0]);
498     Widget sh = shells[dlg];
499     if(shellUp[BrowserDlg] && dlg != BrowserDlg || dialogError) return; // prevent closing dialog when it has an open file-browse daughter
500     shells[dlg] = w;
501     PopDown(dlg);
502     shells[dlg] = sh; // restore
503 }
504
505 int
506 AppendText (Option *opt, char *s)
507 {
508     XawTextBlock t;
509     char *v;
510     int len;
511     GetWidgetText(opt, &v);
512     len = strlen(v);
513     t.ptr = s; t.firstPos = 0; t.length = strlen(s); t.format = XawFmt8Bit;
514     XawTextReplace(opt->handle, len, len, &t);
515     return len;
516 }
517
518 void
519 SetColor (char *colorName, Option *box)
520 {       // sets the color of a widget
521         Arg args[5];
522         Pixel buttonColor;
523         XrmValue vFrom, vTo;
524         if (!appData.monoMode) {
525             vFrom.addr = (caddr_t) colorName;
526             vFrom.size = strlen(colorName);
527             XtConvert(shellWidget, XtRString, &vFrom, XtRPixel, &vTo);
528             if (vTo.addr == NULL) {
529                 buttonColor = (Pixel) -1;
530             } else {
531                 buttonColor = *(Pixel *) vTo.addr;
532             }
533         } else buttonColor = timerBackgroundPixel;
534         XtSetArg(args[0], XtNbackground, buttonColor);;
535         XtSetValues(box->handle, args, 1);
536 }
537
538 void
539 ColorChanged (Widget w, XtPointer data, XEvent *event, Boolean *b)
540 {   // for detecting a typed change in color
541     char buf[10];
542     if ( (XLookupString(&(event->xkey), buf, 2, NULL, NULL) == 1) && *buf == '\r' )
543         RefreshColor((int)(intptr_t) data, 0);
544 }
545
546 static void
547 GraphEventProc(Widget widget, caddr_t client_data, XEvent *event)
548 {   // handle expose and mouse events on Graph widget
549     Dimension w, h;
550     Arg args[16];
551     int j, button=10, f=1, sizing=0;
552     Option *opt, *graph = (Option *) client_data;
553     PointerCallback *userHandler = graph->target;
554
555     if (!XtIsRealized(widget)) return;
556
557     switch(event->type) {
558         case Expose: // make handling of expose events generic, just copying from memory buffer (->choice) to display (->textValue)
559             /* Get window size */
560             j = 0;
561             XtSetArg(args[j], XtNwidth, &w); j++;
562             XtSetArg(args[j], XtNheight, &h); j++;
563             XtGetValues(widget, args, j);
564
565             if(w < graph->max || w > graph->max + 1 || h != graph->value) { // use width fudge of 1 pixel
566                 if(((XExposeEvent*)event)->count >= 0) { // suppress sizing on expose for ordered redraw in response to sizing.
567                     sizing = 1;
568                     graph->max = w; graph->value = h; // note: old values are kept if we we don't exceed width fudge
569                 }
570             } else w = graph->max;
571
572             if(sizing && ((XExposeEvent*)event)->count > 0) { graph->max = 0; return; } // don't bother if further exposure is pending during resize
573             if(!graph->textValue || sizing) { // create surfaces of new size for display widget
574                 if(graph->textValue) cairo_surface_destroy((cairo_surface_t *)graph->textValue);
575                 graph->textValue = (char*) cairo_xlib_surface_create(xDisplay, XtWindow(widget), DefaultVisual(xDisplay, 0), w, h);
576             }
577             if(sizing) { // the memory buffer was already created in GenericPopup(),
578                          // to give drawing routines opportunity to use it before first expose event
579                          // (which are only processed when main gets to the event loop, so after all init!)
580                          // so only change when size is no longer good
581                 if(graph->choice) cairo_surface_destroy((cairo_surface_t *) graph->choice);
582                 graph->choice = (char**) cairo_image_surface_create (CAIRO_FORMAT_ARGB32, w, h);
583                 break;
584             }
585             w = ((XExposeEvent*)event)->width;
586             if(((XExposeEvent*)event)->x + w > graph->max) w--; // cut off fudge pixel
587             if(w) ExposeRedraw(graph, ((XExposeEvent*)event)->x, ((XExposeEvent*)event)->y, w, ((XExposeEvent*)event)->height);
588             return;
589         case MotionNotify:
590             f = 0;
591             w = ((XButtonEvent*)event)->x; h = ((XButtonEvent*)event)->y;
592             break;
593         case ButtonRelease:
594             f = -1; // release indicated by negative button numbers
595         case ButtonPress:
596             w = ((XButtonEvent*)event)->x; h = ((XButtonEvent*)event)->y;
597             switch(((XButtonEvent*)event)->button) {
598                 case Button1: button = 1; break;
599                 case Button2: button = 2; break;
600                 case Button3: button = 3; break;
601                 case Button4: button = 4; break;
602                 case Button5: button = 5; break;
603             }
604     }
605     button *= f;
606     opt = userHandler(button, w, h);
607     if(opt) { // user callback specifies a context menu; pop it up
608         XUngrabPointer(xDisplay, CurrentTime);
609         XtCallActionProc(widget, "XawPositionSimpleMenu", event, &(opt->name), 1);
610         XtPopupSpringLoaded(opt->handle);
611     }
612     XSync(xDisplay, False);
613 }
614
615 void
616 GraphExpose (Option *opt, int x, int y, int w, int h)
617 {
618   XExposeEvent e;
619   if(!opt->handle) return;
620   e.x = x; e.y = y; e.width = w; e.height = h; e.count = -1; e.type = Expose; // count = -1: kludge to suppress sizing
621   GraphEventProc(opt->handle, (caddr_t) opt, (XEvent *) &e); // fake expose event
622 }
623
624 static void
625 GenericCallback (Widget w, XtPointer client_data, XtPointer call_data)
626 {   // all Buttons in a dialog (including OK, cancel) invoke this
627     String name;
628     Arg args[16];
629     char buf[MSG_SIZ];
630     int data = (intptr_t) client_data;
631     DialogClass dlg;
632     Widget sh = XtParent(XtParent(XtParent(w))), oldSh;
633
634     currentOption = dialogOptions[dlg=data>>16]; data &= 0xFFFF;
635     oldSh = shells[dlg]; shells[dlg] = sh; // bow to reality
636     if (data == 30000) { // cancel
637         PopDown(dlg); 
638     } else
639     if (data == 30001) { // save buttons imply OK
640         if(GenericReadout(currentOption, -1)) PopDown(dlg); // calls OK-proc after full readout, but no popdown if it returns false
641     } else
642
643     if(currentCps && dlg != BrowserDlg) {
644         XtSetArg(args[0], XtNlabel, &name);
645         XtGetValues(w, args, 1);
646         if(currentOption[data].type == SaveButton) GenericReadout(currentOption, -1);
647         snprintf(buf, MSG_SIZ,  "option %s\n", name);
648         SendToProgram(buf, currentCps);
649     } else ((ButtonCallback*) currentOption[data].target)(data);
650
651     shells[dlg] = oldSh; // in case of multiple instances, restore previous (as this one could be popped down now)
652 }
653
654 void
655 TabProc (Widget w, XEvent *event, String *prms, Cardinal *nprms)
656 {   // for transfering focus to the next text-edit
657     Option *opt;
658     for(opt = currentOption; opt->type != EndMark; opt++) {
659         if(opt->handle == w) {
660             while(++opt) {
661                 if(opt->type == EndMark) opt = currentOption; // wrap
662                 if(opt->handle == w) return; // full circle
663                 if(opt->type == TextBox || opt->type == Spin || opt->type == Fractional || opt->type == FileName || opt->type == PathName) {
664                     SetFocus(opt->handle, XtParent(XtParent(XtParent(w))), NULL, 0);
665                     return;
666                 }
667             }
668         }
669     }
670 }
671
672 void
673 WheelProc (Widget w, XEvent *event, String *prms, Cardinal *nprms)
674 {   // for scrolling a widget seen through a viewport with the mouse wheel (ListBox!)
675     int j=0, n = atoi(prms[0]);
676     static char *params[3] = { "", "Continuous", "Proportional" };
677     Arg args[16];
678     float h, top;
679     Widget v;
680     if(!n) { // transient dialogs also use this for list-selection callback
681         n = prms[1][0]-'0';
682         Option *opt=dialogOptions[prms[2][0]-'A'] + n;
683         if(opt->textValue) ((ListBoxCallback*) opt->textValue)(n, SelectedListBoxItem(opt));
684         return;
685     }
686     v = XtNameToWidget(XtParent(w), "vertical");
687     if(!v) return;
688     XtSetArg(args[j], XtNshown, &h); j++;
689     XtSetArg(args[j], XtNtopOfThumb, &top); j++;
690     XtGetValues(v, args, j);
691     top += 0.1f*h*n; if(top < 0.f) top = 0.;
692     XtCallActionProc(v, "StartScroll", event, params+1, 1);
693     XawScrollbarSetThumb(v, top, -1.0);
694     XtCallActionProc(v, "NotifyThumb", event, params, 0);
695 //    XtCallActionProc(w, "NotifyScroll", event, params+2, 1);
696     XtCallActionProc(v, "EndScroll", event, params, 0);
697 }
698
699 static char *oneLiner  =
700    "<Key>Return: redraw-display() \n \
701     <Key>Tab: TabProc() \n ";
702 static char scrollTranslations[] =
703    "<Btn1Up>(2): WheelProc(0 0 A) \n \
704     <Btn4Down>: WheelProc(-1) \n \
705     <Btn5Down>: WheelProc(1) \n ";
706
707 static void
708 SqueezeIntoBox (Option *opt, int nr, int width)
709 {   // size buttons in bar to fit, clipping button names where necessary
710     int i, wtot = 0;
711     Dimension widths[20], oldWidths[20];
712     Arg arg;
713     for(i=1; i<nr; i++) {
714         XtSetArg(arg, XtNwidth, &widths[i]);
715         XtGetValues(opt[i].handle, &arg, 1);
716         wtot +=  oldWidths[i] = widths[i];
717     }
718     opt->min = wtot;
719     if(width <= 0) return;
720     while(wtot > width) {
721         int wmax=0, imax=0;
722         for(i=1; i<nr; i++) if(widths[i] > wmax) wmax = widths[imax=i];
723         widths[imax]--;
724         wtot--;
725     }
726     for(i=1; i<nr; i++) if(widths[i] != oldWidths[i]) {
727         XtSetArg(arg, XtNwidth, widths[i]);
728         XtSetValues(opt[i].handle, &arg, 1);
729     }
730     opt->min = wtot;
731 }
732
733 int
734 SetPositionAndSize (Arg *args, Widget leftNeigbor, Widget topNeigbor, int b, int w, int h, int chaining)
735 {   // sizing and positioning most widgets have in common
736     int j = 0;
737     // first position the widget w.r.t. earlier ones
738     if(chaining & 1) { // same row: position w.r.t. last (on current row) and lastrow
739         XtSetArg(args[j], XtNfromVert, topNeigbor); j++;
740         XtSetArg(args[j], XtNfromHoriz, leftNeigbor); j++;
741     } else // otherwise it goes at left margin (which is default), below the previous element
742         XtSetArg(args[j], XtNfromVert, leftNeigbor),  j++;
743     // arrange chaining ('2'-bit indicates top and bottom chain the same)
744     if((chaining & 14) == 6) XtSetArg(args[j], XtNtop,    XtChainBottom), j++;
745     if((chaining & 14) == 10) XtSetArg(args[j], XtNbottom, XtChainTop ), j++;
746     if(chaining & 4) XtSetArg(args[j], XtNbottom, XtChainBottom ), j++;
747     if(chaining & 8) XtSetArg(args[j], XtNtop,    XtChainTop), j++;
748     if(chaining & 0x10) XtSetArg(args[j], XtNright, XtChainRight), j++;
749     if(chaining & 0x20) XtSetArg(args[j], XtNleft,  XtChainRight), j++;
750     if(chaining & 0x40) XtSetArg(args[j], XtNright, XtChainLeft ), j++;
751     if(chaining & 0x80) XtSetArg(args[j], XtNleft,  XtChainLeft ), j++;
752     // set size (if given)
753     if(w) XtSetArg(args[j], XtNwidth, w), j++;
754     if(h) XtSetArg(args[j], XtNheight, h),  j++;
755     // color
756     if(!appData.monoMode) {
757         if(!b && appData.dialogColor[0]) XtSetArg(args[j], XtNbackground, dialogColor),  j++;
758         if(b == 3 && appData.buttonColor[0]) XtSetArg(args[j], XtNbackground, buttonColor),  j++;
759     }
760     if(b == 3) b = 1;
761     // border
762     XtSetArg(args[j], XtNborderWidth, b);  j++;
763     return j;
764 }
765
766 int
767 GenericPopUp (Option *option, char *title, DialogClass dlgNr, DialogClass parent, int modal, int top)
768 {
769     Arg args[24];
770     Widget popup, layout, dialog=NULL, edit=NULL, form,  last, b_ok, b_cancel, previousPane = NULL, textField = NULL, oldForm, oldLastRow, oldForeLast;
771     Window root, child;
772     int x, y, i, j, height=999, width=1, h, c, w, shrink=FALSE, stack = 0, box, chain;
773     int win_x, win_y, maxWidth, maxTextWidth;
774     unsigned int mask;
775     char def[MSG_SIZ], *msg, engineDlg = (currentCps != NULL && dlgNr != BrowserDlg);
776     static char pane[6] = "paneX";
777     Widget texts[100], forelast = NULL, anchor, widest, lastrow = NULL, browse = NULL;
778     Dimension bWidth = 50;
779
780     if(dlgNr < PromoDlg && shellUp[dlgNr]) return 0; // already up
781     if(dlgNr && dlgNr < PromoDlg && shells[dlgNr]) { // reusable, and used before (but popped down)
782         XtPopup(shells[dlgNr], XtGrabNone);
783         shellUp[dlgNr] = True;
784         return 0;
785     }
786
787     dialogOptions[dlgNr] = option; // make available to callback
788     // post currentOption globally, so Spin and Combo callbacks can already use it
789     // WARNING: this kludge does not work for persistent dialogs, so that these cannot have spin or combo controls!
790     currentOption = option;
791
792     if(engineDlg) { // Settings popup for engine: format through heuristic
793         int n = currentCps->nrOptions;
794         if(!n) { DisplayNote(_("Engine has no options")); currentCps = NULL; return 0; }
795         if(n > 50) width = 4; else if(n>24) width = 2; else width = 1;
796         height = n / width + 1;
797         if(n && (currentOption[n-1].type == Button || currentOption[n-1].type == SaveButton)) currentOption[n].min = SAME_ROW; // OK on same line
798         currentOption[n].type = EndMark; currentOption[n].target = NULL; // delimit list by callback-less end mark
799     }
800      i = 0;
801     XtSetArg(args[i], XtNresizable, True); i++;
802     shells[BoardWindow] = shellWidget; parents[dlgNr] = parent;
803
804     if(dlgNr == BoardWindow) popup = shellWidget; else
805     popup = shells[dlgNr] =
806       XtCreatePopupShell(title, !top || !appData.topLevel ? transientShellWidgetClass : topLevelShellWidgetClass,
807                                                            shells[parent], args, i);
808
809     layout =
810       XtCreateManagedWidget(layoutName, formWidgetClass, popup,
811                             layoutArgs, XtNumber(layoutArgs));
812     if(!appData.monoMode && appData.dialogColor[0]) XtSetArg(args[0], XtNbackground, dialogColor);
813     XtSetValues(layout, args, 1);
814
815   for(c=0; c<width; c++) {
816     pane[4] = 'A'+c;
817     form =
818       XtCreateManagedWidget(pane, formWidgetClass, layout,
819                             formArgs, XtNumber(formArgs));
820     j=0;
821     XtSetArg(args[j], stack ? XtNfromVert : XtNfromHoriz, previousPane);  j++;
822     if(!appData.monoMode && appData.dialogColor[0]) XtSetArg(args[j], XtNbackground, dialogColor),  j++;
823     XtSetValues(form, args, j);
824     lastrow = forelast = NULL;
825     previousPane = form;
826
827     last = widest = NULL; anchor = lastrow;
828     for(h=0; h<height || c == width-1; h++) {
829         i = h + c*height;
830         if(option[i].type == EndMark) break;
831         if(option[i].type == -1) continue;
832         lastrow = forelast;
833         forelast = last;
834         switch(option[i].type) {
835           case Fractional:
836             snprintf(def, MSG_SIZ,  "%.2f", *(float*)option[i].target);
837             option[i].value = *(float*)option[i].target;
838             goto tBox;
839           case Spin:
840             if(!engineDlg) option[i].value = *(int*)option[i].target;
841             snprintf(def, MSG_SIZ,  "%d", option[i].value);
842           case TextBox:
843           case FileName:
844           case PathName:
845           tBox:
846             if(option[i].name[0]) { // prefixed by label with option name
847                 j = SetPositionAndSize(args, last, lastrow, 0 /* border */,
848                                        0 /* w */, textHeight /* h */, 0xC0 /* chain to left edge */);
849                 XtSetArg(args[j], XtNjustify, XtJustifyLeft);  j++;
850                 XtSetArg(args[j], XtNlabel, _(option[i].name));  j++;
851                 texts[h] = dialog = XtCreateManagedWidget(option[i].name, labelWidgetClass, form, args, j);
852             } else texts[h] = dialog = NULL; // kludge to position from left margin
853             w = option[i].type == Spin || option[i].type == Fractional ? 70 : option[i].max ? option[i].max : 205;
854             if(option[i].type == FileName || option[i].type == PathName) w -= 55;
855             j = SetPositionAndSize(args, dialog, last, 1 /* border */,
856                                    w /* w */, option[i].type == TextBox ? option[i].value : 0 /* h */, 0x91 /* chain full width */);
857             if(option[i].type == TextBox) { // decorations for multi-line text-edits
858                 if(option[i].min & T_VSCRL) { XtSetArg(args[j], XtNscrollVertical, XawtextScrollAlways);  j++; }
859                 if(option[i].min & T_HSCRL) { XtSetArg(args[j], XtNscrollHorizontal, XawtextScrollAlways);  j++; }
860                 if(option[i].min & T_FILL)  { XtSetArg(args[j], XtNautoFill, True);  j++; }
861                 if(option[i].min & T_WRAP)  { XtSetArg(args[j], XtNwrap, XawtextWrapWord); j++; }
862                 if(option[i].min & T_TOP)   { XtSetArg(args[j], XtNtop, XtChainTop); j++;
863                     if(!option[i].value) {    XtSetArg(args[j], XtNbottom, XtChainTop); j++;
864                                               XtSetValues(dialog, args+j-2, 2);
865                     }
866                 }
867             } else shrink = TRUE;
868             XtSetArg(args[j], XtNeditType, XawtextEdit);  j++;
869             XtSetArg(args[j], XtNuseStringInPlace, False);  j++;
870             XtSetArg(args[j], XtNdisplayCaret, False);  j++;
871             XtSetArg(args[j], XtNresizable, True);  j++;
872             XtSetArg(args[j], XtNinsertPosition, 9999);  j++;
873             XtSetArg(args[j], XtNstring, option[i].type==Spin || option[i].type==Fractional ? def : 
874                                 engineDlg ? option[i].textValue : *(char**)option[i].target);  j++;
875             edit = last;
876             option[i].handle = (void*)
877                 (textField = last = XtCreateManagedWidget("text", asciiTextWidgetClass, form, args, j));
878             XtAddEventHandler(last, ButtonPressMask, False, SetFocus, (XtPointer) popup); // gets focus on mouse click
879             if(option[i].min == 0 || option[i].type != TextBox)
880                 XtOverrideTranslations(last, XtParseTranslationTable(oneLiner)); // standard handler for <Enter> and <Tab>
881
882             if(option[i].type == TextBox || option[i].type == Fractional) break;
883
884             // add increment and decrement controls for spin
885             if(option[i].type == FileName || option[i].type == PathName) {
886                 msg = _("browse"); w = 0; // automatically scale to width of text
887                 j = textHeight ? textHeight : 0;
888             } else {
889                 w = 20; msg = "+"; j = textHeight/2; // spin button
890             }
891             j = SetPositionAndSize(args, last, edit, 3 /* border */,
892                                    w /* w */, j /* h */, 0x31 /* chain to right edge */);
893             edit = XtCreateManagedWidget(msg, commandWidgetClass, form, args, j);
894             XtAddCallback(edit, XtNcallback, SpinCallback, (XtPointer)(intptr_t) i + 256*dlgNr);
895             if(w == 0) browse = edit;
896
897             if(option[i].type != Spin) break;
898
899             j = SetPositionAndSize(args, last, edit, 3 /* border */,
900                                    20 /* w */, textHeight/2 /* h */, 0x31 /* chain to right edge */);
901             XtSetArg(args[j], XtNvertDistance, -1);  j++;
902             last = XtCreateManagedWidget("-", commandWidgetClass, form, args, j);
903             XtAddCallback(last, XtNcallback, SpinCallback, (XtPointer)(intptr_t) i + 256*dlgNr);
904             break;
905           case CheckBox:
906             if(!engineDlg) option[i].value = *(Boolean*)option[i].target; // where checkbox callback uses it
907             j = SetPositionAndSize(args, last, lastrow, 1 /* border */,
908                                    textHeight/2 /* w */, textHeight/2 /* h */, 0xC0 /* chain both to left edge */);
909             XtSetArg(args[j], XtNvertDistance, (textHeight+2)/4 + 3);  j++;
910             XtSetArg(args[j], XtNstate, option[i].value);  j++;
911             lastrow  = last;
912             option[i].handle = (void*)
913                 (last = XtCreateManagedWidget(" ", toggleWidgetClass, form, args, j));
914             j = SetPositionAndSize(args, last, lastrow, 0 /* border */,
915                                    option[i].max /* w */, textHeight /* h */, 0xC1 /* chain */);
916             XtSetArg(args[j], XtNjustify, XtJustifyLeft);  j++;
917             XtSetArg(args[j], XtNlabel, _(option[i].name));  j++;
918             last = XtCreateManagedWidget("label", commandWidgetClass, form, args, j);
919             // make clicking the text toggle checkbox
920             XtAddEventHandler(last, ButtonPressMask, False, CheckCallback, (XtPointer)(intptr_t) i + 256*dlgNr);
921             shrink = TRUE; // following buttons must get text height
922             break;
923           case Icon:
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 BarBegin:
1024           case BoxBegin:
1025             if(option[i].min & SAME_ROW) forelast = lastrow;
1026             j = SetPositionAndSize(args, last, lastrow, 0 /* border */,
1027                                    0 /* w */, 0 /* h */, option[i].min /* chain */);
1028             XtSetArg(args[j], XtNorientation, XtorientHorizontal);  j++;
1029             XtSetArg(args[j], XtNvSpace, 0);                        j++;
1030             option[box=i].handle = (void*)
1031                 (last = XtCreateWidget("box", boxWidgetClass, form, args, j));
1032             oldForm = form; form = last; oldLastRow = lastrow; oldForeLast = forelast;
1033             lastrow = NULL; last = NULL;
1034             break;
1035           case DropDown:
1036             j = SetPositionAndSize(args, last, lastrow, 0 /* border */,
1037                                    0 /* w */, 0 /* h */, 1 /* chain (always on same row) */);
1038             forelast = lastrow;
1039             msg = _(option[i].name); // write name on the menu button
1040             XtSetArg(args[j], XtNmenuName, XtNewString(option[i].name));  j++;
1041             XtSetArg(args[j], XtNlabel, msg);  j++;
1042             option[i].handle = (void*)
1043                 (last = XtCreateManagedWidget(option[i].name, menuButtonWidgetClass, form, args, j));
1044             option[i].textValue = (char*) CreateComboPopup(last, option + i, i + 256*dlgNr, FALSE, -1);
1045             break;
1046           case BarEnd:
1047           case BoxEnd:
1048             XtManageChildren(&form, 1);
1049             SqueezeIntoBox(&option[box], i-box, option[box].max);
1050             if(option[i].target) ((ButtonCallback*)option[i].target)(box); // callback that can make sizing decisions
1051             last = form; lastrow = oldLastRow; form = oldForm; forelast = oldForeLast;
1052             break;
1053           case Break:
1054             width++;
1055             height = i+1;
1056             stack = !(option[i].min & SAME_ROW);
1057             break;
1058         default:
1059             printf("GenericPopUp: unexpected case in switch.\n");
1060             break;
1061         }
1062     }
1063
1064     // make an attempt to align all spins and textbox controls
1065     maxWidth = maxTextWidth = 0;
1066     if(browse != NULL) {
1067         j=0;
1068         XtSetArg(args[j], XtNwidth, &bWidth);  j++;
1069         XtGetValues(browse, args, j);
1070     }
1071     for(h=0; h<height || c == width-1; h++) {
1072         i = h + c*height;
1073         if(option[i].type == EndMark) break;
1074         if(option[i].type == Spin || option[i].type == TextBox || option[i].type == ComboBox
1075                                   || option[i].type == PathName || option[i].type == FileName) {
1076             Dimension w;
1077             if(!texts[h]) continue;
1078             j=0;
1079             XtSetArg(args[j], XtNwidth, &w);  j++;
1080             XtGetValues(texts[h], args, j);
1081             if(option[i].type == Spin) {
1082                 if(w > maxWidth) maxWidth = w;
1083                 widest = texts[h];
1084             } else {
1085                 if(w > maxTextWidth) maxTextWidth = w;
1086                 if(!widest) widest = texts[h];
1087             }
1088         }
1089     }
1090     if(maxTextWidth + 110 < maxWidth)
1091          maxTextWidth = maxWidth - 110;
1092     else maxWidth = maxTextWidth + 110;
1093     for(h=0; h<height || c == width-1; h++) {
1094         i = h + c*height;
1095         if(option[i].type == EndMark) break;
1096         if(!texts[h]) continue; // Note: texts[h] can be undefined (giving errors in valgrind), but then both if's below will be false.
1097         j=0;
1098         if(option[i].type == Spin) {
1099             XtSetArg(args[j], XtNwidth, maxWidth);  j++;
1100             XtSetValues(texts[h], args, j);
1101         } else
1102         if(option[i].type == TextBox || option[i].type == ComboBox || option[i].type == PathName || option[i].type == FileName) {
1103             XtSetArg(args[j], XtNwidth, maxTextWidth);  j++;
1104             XtSetValues(texts[h], args, j);
1105             if(bWidth != 50 && (option[i].type == FileName || option[i].type == PathName)) {
1106                 int tWidth = (option[i].max ? option[i].max : 205) - 5 - bWidth;
1107                 j = 0;
1108                 XtSetArg(args[j], XtNwidth, tWidth);  j++;
1109                 XtSetValues(option[i].handle, args, j);
1110             }
1111         }
1112     }
1113   }
1114
1115     if(option[i].min & SAME_ROW) { // even when OK suppressed this EndMark bit can request chaining of last row to bottom
1116         for(j=i-1; option[j+1].min & SAME_ROW; j--) {
1117             XtSetArg(args[0], XtNtop, XtChainBottom);
1118             XtSetArg(args[1], XtNbottom, XtChainBottom);
1119             XtSetValues(option[j].handle, args, 2);
1120         }
1121         if((option[j].type == TextBox || option[j].type == ListBox) && option[j].name[0] == NULLCHAR) {
1122             Widget w = option[j].handle;
1123             if(option[j].type == ListBox) w = XtParent(w); // for listbox we must chain viewport
1124             XtSetArg(args[0], XtNbottom, XtChainBottom);
1125             XtSetValues(w, args, 1);
1126         }
1127         lastrow = forelast;
1128     } else shrink = FALSE, lastrow = last, last = widest ? widest : dialog;
1129     j = SetPositionAndSize(args, last, anchor ? anchor : lastrow, 3 /* border */,
1130                            0 /* w */, shrink ? textHeight : 0 /* h */, 0x37 /* chain: right, bottom and use both neighbors */);
1131
1132   if(!(option[i].min & NO_OK)) {
1133     option[i].handle = b_ok = XtCreateManagedWidget(_("OK"), commandWidgetClass, form, args, j);
1134     XtAddCallback(b_ok, XtNcallback, GenericCallback, (XtPointer)(intptr_t) (30001 + (dlgNr<<16)));
1135     if(!(option[i].min & NO_CANCEL)) {
1136       XtSetArg(args[1], XtNfromHoriz, b_ok); // overwrites!
1137       b_cancel = XtCreateManagedWidget(_("cancel"), commandWidgetClass, form, args, j);
1138       XtAddCallback(b_cancel, XtNcallback, GenericCallback, (XtPointer)(intptr_t) (30000 + (dlgNr<<16)));
1139     }
1140   }
1141
1142     XtRealizeWidget(popup);
1143     if(dlgNr != BoardWindow) { // assign close button, and position w.r.t. pointer, if not main window
1144         XSetWMProtocols(xDisplay, XtWindow(popup), &wm_delete_window, 1);
1145         snprintf(def, MSG_SIZ, "<Message>WM_PROTOCOLS: GenericPopDown(\"%d\") \n", dlgNr);
1146         XtAugmentTranslations(popup, XtParseTranslationTable(def));
1147         XQueryPointer(xDisplay, xBoardWindow, &root, &child,
1148                         &x, &y, &win_x, &win_y, &mask);
1149
1150         XtSetArg(args[0], XtNx, x - 10);
1151         XtSetArg(args[1], XtNy, y - 30);
1152         XtSetValues(popup, args, 2);
1153     }
1154     XtPopup(popup, modal ? XtGrabExclusive : XtGrabNone);
1155     shellUp[dlgNr]++; // count rather than flag
1156     previous = NULL;
1157     if(textField) SetFocus(textField, popup, (XEvent*) NULL, False);
1158     if(dlgNr && wp[dlgNr] && wp[dlgNr]->width > 0) { // if persistent window-info available, reposition
1159         j = 0;
1160         XtSetArg(args[j], XtNheight, (Dimension) (wp[dlgNr]->height));  j++;
1161         XtSetArg(args[j], XtNwidth,  (Dimension) (wp[dlgNr]->width));  j++;
1162         XtSetArg(args[j], XtNx, (Position) (wp[dlgNr]->x));  j++;
1163         XtSetArg(args[j], XtNy, (Position) (wp[dlgNr]->y));  j++;
1164         XtSetValues(popup, args, j);
1165     }
1166     RaiseWindow(dlgNr);
1167     return 1; // tells caller he must do initialization (e.g. add specific event handlers)
1168 }
1169
1170
1171 /* function called when the data to Paste is ready */
1172 static void
1173 SendTextCB (Widget w, XtPointer client_data, Atom *selection,
1174             Atom *type, XtPointer value, unsigned long *len, int *format)
1175 {
1176   char buf[MSG_SIZ], *p = (char*) textOptions[(int)(intptr_t) client_data].choice, *name = (char*) value, *q;
1177   if (value==NULL || *len==0) return; /* nothing selected, abort */
1178   name[*len]='\0';
1179   strncpy(buf, p, MSG_SIZ);
1180   q = strstr(p, "$name");
1181   snprintf(buf + (q-p), MSG_SIZ -(q-p), "%s%s", name, q+5);
1182   SendString(buf);
1183   XtFree(value);
1184 }
1185
1186 void
1187 SendText (int n)
1188 {
1189     char *p = (char*) textOptions[n].choice;
1190     if(strstr(p, "$name")) {
1191         XtGetSelectionValue(menuBarWidget,
1192           XA_PRIMARY, XA_STRING,
1193           /* (XtSelectionCallbackProc) */ SendTextCB,
1194           (XtPointer) (intptr_t) n, /* client_data passed to PastePositionCB */
1195           CurrentTime
1196         );
1197     } else SendString(p);
1198 }
1199
1200 void
1201 SetInsertPos (Option *opt, int pos)
1202 {
1203     Arg args[16];
1204     XtSetArg(args[0], XtNinsertPosition, pos);
1205     XtSetValues(opt->handle, args, 1);
1206 //    SetFocus(opt->handle, shells[InputBoxDlg], NULL, False); // No idea why this does not work, and the following is needed:
1207 //    XSetInputFocus(xDisplay, XtWindow(opt->handle), RevertToPointerRoot, CurrentTime);
1208 }
1209
1210 void
1211 TypeInProc (Widget w, XEvent *event, String *prms, Cardinal *nprms)
1212 {   // can be used as handler for any text edit in any dialog (from GenericPopUp, that is)
1213     int n = prms[0][0] - '0';
1214     Widget sh = XtParent(XtParent(XtParent(w))); // popup shell
1215
1216     if(n<2) { // Enter or Esc typed from primed text widget: treat as if dialog OK or cancel button hit.
1217         int dlgNr; // figure out what the dialog number is by comparing shells (because we must pass it :( )
1218         for(dlgNr=0; dlgNr<NrOfDialogs; dlgNr++) if(shellUp[dlgNr] && shells[dlgNr] == sh)
1219             GenericCallback (w, (XtPointer)(intptr_t) (30000 + n + (dlgNr<<16)), NULL);
1220     }
1221 }
1222
1223 void
1224 HardSetFocus (Option *opt)
1225 {
1226     XSetInputFocus(xDisplay, XtWindow(opt->handle), RevertToPointerRoot, CurrentTime);
1227 }
1228
1229 void
1230 FileNamePopUpGTK(char *label, char *def, char *filter, FileProc proc, Boolean pathFlag, char *openMode, char **openName, FILE **openFP)
1231 {
1232     Browse(BoardWindow, label, (def[0] ? def : NULL), filter, False, openMode, openName, openFP);
1233 }
1234