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