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