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