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