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