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