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