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