1c711bbde034b7ab1f7cfa0de4f7be31bf2fb782
[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     // border
680     XtSetArg(args[j], XtNborderWidth, b);  j++;
681     return j;
682 }
683
684 int
685 GenericPopUp (Option *option, char *title, DialogClass dlgNr, DialogClass parent, int modal, int top)
686 {
687     Arg args[24];
688     Widget popup, layout, dialog=NULL, edit=NULL, form,  last, b_ok, b_cancel, previousPane = NULL, textField = NULL, oldForm, oldLastRow, oldForeLast;
689     Window root, child;
690     int x, y, i, j, height=999, width=1, h, c, w, shrink=FALSE, stack = 0, box, chain;
691     int win_x, win_y, maxWidth, maxTextWidth;
692     unsigned int mask;
693     char def[MSG_SIZ], *msg;
694     static char pane[6] = "paneX";
695     Widget texts[100], forelast = NULL, anchor, widest, lastrow = NULL, browse = NULL;
696     Dimension bWidth = 50, m;
697
698     if(dlgNr < PromoDlg && shellUp[dlgNr]) return 0; // already up
699     if(dlgNr && dlgNr < PromoDlg && shells[dlgNr]) { // reusable, and used before (but popped down)
700         XtPopup(shells[dlgNr], XtGrabNone);
701         shellUp[dlgNr] = True;
702         return 0;
703     }
704
705     dialogOptions[dlgNr] = option; // make available to callback
706     // post currentOption globally, so Spin and Combo callbacks can already use it
707     // WARNING: this kludge does not work for persistent dialogs, so that these cannot have spin or combo controls!
708     currentOption = option;
709
710     if(currentCps) { // Settings popup for engine: format through heuristic
711         int n = currentCps->nrOptions;
712         if(!n) { DisplayNote(_("Engine has no options")); currentCps = NULL; return 0; }
713         if(n > 50) width = 4; else if(n>24) width = 2; else width = 1;
714         height = n / width + 1;
715         if(n && (currentOption[n-1].type == Button || currentOption[n-1].type == SaveButton)) currentOption[n].min = SAME_ROW; // OK on same line
716         currentOption[n].type = EndMark; currentOption[n].target = NULL; // delimit list by callback-less end mark
717     }
718      i = 0;
719     XtSetArg(args[i], XtNresizable, True); i++;
720     shells[BoardWindow] = shellWidget; parents[dlgNr] = parent;
721
722     popup = shells[dlgNr] =
723       XtCreatePopupShell(title, !top || !appData.topLevel ? transientShellWidgetClass : topLevelShellWidgetClass,
724                                                            shells[parent], args, i);
725
726     layout =
727       XtCreateManagedWidget(layoutName, formWidgetClass, popup,
728                             layoutArgs, XtNumber(layoutArgs));
729   for(c=0; c<width; c++) {
730     pane[4] = 'A'+c;
731     form =
732       XtCreateManagedWidget(pane, formWidgetClass, layout,
733                             formArgs, XtNumber(formArgs));
734     j=0;
735     XtSetArg(args[j], stack ? XtNfromVert : XtNfromHoriz, previousPane);  j++;
736     XtSetValues(form, args, j);
737     lastrow = forelast = NULL;
738     previousPane = form;
739
740     last = widest = NULL; anchor = lastrow;
741     for(h=0; h<height || c == width-1; h++) {
742         i = h + c*height;
743         if(option[i].type == EndMark) break;
744         if(option[i].type == -1) continue;
745         lastrow = forelast;
746         forelast = last;
747         switch(option[i].type) {
748           case Fractional:
749             snprintf(def, MSG_SIZ,  "%.2f", *(float*)option[i].target);
750             option[i].value = *(float*)option[i].target;
751             goto tBox;
752           case Spin:
753             if(!currentCps) option[i].value = *(int*)option[i].target;
754             snprintf(def, MSG_SIZ,  "%d", option[i].value);
755           case TextBox:
756           case FileName:
757           case PathName:
758           tBox:
759             if(option[i].name[0]) { // prefixed by label with option name
760                 j = SetPositionAndSize(args, last, lastrow, 0 /* border */,
761                                        0 /* w */, textHeight /* h */, 0xC0 /* chain to left edge */);
762                 XtSetArg(args[j], XtNjustify, XtJustifyLeft);  j++;
763                 XtSetArg(args[j], XtNlabel, _(option[i].name));  j++;
764                 texts[h] = dialog = XtCreateManagedWidget(option[i].name, labelWidgetClass, form, args, j);
765             } else texts[h] = dialog = NULL; // kludge to position from left margin
766             w = option[i].type == Spin || option[i].type == Fractional ? 70 : option[i].max ? option[i].max : 205;
767             if(option[i].type == FileName || option[i].type == PathName) w -= 55;
768             j = SetPositionAndSize(args, dialog, last, 1 /* border */,
769                                    w /* w */, option[i].type == TextBox ? option[i].value : 0 /* h */, 0x91 /* chain full width */);
770             if(option[i].type == TextBox && option[i].value) { // decorations for multi-line text-edits
771                 if(option[i].min & T_VSCRL) { XtSetArg(args[j], XtNscrollVertical, XawtextScrollAlways);  j++; }
772                 if(option[i].min & T_HSCRL) { XtSetArg(args[j], XtNscrollHorizontal, XawtextScrollAlways);  j++; }
773                 if(option[i].min & T_FILL)  { XtSetArg(args[j], XtNautoFill, True);  j++; }
774                 if(option[i].min & T_WRAP)  { XtSetArg(args[j], XtNwrap, XawtextWrapWord); j++; }
775                 if(option[i].min & T_TOP)   { XtSetArg(args[j], XtNtop, XtChainTop); j++; }
776             } else shrink = TRUE;
777             XtSetArg(args[j], XtNeditType, XawtextEdit);  j++;
778             XtSetArg(args[j], XtNuseStringInPlace, False);  j++;
779             XtSetArg(args[j], XtNdisplayCaret, False);  j++;
780             XtSetArg(args[j], XtNresizable, True);  j++;
781             XtSetArg(args[j], XtNinsertPosition, 9999);  j++;
782             XtSetArg(args[j], XtNstring, option[i].type==Spin || option[i].type==Fractional ? def : 
783                                 currentCps ? option[i].textValue : *(char**)option[i].target);  j++;
784             edit = last;
785             option[i].handle = (void*)
786                 (textField = last = XtCreateManagedWidget("text", asciiTextWidgetClass, form, args, j));
787             XtAddEventHandler(last, ButtonPressMask, False, SetFocus, (XtPointer) popup); // gets focus on mouse click
788             if(option[i].min == 0 || option[i].type != TextBox)
789                 XtOverrideTranslations(last, XtParseTranslationTable(oneLiner)); // standard handler for <Enter> and <Tab>
790
791             if(option[i].type == TextBox || option[i].type == Fractional) break;
792
793             // add increment and decrement controls for spin
794             if(option[i].type == FileName || option[i].type == PathName) {
795                 msg = _("browse"); w = 0; // automatically scale to width of text
796                 j = textHeight ? textHeight : 0;
797             } else {
798                 w = 20; msg = "+"; j = textHeight/2; // spin button
799             }
800             j = SetPositionAndSize(args, last, edit, 1 /* border */,
801                                    w /* w */, j /* h */, 0x31 /* chain to right edge */);
802             edit = XtCreateManagedWidget(msg, commandWidgetClass, form, args, j);
803             XtAddCallback(edit, XtNcallback, SpinCallback, (XtPointer)(intptr_t) i + 256*dlgNr);
804             if(w == 0) browse = edit;
805
806             if(option[i].type != Spin) break;
807
808             j = SetPositionAndSize(args, last, edit, 1 /* border */,
809                                    20 /* w */, textHeight/2 /* h */, 0x31 /* chain to right edge */);
810             XtSetArg(args[j], XtNvertDistance, -1);  j++;
811             last = XtCreateManagedWidget("-", commandWidgetClass, form, args, j);
812             XtAddCallback(last, XtNcallback, SpinCallback, (XtPointer)(intptr_t) i + 256*dlgNr);
813             break;
814           case CheckBox:
815             if(!currentCps) option[i].value = *(Boolean*)option[i].target; // where checkbox callback uses it
816             j = SetPositionAndSize(args, last, lastrow, 1 /* border */,
817                                    textHeight/2 /* w */, textHeight/2 /* h */, 0xC0 /* chain both to left edge */);
818             XtSetArg(args[j], XtNvertDistance, (textHeight+2)/4 + 3);  j++;
819             XtSetArg(args[j], XtNstate, option[i].value);  j++;
820             lastrow  = last;
821             option[i].handle = (void*)
822                 (last = XtCreateManagedWidget(" ", toggleWidgetClass, form, args, j));
823             j = SetPositionAndSize(args, last, lastrow, 0 /* border */,
824                                    option[i].max /* w */, textHeight /* h */, 0xC1 /* chain */);
825             XtSetArg(args[j], XtNjustify, XtJustifyLeft);  j++;
826             XtSetArg(args[j], XtNlabel, _(option[i].name));  j++;
827             last = XtCreateManagedWidget("label", commandWidgetClass, form, args, j);
828             // make clicking the text toggle checkbox
829             XtAddEventHandler(last, ButtonPressMask, False, CheckCallback, (XtPointer)(intptr_t) i + 256*dlgNr);
830             shrink = TRUE; // following buttons must get text height
831             break;
832           case Label:
833             msg = option[i].name;
834             if(!msg) break;
835             chain = option[i].min;
836             if(chain & SAME_ROW) forelast = lastrow; else shrink = FALSE;
837             j = SetPositionAndSize(args, last, lastrow, (chain & 2) != 0 /* border */,
838                                    option[i].max /* w */, shrink ? textHeight : 0 /* h */, chain | 2 /* chain */);
839 #if ENABLE_NLS
840             if(option[i].choice) XtSetArg(args[j], XtNfontSet, *(XFontSet*)option[i].choice), j++;
841 #else
842             if(option[i].choice) XtSetArg(args[j], XtNfont, *(XFontStruct*)option[i].choice), j++;
843 #endif
844             XtSetArg(args[j], XtNresizable, False);  j++;
845             XtSetArg(args[j], XtNjustify, XtJustifyLeft);  j++;
846             XtSetArg(args[j], XtNlabel, _(msg));  j++;
847             option[i].handle = (void*) (last = XtCreateManagedWidget("label", labelWidgetClass, form, args, j));
848             if(option[i].target) // allow user to specify event handler for button presses
849                 XtAddEventHandler(last, ButtonPressMask, False, CheckCallback, (XtPointer)(intptr_t) i + 256*dlgNr);
850             break;
851           case SaveButton:
852           case Button:
853             if(option[i].min & SAME_ROW) {
854                 chain = 0x31; // 0011.0001 = both left and right side to right edge
855                 forelast = lastrow;
856             } else chain = 0, shrink = FALSE;
857             j = SetPositionAndSize(args, last, lastrow, 1 /* border */,
858                                    option[i].max /* w */, shrink ? textHeight : 0 /* h */, chain /* chain */);
859             XtSetArg(args[j], XtNlabel, _(option[i].name));  j++;
860             if(option[i].textValue) { // special for buttons of New Variant dialog
861                 XtSetArg(args[j], XtNsensitive, appData.noChessProgram || option[i].value < 0
862                                          || strstr(first.variants, VariantName(option[i].value))); j++;
863                 XtSetArg(args[j], XtNborderWidth, (gameInfo.variant == option[i].value)+1); j++;
864             }
865             option[i].handle = (void*)
866                 (dialog = last = XtCreateManagedWidget(option[i].name, commandWidgetClass, form, args, j));
867             if(option[i].choice && ((char*)option[i].choice)[0] == '#' && !currentCps) { // for the color picker default-reset
868                 SetColor( *(char**) option[i-1].target, &option[i]);
869                 XtAddEventHandler(option[i-1].handle, KeyReleaseMask, False, ColorChanged, (XtPointer)(intptr_t) i-1);
870             }
871             XtAddCallback(last, XtNcallback, GenericCallback, (XtPointer)(intptr_t) i + (dlgNr<<16)); // invokes user callback
872             if(option[i].textValue) SetColor( option[i].textValue, &option[i]); // for new-variant buttons
873             break;
874           case ComboBox:
875             j = SetPositionAndSize(args, last, lastrow, 0 /* border */,
876                                    0 /* w */, textHeight /* h */, 0xC0 /* chain both sides to left edge */);
877             XtSetArg(args[j], XtNjustify, XtJustifyLeft);  j++;
878             XtSetArg(args[j], XtNlabel, _(option[i].name));  j++;
879             texts[h] = dialog = XtCreateManagedWidget(option[i].name, labelWidgetClass, form, args, j);
880
881             if(option[i].min & COMBO_CALLBACK) msg = _(option[i].name); else {
882               if(!currentCps) SetCurrentComboSelection(option+i);
883               msg=_(((char**)option[i].choice)[option[i].value]);
884             }
885
886             j = SetPositionAndSize(args, dialog, last, (option[i].min & 2) == 0 /* border */,
887                                    option[i].max && !currentCps ? option[i].max : 100 /* w */,
888                                    textHeight /* h */, 0x91 /* chain */); // same row as its label!
889             XtSetArg(args[j], XtNmenuName, XtNewString(option[i].name));  j++;
890             XtSetArg(args[j], XtNlabel, msg);  j++;
891             shrink = TRUE;
892             option[i].handle = (void*)
893                 (last = XtCreateManagedWidget(" ", menuButtonWidgetClass, form, args, j));
894             CreateComboPopup(last, option + i, i + 256*dlgNr, TRUE, -1);
895             values[i] = option[i].value;
896             break;
897           case ListBox:
898             // Listbox goes in viewport, as needed for game list
899             if(option[i].min & SAME_ROW) forelast = lastrow;
900             j = SetPositionAndSize(args, last, lastrow, 1 /* border */,
901                                    option[i].max /* w */, option[i].value /* h */, option[i].min /* chain */);
902             XtSetArg(args[j], XtNresizable, False);  j++;
903             XtSetArg(args[j], XtNallowVert, True); j++; // scoll direction
904             last =
905               XtCreateManagedWidget("viewport", viewportWidgetClass, form, args, j);
906             j = 0; // now list itself
907             XtSetArg(args[j], XtNdefaultColumns, 1);  j++;
908             XtSetArg(args[j], XtNforceColumns, True);  j++;
909             XtSetArg(args[j], XtNverticalList, True);  j++;
910             option[i].handle = (void*)
911                 (edit = XtCreateManagedWidget("list", listWidgetClass, last, args, j));
912             XawListChange(option[i].handle, option[i].target, 0, 0, True);
913             XawListHighlight(option[i].handle, 0);
914             scrollTranslations[25] = '0' + i;
915             scrollTranslations[27] = 'A' + dlgNr;
916             XtOverrideTranslations(edit, XtParseTranslationTable(scrollTranslations)); // for mouse-wheel
917             break;
918           case Graph:
919             j = SetPositionAndSize(args, last, lastrow, 0 /* border */,
920                                    option[i].max /* w */, option[i].value /* h */, option[i].min /* chain */);
921             option[i].handle = (void*)
922                 (last = XtCreateManagedWidget("graph", widgetClass, form, args, j));
923             XtAddEventHandler(last, ExposureMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask, False,
924                       (XtEventHandler) GraphEventProc, option[i].target); // mandatory user-supplied expose handler
925             break;
926           case PopUp: // note: used only after Graph, so 'last' refers to the Graph widget
927             option[i].handle = (void*) CreateComboPopup(last, option + i, i + 256*dlgNr, TRUE, option[i].value);
928             break;
929           case BoxBegin:
930             if(option[i].min & SAME_ROW) forelast = lastrow;
931             j = SetPositionAndSize(args, last, lastrow, 0 /* border */,
932                                    0 /* w */, 0 /* h */, option[i].min /* chain */);
933             XtSetArg(args[j], XtNorientation, XtorientHorizontal);  j++;
934             XtSetArg(args[j], XtNvSpace, 0);                        j++;
935             option[box=i].handle = (void*)
936                 (last = XtCreateWidget("box", boxWidgetClass, form, args, j));
937             oldForm = form; form = last; oldLastRow = lastrow; oldForeLast = forelast;
938             lastrow = NULL; last = NULL;
939             break;
940           case DropDown:
941             j = SetPositionAndSize(args, last, lastrow, 0 /* border */,
942                                    0 /* w */, 0 /* h */, 1 /* chain (always on same row) */);
943             forelast = lastrow;
944             msg = _(option[i].name); // write name on the menu button
945             XtSetArg(args[j], XtNmenuName, XtNewString(option[i].name));  j++;
946             XtSetArg(args[j], XtNlabel, msg);  j++;
947             option[i].handle = (void*)
948                 (last = XtCreateManagedWidget(option[i].name, menuButtonWidgetClass, form, args, j));
949             option[i].textValue = (char*) CreateComboPopup(last, option + i, i + 256*dlgNr, FALSE, -1);
950             break;
951           case BoxEnd:
952             XtManageChildren(&form, 1);
953             SqueezeIntoBox(&option[box], i-box, option[box].max);
954             if(option[i].target) ((ButtonCallback*)option[i].target)(box); // callback that can make sizing decisions
955             last = form; lastrow = oldLastRow; form = oldForm; forelast = oldForeLast;
956             break;
957           case Break:
958             width++;
959             height = i+1;
960             stack = !(option[i].min & SAME_ROW);
961             break;
962         default:
963             printf("GenericPopUp: unexpected case in switch.\n");
964             break;
965         }
966     }
967
968     // make an attempt to align all spins and textbox controls
969     maxWidth = maxTextWidth = 0;
970     if(browse != NULL) {
971         j=0;
972         XtSetArg(args[j], XtNwidth, &bWidth);  j++;
973         XtGetValues(browse, args, j);
974     }
975     for(h=0; h<height || c == width-1; h++) {
976         i = h + c*height;
977         if(option[i].type == EndMark) break;
978         if(option[i].type == Spin || option[i].type == TextBox || option[i].type == ComboBox
979                                   || option[i].type == PathName || option[i].type == FileName) {
980             Dimension w;
981             if(!texts[h]) continue;
982             j=0;
983             XtSetArg(args[j], XtNwidth, &w);  j++;
984             XtGetValues(texts[h], args, j);
985             if(option[i].type == Spin) {
986                 if(w > maxWidth) maxWidth = w;
987                 widest = texts[h];
988             } else {
989                 if(w > maxTextWidth) maxTextWidth = w;
990                 if(!widest) widest = texts[h];
991             }
992         }
993     }
994     if(maxTextWidth + 110 < maxWidth)
995          maxTextWidth = maxWidth - 110;
996     else maxWidth = maxTextWidth + 110;
997     for(h=0; h<height || c == width-1; h++) {
998         i = h + c*height;
999         if(option[i].type == EndMark) break;
1000         if(!texts[h]) continue; // Note: texts[h] can be undefined (giving errors in valgrind), but then both if's below will be false.
1001         j=0;
1002         if(option[i].type == Spin) {
1003             XtSetArg(args[j], XtNwidth, maxWidth);  j++;
1004             XtSetValues(texts[h], args, j);
1005         } else
1006         if(option[i].type == TextBox || option[i].type == ComboBox || option[i].type == PathName || option[i].type == FileName) {
1007             XtSetArg(args[j], XtNwidth, maxTextWidth);  j++;
1008             XtSetValues(texts[h], args, j);
1009             if(bWidth != 50 && (option[i].type == FileName || option[i].type == PathName)) {
1010                 int tWidth = (option[i].max ? option[i].max : 205) - 5 - bWidth;
1011                 j = 0;
1012                 XtSetArg(args[j], XtNwidth, tWidth);  j++;
1013                 XtSetValues(option[i].handle, args, j);
1014             }
1015         }
1016     }
1017   }
1018
1019     if(option[i].min & SAME_ROW) { // even when OK suppressed this EndMark bit can request chaining of last row to bottom
1020         for(j=i-1; option[j+1].min & SAME_ROW; j--) {
1021             XtSetArg(args[0], XtNtop, XtChainBottom);
1022             XtSetArg(args[1], XtNbottom, XtChainBottom);
1023             XtSetValues(option[j].handle, args, 2);
1024         }
1025         if((option[j].type == TextBox || option[j].type == ListBox) && option[j].name[0] == NULLCHAR) {
1026             Widget w = option[j].handle;
1027             if(option[j].type == ListBox) w = XtParent(w); // for listbox we must chain viewport
1028             XtSetArg(args[0], XtNbottom, XtChainBottom);
1029             XtSetValues(w, args, 1);
1030         }
1031         lastrow = forelast;
1032     } else shrink = FALSE, lastrow = last, last = widest ? widest : dialog;
1033     j = SetPositionAndSize(args, last, anchor ? anchor : lastrow, 1 /* border */,
1034                            0 /* w */, shrink ? textHeight : 0 /* h */, 0x37 /* chain: right, bottom and use both neighbors */);
1035
1036   if(!(option[i].min & NO_OK)) {
1037     option[i].handle = b_ok = XtCreateManagedWidget(_("OK"), commandWidgetClass, form, args, j);
1038     XtAddCallback(b_ok, XtNcallback, GenericCallback, (XtPointer)(intptr_t) (30001 + (dlgNr<<16)));
1039     if(!(option[i].min & NO_CANCEL)) {
1040       XtSetArg(args[1], XtNfromHoriz, b_ok); // overwrites!
1041       b_cancel = XtCreateManagedWidget(_("cancel"), commandWidgetClass, form, args, j);
1042       XtAddCallback(b_cancel, XtNcallback, GenericCallback, (XtPointer)(intptr_t) (30000 + (dlgNr<<16)));
1043     }
1044   }
1045
1046     XtRealizeWidget(popup);
1047     XSetWMProtocols(xDisplay, XtWindow(popup), &wm_delete_window, 1);
1048     snprintf(def, MSG_SIZ, "<Message>WM_PROTOCOLS: GenericPopDown(\"%d\") \n", dlgNr);
1049     XtAugmentTranslations(popup, XtParseTranslationTable(def));
1050     XQueryPointer(xDisplay, xBoardWindow, &root, &child,
1051                   &x, &y, &win_x, &win_y, &mask);
1052
1053     XtSetArg(args[0], XtNx, x - 10);
1054     XtSetArg(args[1], XtNy, y - 30);
1055     XtSetValues(popup, args, 2);
1056
1057     XtPopup(popup, modal ? XtGrabExclusive : XtGrabNone);
1058     shellUp[dlgNr]++; // count rather than flag
1059     previous = NULL;
1060     if(textField) SetFocus(textField, popup, (XEvent*) NULL, False);
1061     if(dlgNr && wp[dlgNr] && wp[dlgNr]->width > 0) { // if persistent window-info available, reposition
1062         j = 0;
1063         XtSetArg(args[j], XtNheight, (Dimension) (wp[dlgNr]->height));  j++;
1064         XtSetArg(args[j], XtNwidth,  (Dimension) (wp[dlgNr]->width));  j++;
1065         XtSetArg(args[j], XtNx, (Position) (wp[dlgNr]->x));  j++;
1066         XtSetArg(args[j], XtNy, (Position) (wp[dlgNr]->y));  j++;
1067         XtSetValues(popup, args, j);
1068     }
1069     return 1; // tells caller he must do initialization (e.g. add specific event handlers)
1070 }
1071
1072
1073 /* function called when the data to Paste is ready */
1074 static void
1075 SendTextCB (Widget w, XtPointer client_data, Atom *selection,
1076             Atom *type, XtPointer value, unsigned long *len, int *format)
1077 {
1078   char buf[MSG_SIZ], *p = (char*) textOptions[(int)(intptr_t) client_data].choice, *name = (char*) value, *q;
1079   if (value==NULL || *len==0) return; /* nothing selected, abort */
1080   name[*len]='\0';
1081   strncpy(buf, p, MSG_SIZ);
1082   q = strstr(p, "$name");
1083   snprintf(buf + (q-p), MSG_SIZ -(q-p), "%s%s", name, q+5);
1084   SendString(buf);
1085   XtFree(value);
1086 }
1087
1088 void
1089 SendText (int n)
1090 {
1091     char *p = (char*) textOptions[n].choice;
1092     if(strstr(p, "$name")) {
1093         XtGetSelectionValue(menuBarWidget,
1094           XA_PRIMARY, XA_STRING,
1095           /* (XtSelectionCallbackProc) */ SendTextCB,
1096           (XtPointer) (intptr_t) n, /* client_data passed to PastePositionCB */
1097           CurrentTime
1098         );
1099     } else SendString(p);
1100 }
1101
1102 void
1103 SetInsertPos (Option *opt, int pos)
1104 {
1105     Arg args[16];
1106     XtSetArg(args[0], XtNinsertPosition, pos);
1107     XtSetValues(opt->handle, args, 1);
1108 //    SetFocus(opt->handle, shells[InputBoxDlg], NULL, False); // No idea why this does not work, and the following is needed:
1109     XSetInputFocus(xDisplay, XtWindow(opt->handle), RevertToPointerRoot, CurrentTime);
1110 }
1111
1112 void
1113 TypeInProc (Widget w, XEvent *event, String *prms, Cardinal *nprms)
1114 {   // can be used as handler for any text edit in any dialog (from GenericPopUp, that is)
1115     int n = prms[0][0] - '0';
1116     Widget sh = XtParent(XtParent(XtParent(w))); // popup shell
1117
1118     if(n<2) { // Enter or Esc typed from primed text widget: treat as if dialog OK or cancel button hit.
1119         int dlgNr; // figure out what the dialog number is by comparing shells (because we must pass it :( )
1120         for(dlgNr=0; dlgNr<NrOfDialogs; dlgNr++) if(shellUp[dlgNr] && shells[dlgNr] == sh)
1121             GenericCallback (w, (XtPointer)(intptr_t) (30000 + n + (dlgNr<<16)), NULL);
1122     }
1123 }
1124
1125 void
1126 HardSetFocus (Option *opt)
1127 {
1128     XSetInputFocus(xDisplay, XtWindow(opt->handle), RevertToPointerRoot, CurrentTime);
1129 }
1130
1131