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