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