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