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