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