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