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