Redo Move History with generic popup in WinBoard style
[xboard.git] / xoptions.c
1 /*
2  * xoptions.c -- Move list window, part of X front end for XBoard
3  *
4  * Copyright 2000, 2009, 2010, 2011 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
70 #include "common.h"
71 #include "backend.h"
72 #include "xboard.h"
73 #include "gettext.h"
74
75 #ifdef ENABLE_NLS
76 # define  _(s) gettext (s)
77 # define N_(s) gettext_noop (s)
78 #else
79 # define  _(s) (s)
80 # define N_(s)  s
81 #endif
82
83 // [HGM] the following code for makng menu popups was cloned from the FileNamePopUp routines
84
85 static Widget previous = NULL;
86
87 void SetFocus(Widget w, XtPointer data, XEvent *event, Boolean *b)
88 {
89     Arg args[2];
90     char *s;
91     int j;
92
93     if(previous) {
94         XtSetArg(args[0], XtNdisplayCaret, False);
95         XtSetValues(previous, args, 1);
96     }
97     XtSetArg(args[0], XtNstring, &s);
98     XtGetValues(w, args, 1);
99     j = 1;
100     XtSetArg(args[0], XtNdisplayCaret, True);
101     if(!strchr(s, '\n') && strlen(s) < 80) XtSetArg(args[1], XtNinsertPosition, strlen(s)), j++;
102     XtSetValues(w, args, j);
103     XtSetKeyboardFocus((Widget) data, w);
104     previous = w;
105 }
106
107 //--------------------------- Engine-specific options menu ----------------------------------
108
109 typedef void ButtonCallback(int n);
110 typedef int OKCallback(int n);
111
112 int values[MAX_OPTIONS];
113 ChessProgramState *currentCps;
114 static Option *currentOption;
115 static Boolean browserUp;
116 ButtonCallback *comboCallback;
117
118 void GetWidgetText(Option *opt, char **buf)
119 {
120     Arg arg;
121     XtSetArg(arg, XtNstring, buf);
122     XtGetValues(opt->handle, &arg, 1);
123 }
124
125 void SetWidgetText(Option *opt, char *buf, int n)
126 {
127     Arg arg;
128     XtSetArg(arg, XtNstring, buf);
129     XtSetValues(opt->handle, &arg, 1);
130     SetFocus(opt->handle, shells[n], NULL, False);
131 }
132
133 void SetWidgetState(Option *opt, int state)
134 {
135     Arg arg;
136     XtSetArg(arg, XtNstate, state);
137     XtSetValues(opt->handle, &arg, 1);
138 }
139
140 void CheckCallback(Widget ww, XtPointer data, XEvent *event, Boolean *b)
141 {
142     Widget w = currentOption[(int)(intptr_t)data].handle;
143     Boolean s;
144     Arg args[16];
145
146     XtSetArg(args[0], XtNstate, &s);
147     XtGetValues(w, args, 1);
148     SetWidgetState(&currentOption[(int)(intptr_t)data], !s);
149 }
150
151 void SpinCallback(w, client_data, call_data)
152      Widget w;
153      XtPointer client_data, call_data;
154 {
155     String name, val;
156     Arg args[16];
157     char buf[MSG_SIZ], *p;
158     int j;
159     int data = (intptr_t) client_data;
160
161     XtSetArg(args[0], XtNlabel, &name);
162     XtGetValues(w, args, 1);
163
164     GetWidgetText(&currentOption[data], &val);
165     sscanf(val, "%d", &j);
166     if (strcmp(name, "browse") == 0) {
167         char *q=val, *r;
168         for(r = ""; *q; q++) if(*q == '.') r = q; else if(*q == '/') r = ""; // last dot after last slash
169         if(!strcmp(r, "") && !currentCps && currentOption[data].type == FileName && currentOption[data].textValue)
170                 r = currentOption[data].textValue;
171         browserUp = True;
172         if(XsraSelFile(shells[0], currentOption[data].name, NULL, NULL, "", "", r,
173                                   currentOption[data].type == PathName ? "p" : "f", NULL, &p)) {
174                 int len = strlen(p);
175                 if(len && p[len-1] == '/') p[len-1] = NULLCHAR;
176                 XtSetArg(args[0], XtNstring, p);
177                 XtSetValues(currentOption[data].handle, args, 1);
178         }
179         browserUp = False;
180         SetFocus(currentOption[data].handle, shells[0], (XEvent*) NULL, False);
181         return;
182     } else
183     if (strcmp(name, "+") == 0) {
184         if(++j > currentOption[data].max) return;
185     } else
186     if (strcmp(name, "-") == 0) {
187         if(--j < currentOption[data].min) return;
188     } else return;
189     snprintf(buf, MSG_SIZ,  "%d", j);
190     SetWidgetText(&currentOption[data], buf, 0);
191 }
192
193 void ComboSelect(w, addr, index) // callback for all combo items
194      Widget w;
195      caddr_t addr;
196      caddr_t index;
197 {
198     Arg args[16];
199     int i = ((intptr_t)addr)>>8;
200     int j = 255 & (intptr_t) addr;
201
202     values[i] = j; // store in temporary, for transfer at OK
203     XtSetArg(args[0], XtNlabel, _(((char**)currentOption[i].textValue)[j]));
204     XtSetValues(currentOption[i].handle, args, 1);
205
206     if(currentOption[i].min & 1 && !currentCps && comboCallback) (comboCallback)(i);
207 }
208
209 void CreateComboPopup(parent, name, n, mb)
210      Widget parent;
211      String name;
212      int n;
213      char *mb[];
214 {
215     int i=0, j;
216     Widget menu, entry;
217     Arg args[16];
218
219     menu = XtCreatePopupShell(name, simpleMenuWidgetClass,
220                               parent, NULL, 0);
221     j = 0;
222     XtSetArg(args[j], XtNwidth, 100);  j++;
223 //    XtSetArg(args[j], XtNright, XtChainRight);  j++;
224     while (mb[i] != NULL) {
225             XtSetArg(args[j], XtNlabel, _(mb[i]));
226             entry = XtCreateManagedWidget(mb[i], smeBSBObjectClass,
227                                           menu, args, j+1);
228             XtAddCallback(entry, XtNcallback,
229                           (XtCallbackProc) ComboSelect,
230                           (caddr_t)(intptr_t) (256*n+i));
231         i++;
232     }
233 }
234
235
236 //----------------------------Generic dialog --------------------------------------------
237
238 // cloned from Engine Settings dialog (and later merged with it)
239
240 extern WindowPlacement wpComment, wpTags, wpMoveHistory;
241 char *trialSound;
242 static int oldCores, oldPonder;
243 int MakeColors P((void));
244 void CreateGCs P((int redo));
245 void CreateAnyPieces P((void));
246 int GenericReadout P((int selected));
247 Widget shells[10];
248 Widget marked[10];
249 Boolean shellUp[10];
250 WindowPlacement *wp[10] = { NULL, &wpComment, &wpTags, NULL, NULL, NULL, NULL, &wpMoveHistory };
251 Option *dialogOptions[10];
252
253 void MarkMenu(char *item, int dlgNr)
254 {
255     Arg args[2];
256     XtSetArg(args[0], XtNleftBitmap, xMarkPixmap);
257     XtSetValues(marked[dlgNr] = XtNameToWidget(menuBarWidget, item), args, 1);
258 }
259
260 int PopDown(int n)
261 {
262     int j;
263     Arg args[10];
264     Dimension windowH, windowW; Position windowX, windowY;
265     if (!shellUp[n]) return 0;
266     if(n && wp[n]) { // remember position
267         j = 0;
268         XtSetArg(args[j], XtNx, &windowX); j++;
269         XtSetArg(args[j], XtNy, &windowY); j++;
270         XtSetArg(args[j], XtNheight, &windowH); j++;
271         XtSetArg(args[j], XtNwidth, &windowW); j++;
272         XtGetValues(shells[n], args, j);
273         wp[n]->x = windowX;
274         wp[n]->x = windowY;
275         wp[n]->width  = windowW;
276         wp[n]->height = windowH;
277     }
278     previous = NULL;
279     XtPopdown(shells[n]);
280     if(n == 0) XtDestroyWidget(shells[n]);
281     shellUp[n] = False;
282     if(marked[n]) {
283         XtSetArg(args[0], XtNleftBitmap, None);
284         XtSetValues(marked[n], args, 1);
285     }
286     if(!n) currentCps = NULL; // if an Engine Settings dialog was up, we must be popping it down now
287     return 1;
288 }
289
290 void GenericPopDown(w, event, prms, nprms)
291      Widget w;
292      XEvent *event;
293      String *prms;
294      Cardinal *nprms;
295 {
296     if(browserUp) return; // prevent closing dialog when it has an open file-browse daughter
297     PopDown(prms[0][0] - '0');
298 }
299
300 char *engineName, *engineDir, *engineChoice, *engineLine, *nickName, *params, *tfName;
301 Boolean isUCI, hasBook, storeVariant, v1, addToList, useNick;
302 extern Option installOptions[], matchOptions[];
303 char *engineNr[] = { N_("First Engine"), N_("Second Engine"), NULL };
304 char *engineList[100] = {" "}, *engineMnemonic[100] = {""};
305
306 void AppendText(Option *opt, char *s)
307 {
308     XawTextBlock t;
309     t.ptr = s; t.firstPos = 0; t.length = strlen(s); t.format = XawFmt8Bit;
310     XawTextReplace(opt->handle, 9999, 9999, &t);
311 }
312
313 void AddLine(Option *opt, char *s)
314 {
315     AppendText(opt, s);
316     AppendText(opt, "\n");
317 }
318
319 void AddToTourney(int n)
320 {
321     GenericReadout(4);  // selected engine
322     AddLine(&matchOptions[3], engineChoice);
323 }
324
325 int MatchOK(int n)
326 {
327     if(appData.participants && appData.participants[0]) free(appData.participants);
328     appData.participants = strdup(engineName);
329     if(!CreateTourney(tfName)) return !appData.participants[0];
330     PopDown(0); // early popdown to prevent FreezeUI called through MatchEvent from causing XtGrab warning
331     MatchEvent(2); // start tourney
332     return 1;
333 }
334
335 Option matchOptions[] = {
336 { 0,  0,          0, NULL, (void*) &tfName, ".trn", NULL, FileName, N_("Tournament file:") },
337 { 0,  0,          0, NULL, (void*) &appData.roundSync, "", NULL, CheckBox, N_("Sync after round    (for concurrent playing of a single") },
338 { 0,  0,          0, NULL, (void*) &appData.cycleSync, "", NULL, CheckBox, N_("Sync after cycle      tourney with multiple XBoards)") },
339 { 0xD, 150,       0, NULL, (void*) &engineName, "", NULL, TextBox, "Tourney participants:" },
340 { 0,  1,          0, NULL, (void*) &engineChoice, (char*) (engineMnemonic+1), (engineMnemonic+1), ComboBox, N_("Select Engine:") },
341 { 0,  0,         10, NULL, (void*) &appData.tourneyType, "", NULL, Spin, N_("Tourney type (0 = round-robin, 1 = gauntlet):") },
342 { 0,  1, 1000000000, NULL, (void*) &appData.tourneyCycles, "", NULL, Spin, N_("Number of tourney cycles (or Swiss rounds):") },
343 { 0,  1, 1000000000, NULL, (void*) &appData.defaultMatchGames, "", NULL, Spin, N_("Default Number of Games in Match (or Pairing):") },
344 { 0,  0, 1000000000, NULL, (void*) &appData.matchPause, "", NULL, Spin, N_("Pause between Match Games (msec):") },
345 { 0,  0,          0, NULL, (void*) &appData.saveGameFile, ".pgn", NULL, FileName, N_("Save Tourney Games on:") },
346 { 0,  0,          0, NULL, (void*) &appData.loadGameFile, ".pgn", NULL, FileName, N_("Game File with Opening Lines:") },
347 { 0, -2, 1000000000, NULL, (void*) &appData.loadGameIndex, "", NULL, Spin, N_("Game Number (-1 or -2 = Auto-Increment):") },
348 { 0,  0,          0, NULL, (void*) &appData.loadPositionFile, ".fen", NULL, FileName, N_("File with Start Positions:") },
349 { 0, -2, 1000000000, NULL, (void*) &appData.loadPositionIndex, "", NULL, Spin, N_("Position Number (-1 or -2 = Auto-Increment):") },
350 { 0,  0, 1000000000, NULL, (void*) &appData.rewindIndex, "", NULL, Spin, N_("Rewind Index after this many Games (0 = never):") },
351 { 0, 0, 0, NULL, (void*) &MatchOK, "", NULL, EndMark , "" }
352 };
353
354 int GeneralOptionsOK(int n)
355 {
356         int newPonder = appData.ponderNextMove;
357         appData.ponderNextMove = oldPonder;
358         PonderNextMoveEvent(newPonder);
359         return 1;
360 }
361
362 Option generalOptions[] = {
363 { 0,  0, 0, NULL, (void*) &appData.sweepSelect, "", NULL, CheckBox, N_("Almost Always Queen (Detour Under-Promote)") },
364 { 0,  0, 0, NULL, (void*) &appData.animateDragging, "", NULL, CheckBox, N_("Animate Dragging") },
365 { 0,  0, 0, NULL, (void*) &appData.animate, "", NULL, CheckBox, N_("Animate Moving") },
366 { 0,  0, 0, NULL, (void*) &appData.autoCallFlag, "", NULL, CheckBox, N_("Auto Flag") },
367 { 0,  0, 0, NULL, (void*) &appData.autoFlipView, "", NULL, CheckBox, N_("Auto Flip View") },
368 { 0,  0, 0, NULL, (void*) &appData.blindfold, "", NULL, CheckBox, N_("Blindfold") },
369 { 0,  0, 0, NULL, (void*) &appData.dropMenu, "", NULL, CheckBox, N_("Drop Menu") },
370 { 0,  0, 0, NULL, (void*) &appData.hideThinkingFromHuman, "", NULL, CheckBox, N_("Hide Thinking from Human") },
371 { 0,  0, 0, NULL, (void*) &appData.highlightDragging, "", NULL, CheckBox, N_("Highlight Dragging (Show Move Targets)") },
372 { 0,  0, 0, NULL, (void*) &appData.highlightLastMove, "", NULL, CheckBox, N_("Highlight Last Move") },
373 { 0,  0, 0, NULL, (void*) &appData.highlightMoveWithArrow, "", NULL, CheckBox, N_("Highlight with Arrow") },
374 { 0,  0, 0, NULL, (void*) &appData.ringBellAfterMoves, "", NULL, CheckBox, N_("Move Sound") },
375 { 0,  0, 0, NULL, (void*) &appData.oneClick, "", NULL, CheckBox, N_("One-Click Moving") },
376 { 0,  0, 0, NULL, (void*) &appData.periodicUpdates, "", NULL, CheckBox, N_("Periodic Updates (in Analysis Mode)") },
377 { 0,  0, 0, NULL, (void*) &appData.ponderNextMove, "", NULL, CheckBox, N_("Ponder Next Move") },
378 { 0,  0, 0, NULL, (void*) &appData.popupExitMessage, "", NULL, CheckBox, N_("Popup Exit Messages") },
379 { 0,  0, 0, NULL, (void*) &appData.popupMoveErrors, "", NULL, CheckBox, N_("Popup Move Errors") },
380 { 0,  0, 0, NULL, (void*) &appData.showCoords, "", NULL, CheckBox, N_("Show Coordinates") },
381 { 0,  0, 0, NULL, (void*) &appData.markers, "", NULL, CheckBox, N_("Show Target Squares") },
382 { 0,  0, 0, NULL, (void*) &appData.testLegality, "", NULL, CheckBox, N_("Test Legality") },
383 { 0, 0, 10, NULL, (void*) &appData.flashCount, "", NULL, Spin, N_("Flash Moves (0 = no flashing):") },
384 { 0, 1, 10, NULL, (void*) &appData.flashRate, "", NULL, Spin, N_("Flash Rate (high = fast):") },
385 { 0, 5, 100,NULL, (void*) &appData.animSpeed, "", NULL, Spin, N_("Animation Speed (high = slow):") },
386 { 0,  0, 0, NULL, (void*) &GeneralOptionsOK, "", NULL, EndMark , "" }
387 };
388
389 void Pick(int n)
390 {
391         VariantClass v = currentOption[n].value;
392         if(!appData.noChessProgram) {
393             char *name = VariantName(v), buf[MSG_SIZ];
394             if (first.protocolVersion > 1 && StrStr(first.variants, name) == NULL) {
395                 /* [HGM] in protocol 2 we check if variant is suported by engine */
396               snprintf(buf, MSG_SIZ,  _("Variant %s not supported by %s"), name, first.tidy);
397                 DisplayError(buf, 0);
398                 return; /* ignore OK if first engine does not support it */
399             } else
400             if (second.initDone && second.protocolVersion > 1 && StrStr(second.variants, name) == NULL) {
401               snprintf(buf, MSG_SIZ,  _("Warning: second engine (%s) does not support this!"), second.tidy);
402                 DisplayError(buf, 0);   /* use of second engine is optional; only warn user */
403             }
404         }
405
406         GenericReadout(-1); // make sure ranks and file settings are read
407
408         gameInfo.variant = v;
409         appData.variant = VariantName(v);
410
411         shuffleOpenings = FALSE; /* [HGM] shuffle: possible shuffle reset when we switch */
412         startedFromPositionFile = FALSE; /* [HGM] loadPos: no longer valid in new variant */
413         appData.pieceToCharTable = NULL;
414         appData.pieceNickNames = "";
415         appData.colorNickNames = "";
416         Reset(True, True);
417         PopDown(0);
418         return;
419 }
420
421 Option variantDescriptors[] = {
422 { VariantNormal, 0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("normal")},
423 { VariantFairy, 1, 135, NULL, (void*) &Pick, "#BFBFBF", NULL, Button, N_("fairy")},
424 { VariantFischeRandom, 0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("FRC")},
425 { VariantSChess, 1, 135, NULL, (void*) &Pick, "#FFBFBF", NULL, Button, N_("Seirawan")},
426 { VariantWildCastle, 0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("wild castle")},
427 { VariantSuper, 1, 135, NULL, (void*) &Pick, "#FFBFBF", NULL, Button, N_("Superchess")},
428 { VariantNoCastle, 0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("no castle")},
429 { VariantCrazyhouse, 1, 135, NULL, (void*) &Pick, "#FFBFBF", NULL, Button, N_("crazyhouse")},
430 { VariantKnightmate, 0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("knightmate")},
431 { VariantBughouse, 1, 135, NULL, (void*) &Pick, "#FFBFBF", NULL, Button, N_("bughouse")},
432 { VariantBerolina, 0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("berolina")},
433 { VariantShogi, 1, 135, NULL, (void*) &Pick, "#BFFFFF", NULL, Button, N_("shogi (9x9)")},
434 { VariantCylinder, 0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("cylinder")},
435 { VariantXiangqi, 1, 135, NULL, (void*) &Pick, "#BFFFFF", NULL, Button, N_("xiangqi (9x10)")},
436 { VariantShatranj, 0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("shatranj")},
437 { VariantCourier, 1, 135, NULL, (void*) &Pick, "#BFFFBF", NULL, Button, N_("courier (12x8)")},
438 { VariantMakruk, 0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("makruk")},
439 { VariantGreat, 1, 135, NULL, (void*) &Pick, "#BFBFFF", NULL, Button, N_("Great Shatranj (10x8)")},
440 { VariantAtomic, 0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("atomic")},
441 { VariantCapablanca, 1, 135, NULL, (void*) &Pick, "#BFBFFF", NULL, Button, N_("Capablanca (10x8)")},
442 { VariantTwoKings, 0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("two kings")},
443 { VariantGothic, 1, 135, NULL, (void*) &Pick, "#BFBFFF", NULL, Button, N_("Gothic (10x8)")},
444 { Variant3Check, 0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("3-checks")},
445 { VariantJanus, 1, 135, NULL, (void*) &Pick, "#BFBFFF", NULL, Button, N_("janus (10x8)")},
446 { VariantSuicide, 0, 135, NULL, (void*) &Pick, "#FFFFBF", NULL, Button, N_("suicide")},
447 { VariantCapaRandom, 1, 135, NULL, (void*) &Pick, "#BFBFFF", NULL, Button, N_("CRC (10x8)")},
448 { VariantGiveaway, 0, 135, NULL, (void*) &Pick, "#FFFFBF", NULL, Button, N_("give-away")},
449 { VariantSpartan, 1, 135, NULL, (void*) &Pick, "#FF0000", NULL, Button, N_("Spartan")},
450 { VariantLosers, 0, 135, NULL, (void*) &Pick, "#FFFFBF", NULL, Button, N_("losers")},
451 { 0, 0, 0, NULL, NULL, NULL, NULL, Label, N_("Board size ( -1 = default for selected variant):")},
452 { 0, -1, BOARD_RANKS-1, NULL, (void*) &appData.NrRanks, "", NULL, Spin, N_("Number of Board Ranks:") },
453 { 0, -1, BOARD_FILES, NULL, (void*) &appData.NrFiles, "", NULL, Spin, N_("Number of Board Files:") },
454 { 0, -1, BOARD_RANKS-1, NULL, (void*) &appData.holdingsSize, "", NULL, Spin, N_("Holdings Size:") },
455 { 0, 0, 0, NULL, NULL, NULL, NULL, Label,
456                                 N_("WARNING: variants with un-orthodox\n"
457                                   "pieces only have built-in bitmaps\n"
458                                   "for -boardSize middling, bulky and\n"
459                                   "petite, and substitute king or amazon\n"
460                                   "for missing bitmaps. (See manual.)")},
461 { 0, 2, 0, NULL, NULL, "", NULL, EndMark , "" }
462 };
463
464 int CommonOptionsOK(int n)
465 {
466         int newPonder = appData.ponderNextMove;
467         // make sure changes are sent to first engine by re-initializing it
468         // if it was already started pre-emptively at end of previous game
469         if(gameMode == BeginningOfGame) Reset(True, True); else {
470             // Some changed setting need immediate sending always.
471             if(oldCores != appData.smpCores)
472                 NewSettingEvent(False, &(first.maxCores), "cores", appData.smpCores);
473             appData.ponderNextMove = oldPonder;
474             PonderNextMoveEvent(newPonder);
475         }
476         return 1;
477 }
478
479 Option commonEngineOptions[] = {
480 { 0,     0, 0, NULL, (void*) &appData.ponderNextMove, "", NULL, CheckBox, N_("Ponder Next Move") },
481 { 0,  0, 1000, NULL, (void*) &appData.smpCores, "", NULL, Spin, N_("Maximum Number of CPUs per Engine:") },
482 { 0,     0, 0, NULL, (void*) &appData.polyglotDir, "", NULL, PathName, N_("Polygot Directory:") },
483 { 0, 0, 16000, NULL, (void*) &appData.defaultHashSize, "", NULL, Spin, N_("Hash-Table Size (MB):") },
484 { 0,     0, 0, NULL, (void*) &appData.defaultPathEGTB, "", NULL, PathName, N_("Nalimov EGTB Path:") },
485 { 0,  0, 1000, NULL, (void*) &appData.defaultCacheSizeEGTB, "", NULL, Spin, N_("EGTB Cache Size (MB):") },
486 { 0,     0, 0, NULL, (void*) &appData.usePolyglotBook, "", NULL, CheckBox, N_("Use GUI Book") },
487 { 0,     0, 0, NULL, (void*) &appData.polyglotBook, ".bin", NULL, FileName, N_("Opening-Book Filename:") },
488 { 0,   0, 100, NULL, (void*) &appData.bookDepth, "", NULL, Spin, N_("Book Depth (moves):") },
489 { 0,   0, 100, NULL, (void*) &appData.bookStrength, "", NULL, Spin, N_("Book Variety (0) vs. Strength (100):") },
490 { 0,     0, 0, NULL, (void*) &appData.firstHasOwnBookUCI, "", NULL, CheckBox, N_("Engine #1 Has Own Book") },
491 { 0,     0, 0, NULL, (void*) &appData.secondHasOwnBookUCI, "", NULL, CheckBox, N_("Engine #2 Has Own Book          ") },
492 { 0,     1, 0, NULL, (void*) &CommonOptionsOK, "", NULL, EndMark , "" }
493 };
494
495 Option adjudicationOptions[] = {
496 { 0, 0,    0, NULL, (void*) &appData.checkMates, "", NULL, CheckBox, N_("Detect all Mates") },
497 { 0, 0,    0, NULL, (void*) &appData.testClaims, "", NULL, CheckBox, N_("Verify Engine Result Claims") },
498 { 0, 0,    0, NULL, (void*) &appData.materialDraws, "", NULL, CheckBox, N_("Draw if Insufficient Mating Material") },
499 { 0, 0,    0, NULL, (void*) &appData.trivialDraws, "", NULL, CheckBox, N_("Adjudicate Trivial Draws (3-Move Delay)") },
500 { 0, 0,  100, NULL, (void*) &appData.ruleMoves, "", NULL, Spin, N_("N-Move Rule:") },
501 { 0, 0,    6, NULL, (void*) &appData.drawRepeats, "", NULL, Spin, N_("N-fold Repeats:") },
502 { 0, 0, 1000, NULL, (void*) &appData.adjudicateDrawMoves, "", NULL, Spin, N_("Draw after N Moves Total:") },
503 { 0,-5000, 0, NULL, (void*) &appData.adjudicateLossThreshold, "", NULL, Spin, N_("Win / Loss Threshold:") },
504 { 0, 0,    0, NULL, (void*) &first.scoreIsAbsolute, "", NULL, CheckBox, N_("Negate Score of Engine #1") },
505 { 0, 0,    0, NULL, (void*) &second.scoreIsAbsolute, "", NULL, CheckBox, N_("Negate Score of Engine #2") },
506 { 0, 1,    0, NULL, NULL, "", NULL, EndMark , "" }
507 };
508
509 int IcsOptionsOK(int n)
510 {
511     ParseIcsTextColors();
512     return 1;
513 }
514
515 Option icsOptions[] = {
516 { 0, 0, 0, NULL, (void*) &appData.autoKibitz, "",  NULL, CheckBox, N_("Auto-Kibitz") },
517 { 0, 0, 0, NULL, (void*) &appData.autoComment, "", NULL, CheckBox, N_("Auto-Comment") },
518 { 0, 0, 0, NULL, (void*) &appData.autoObserve, "", NULL, CheckBox, N_("Auto-Observe") },
519 { 0, 0, 0, NULL, (void*) &appData.autoRaiseBoard, "", NULL, CheckBox, N_("Auto-Raise Board") },
520 { 0, 0, 0, NULL, (void*) &appData.bgObserve, "",   NULL, CheckBox, N_("Background Observe while Playing") },
521 { 0, 0, 0, NULL, (void*) &appData.dualBoard, "",   NULL, CheckBox, N_("Dual Board for Background-Observed Game") },
522 { 0, 0, 0, NULL, (void*) &appData.getMoveList, "", NULL, CheckBox, N_("Get Move List") },
523 { 0, 0, 0, NULL, (void*) &appData.quietPlay, "",   NULL, CheckBox, N_("Quiet Play") },
524 { 0, 0, 0, NULL, (void*) &appData.seekGraph, "",   NULL, CheckBox, N_("Seek Graph") },
525 { 0, 0, 0, NULL, (void*) &appData.autoRefresh, "", NULL, CheckBox, N_("Auto-Refresh Seek Graph") },
526 { 0, 0, 0, NULL, (void*) &appData.premove, "",     NULL, CheckBox, N_("Premove") },
527 { 0, 0, 0, NULL, (void*) &appData.premoveWhite, "", NULL, CheckBox, N_("Premove for White") },
528 { 0, 0, 0, NULL, (void*) &appData.premoveWhiteText, "", NULL, TextBox, N_("First White Move:") },
529 { 0, 0, 0, NULL, (void*) &appData.premoveBlack, "", NULL, CheckBox, N_("Premove for Black") },
530 { 0, 0, 0, NULL, (void*) &appData.premoveBlackText, "", NULL, TextBox, N_("First Black Move:") },
531 { 0, 0, 0, NULL, NULL, NULL, NULL, Break, "" },
532 { 0, 0, 0, NULL, (void*) &appData.icsAlarm, "", NULL, CheckBox, N_("Alarm") },
533 { 0, 0, 100000000, NULL, (void*) &appData.icsAlarmTime, "", NULL, Spin, N_("Alarm Time (msec):") },
534 //{ 0, 0, 0, NULL, (void*) &appData.chatBoxes, "", NULL, TextBox, N_("Startup Chat Boxes:") },
535 { 0, 0, 0, NULL, (void*) &appData.colorize, "", NULL, CheckBox, N_("Colorize Messages") },
536 { 0, 0, 0, NULL, (void*) &appData.colorShout, "", NULL, TextBox, N_("Shout Text Colors:") },
537 { 0, 0, 0, NULL, (void*) &appData.colorSShout, "", NULL, TextBox, N_("S-Shout Text Colors:") },
538 { 0, 0, 0, NULL, (void*) &appData.colorChannel1, "", NULL, TextBox, N_("Channel #1 Text Colors:") },
539 { 0, 0, 0, NULL, (void*) &appData.colorChannel, "", NULL, TextBox, N_("Other Channel Text Colors:") },
540 { 0, 0, 0, NULL, (void*) &appData.colorKibitz, "", NULL, TextBox, N_("Kibitz Text Colors:") },
541 { 0, 0, 0, NULL, (void*) &appData.colorTell, "", NULL, TextBox, N_("Tell Text Colors:") },
542 { 0, 0, 0, NULL, (void*) &appData.colorChallenge, "", NULL, TextBox, N_("Challenge Text Colors:") },
543 { 0, 0, 0, NULL, (void*) &appData.colorRequest, "", NULL, TextBox, N_("Request Text Colors:") },
544 { 0, 0, 0, NULL, (void*) &appData.colorSeek, "", NULL, TextBox, N_("Seek Text Colors:") },
545 { 0, 0, 0, NULL, (void*) &IcsOptionsOK, "", NULL, EndMark , "" }
546 };
547
548 Option loadOptions[] = {
549 { 0, 0, 0, NULL, (void*) &appData.autoDisplayTags, "", NULL, CheckBox, N_("Auto-Display Tags") },
550 { 0, 0, 0, NULL, (void*) &appData.autoDisplayComment, "", NULL, CheckBox, N_("Auto-Display Comment") },
551 { 0, 0, 0, NULL, NULL, NULL, NULL, Label, N_("Auto-Play speed of loaded games\n(0 = instant, -1 = off):") },
552 { 0, -1, 10000000, NULL, (void*) &appData.timeDelay, "", NULL, Fractional, N_("Seconds per Move:") },
553 { 0,  0, 0, NULL, NULL, "", NULL, EndMark , "" }
554 };
555
556 Option saveOptions[] = {
557 { 0, 0, 0, NULL, (void*) &appData.autoSaveGames, "", NULL, CheckBox, N_("Auto-Save Games") },
558 { 0, 0, 0, NULL, (void*) &appData.saveGameFile, ".pgn", NULL, FileName,  N_("Save Games on File:") },
559 { 0, 0, 0, NULL, (void*) &appData.savePositionFile, ".fen", NULL, FileName,  N_("Save Final Positions on File:") },
560 { 0, 0, 0, NULL, (void*) &appData.pgnEventHeader, "", NULL, TextBox,  N_("PGN Event Header:") },
561 { 0, 0, 0, NULL, (void*) &appData.oldSaveStyle, "", NULL, CheckBox, N_("Old Save Style (as opposed to PGN)") },
562 { 0, 0, 0, NULL, (void*) &appData.saveExtendedInfoInPGN, "", NULL, CheckBox, N_("Save Score/Depth Info in PGN") },
563 { 0, 0, 0, NULL, (void*) &appData.saveOutOfBookInfo, "", NULL, CheckBox, N_("Save Out-of-Book Info in PGN           ") },
564 { 0, 1, 0, NULL, NULL, "", NULL, EndMark , "" }
565 };
566
567 char *soundNames[] = {
568         N_("No Sound"),
569         N_("Default Beep"),
570         N_("Above WAV File"),
571         N_("Car Horn"),
572         N_("Cymbal"),
573         N_("Ding"),
574         N_("Gong"),
575         N_("Laser"),
576         N_("Penalty"),
577         N_("Phone"),
578         N_("Pop"),
579         N_("Slap"),
580         N_("Wood Thunk"),
581         NULL,
582         N_("User File")
583 };
584
585 char *soundFiles[] = { // sound files corresponding to above names
586         "",
587         "$",
588         "*", // kludge alert: as first thing in the dialog readout this is replaced with the user-given .WAV filename
589         "honkhonk.wav",
590         "cymbal.wav",
591         "ding1.wav",
592         "gong.wav",
593         "laser.wav",
594         "penalty.wav",
595         "phone.wav",
596         "pop2.wav",
597         "slap.wav",
598         "woodthunk.wav",
599         NULL,
600         NULL
601 };
602
603 void Test(int n)
604 {
605     GenericReadout(2);
606     if(soundFiles[values[3]]) PlaySound(soundFiles[values[3]]);
607 }
608
609 Option soundOptions[] = {
610 { 0, 0, 0, NULL, (void*) &appData.soundProgram, "", NULL, TextBox, N_("Sound Program:") },
611 { 0, 0, 0, NULL, (void*) &appData.soundDirectory, "", NULL, PathName, N_("Sounds Directory:") },
612 { 0, 0, 0, NULL, (void*) (soundFiles+2) /* kludge! */, ".wav", NULL, FileName, N_("User WAV File:") },
613 { 0, 0, 0, NULL, (void*) &trialSound, (char*) soundNames, soundFiles, ComboBox, N_("Try-Out Sound:") },
614 { 0, 1, 0, NULL, (void*) &Test, NULL, NULL, Button, N_("Play") },
615 { 0, 0, 0, NULL, (void*) &appData.soundMove, (char*) soundNames, soundFiles, ComboBox, N_("Move:") },
616 { 0, 0, 0, NULL, (void*) &appData.soundIcsWin, (char*) soundNames, soundFiles, ComboBox, N_("Win:") },
617 { 0, 0, 0, NULL, (void*) &appData.soundIcsLoss, (char*) soundNames, soundFiles, ComboBox, N_("Lose:") },
618 { 0, 0, 0, NULL, (void*) &appData.soundIcsDraw, (char*) soundNames, soundFiles, ComboBox, N_("Draw:") },
619 { 0, 0, 0, NULL, (void*) &appData.soundIcsUnfinished, (char*) soundNames, soundFiles, ComboBox, N_("Unfinished:") },
620 { 0, 0, 0, NULL, (void*) &appData.soundIcsAlarm, (char*) soundNames, soundFiles, ComboBox, N_("Alarm:") },
621 { 0, 0, 0, NULL, (void*) &appData.soundShout, (char*) soundNames, soundFiles, ComboBox, N_("Shout:") },
622 { 0, 0, 0, NULL, (void*) &appData.soundSShout, (char*) soundNames, soundFiles, ComboBox, N_("S-Shout:") },
623 { 0, 0, 0, NULL, (void*) &appData.soundChannel, (char*) soundNames, soundFiles, ComboBox, N_("Channel:") },
624 { 0, 0, 0, NULL, (void*) &appData.soundChannel1, (char*) soundNames, soundFiles, ComboBox, N_("Channel 1:") },
625 { 0, 0, 0, NULL, (void*) &appData.soundTell, (char*) soundNames, soundFiles, ComboBox, N_("Tell:") },
626 { 0, 0, 0, NULL, (void*) &appData.soundKibitz, (char*) soundNames, soundFiles, ComboBox, N_("Kibitz:") },
627 { 0, 0, 0, NULL, (void*) &appData.soundChallenge, (char*) soundNames, soundFiles, ComboBox, N_("Challenge:") },
628 { 0, 0, 0, NULL, (void*) &appData.soundRequest, (char*) soundNames, soundFiles, ComboBox, N_("Request:") },
629 { 0, 0, 0, NULL, (void*) &appData.soundSeek, (char*) soundNames, soundFiles, ComboBox, N_("Seek:") },
630 { 0, 1, 0, NULL, NULL, "", NULL, EndMark , "" }
631 };
632
633 void SetColor(char *colorName, Option *box)
634 {
635         Arg args[5];
636         Pixel buttonColor;
637         XrmValue vFrom, vTo;
638         if (!appData.monoMode) {
639             vFrom.addr = (caddr_t) colorName;
640             vFrom.size = strlen(colorName);
641             XtConvert(shellWidget, XtRString, &vFrom, XtRPixel, &vTo);
642             if (vTo.addr == NULL) {
643                 buttonColor = (Pixel) -1;
644             } else {
645                 buttonColor = *(Pixel *) vTo.addr;
646             }
647         } else buttonColor = (Pixel) 0;
648         XtSetArg(args[0], XtNbackground, buttonColor);;
649         XtSetValues(box->handle, args, 1);
650 }
651
652 void SetColorText(int n, char *buf)
653 {
654     SetWidgetText(&currentOption[n-1], buf, 0);
655     SetColor(buf, &currentOption[n]);
656 }
657
658 void DefColor(int n)
659 {
660     SetColorText(n, (char*) currentOption[n].choice);
661 }
662
663 void RefreshColor(int source, int n)
664 {
665     int col, j, r, g, b, step = 10;
666     char *s, buf[MSG_SIZ]; // color string
667     Arg args[5];
668     GetWidgetText(&currentOption[source], &s);
669     if(sscanf(s, "#%x", &col) != 1) return;   // malformed
670     b = col & 0xFF; g = col & 0xFF00; r = col & 0xFF0000;
671     switch(n) {
672         case 1: r += 0x10000*step;break;
673         case 2: g += 0x100*step;  break;
674         case 3: b += step;        break;
675         case 4: r -= 0x10000*step; g -= 0x100*step; b -= step; break;
676     }
677     if(r < 0) r = 0; if(g < 0) g = 0; if(b < 0) b = 0;
678     if(r > 0xFF0000) r = 0xFF0000; if(g > 0xFF00) g = 0xFF00; if(b > 0xFF) b = 0xFF;
679     col = r | g | b;
680     snprintf(buf, MSG_SIZ, "#%06x", col);
681     for(j=1; j<7; j++) if(buf[j] >= 'a') buf[j] -= 32; // capitalize
682     SetColorText(source+1, buf);
683 }
684
685 void ColorChanged(Widget w, XtPointer data, XEvent *event, Boolean *b)
686 {
687     char buf[10];
688     if ( (XLookupString(&(event->xkey), buf, 2, NULL, NULL) == 1) && *buf == '\r' )
689         RefreshColor((int)(intptr_t) data, 0);
690 }
691
692 void AdjustColor(int i)
693 {
694     int n = currentOption[i].value;
695     RefreshColor(i-n-1, n);
696 }
697
698 int BoardOptionsOK(int n)
699 {
700     if(appData.overrideLineGap >= 0) lineGap = appData.overrideLineGap; else lineGap = defaultLineGap;
701     useImages = useImageSqs = 0;
702     MakeColors(); CreateGCs(True);
703     CreateAnyPieces();
704     InitDrawingSizes(-1, 0);
705     DrawPosition(True, NULL);
706     return 1;
707 }
708
709 Option boardOptions[] = {
710 { 0,   0, 70, NULL, (void*) &appData.whitePieceColor, "", NULL, TextBox, N_("White Piece Color:") },
711 { 1000, 1, 0, NULL, (void*) &DefColor, NULL, (char**) "#FFFFCC", Button, "      " },
712 {    1, 1, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, "R" },
713 {    2, 1, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, "G" },
714 {    3, 1, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, "B" },
715 {    4, 1, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, "D" },
716 { 0,   0, 70, NULL, (void*) &appData.blackPieceColor, "", NULL, TextBox, N_("Black Piece Color:") },
717 { 1000, 1, 0, NULL, (void*) &DefColor, NULL, (char**) "#202020", Button, "      " },
718 {    1, 1, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, "R" },
719 {    2, 1, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, "G" },
720 {    3, 1, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, "B" },
721 {    4, 1, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, "D" },
722 { 0,   0, 70, NULL, (void*) &appData.lightSquareColor, "", NULL, TextBox, N_("Light Square Color:") },
723 { 1000, 1, 0, NULL, (void*) &DefColor, NULL, (char**) "#C8C365", Button, "      " },
724 {    1, 1, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, "R" },
725 {    2, 1, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, "G" },
726 {    3, 1, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, "B" },
727 {    4, 1, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, "D" },
728 { 0,   0, 70, NULL, (void*) &appData.darkSquareColor, "", NULL, TextBox, N_("Dark Square Color:") },
729 { 1000, 1, 0, NULL, (void*) &DefColor, NULL, (char**) "#77A26D", Button, "      " },
730 {    1, 1, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, "R" },
731 {    2, 1, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, "G" },
732 {    3, 1, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, "B" },
733 {    4, 1, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, "D" },
734 { 0,   0, 70, NULL, (void*) &appData.highlightSquareColor, "", NULL, TextBox, N_("Highlight Color:") },
735 { 1000, 1, 0, NULL, (void*) &DefColor, NULL, (char**) "#FFFF00", Button, "      " },
736 {    1, 1, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, "R" },
737 {    2, 1, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, "G" },
738 {    3, 1, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, "B" },
739 {    4, 1, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, "D" },
740 { 0,   0, 70, NULL, (void*) &appData.premoveHighlightColor, "", NULL, TextBox, N_("Premove Highlight Color:") },
741 { 1000, 1, 0, NULL, (void*) &DefColor, NULL, (char**) "#FF0000", Button, "      " },
742 {    1, 1, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, "R" },
743 {    2, 1, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, "G" },
744 {    3, 1, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, "B" },
745 {    4, 1, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, "D" },
746 { 0, 0, 0, NULL, (void*) &appData.upsideDown, "", NULL, CheckBox, N_("Flip Pieces Shogi Style        (Colored buttons restore default)") },
747 //{ 0, 0, 0, NULL, (void*) &appData.allWhite, "", NULL, CheckBox, N_("Use Outline Pieces for Black") },
748 { 0, 0, 0, NULL, (void*) &appData.monoMode, "", NULL, CheckBox, N_("Mono Mode") },
749 { 0,-1, 5, NULL, (void*) &appData.overrideLineGap, "", NULL, Spin, N_("Line Gap ( -1 = default for board size):") },
750 { 0, 0, 0, NULL, (void*) &appData.liteBackTextureFile, ".xpm", NULL, FileName, N_("Light-Squares Texture File:") },
751 { 0, 0, 0, NULL, (void*) &appData.darkBackTextureFile, ".xpm", NULL, FileName, N_("Dark-Squares Texture File:") },
752 { 0, 0, 0, NULL, (void*) &appData.bitmapDirectory, "", NULL, PathName, N_("Directory with Bitmap Pieces:") },
753 { 0, 0, 0, NULL, (void*) &appData.pixmapDirectory, "", NULL, PathName, N_("Directory with Pixmap Pieces:") },
754 { 0, 0, 0, NULL, (void*) &BoardOptionsOK, "", NULL, EndMark , "" }
755 };
756
757 int GenericReadout(int selected)
758 {
759     int i, j, res=1;
760     String val;
761     Arg args[16];
762     char buf[MSG_SIZ], **dest;
763     float x;
764         for(i=0; ; i++) { // send all options that had to be OK-ed to engine
765             if(selected >= 0) { if(i < selected) continue; else if(i > selected) break; }
766             switch(currentOption[i].type) {
767                 case TextBox:
768                 case FileName:
769                 case PathName:
770                     XtSetArg(args[0], XtNstring, &val);
771                     XtGetValues(currentOption[i].handle, args, 1);
772                     dest = currentCps ? &(currentOption[i].textValue) : (char**) currentOption[i].target;
773                     if(*dest == NULL || strcmp(*dest, val)) {
774                         if(currentCps) {
775                             snprintf(buf, MSG_SIZ,  "option %s=%s\n", currentOption[i].name, val);
776                             SendToProgram(buf, currentCps);
777                         } else {
778                             if(*dest) free(*dest);
779                             *dest = malloc(strlen(val)+1);
780                         }
781                         safeStrCpy(*dest, val, MSG_SIZ - (*dest - currentOption[i].name)); // copy text there
782                     }
783                     break;
784                 case Spin:
785                 case Fractional:
786                     XtSetArg(args[0], XtNstring, &val);
787                     XtGetValues(currentOption[i].handle, args, 1);
788                     sscanf(val, "%f", &x);
789                     if(x > currentOption[i].max) x = currentOption[i].max;
790                     if(x < currentOption[i].min) x = currentOption[i].min;
791                     if(currentOption[i].type == Fractional)
792                         *(float*) currentOption[i].target = x; // engines never have float options!
793                     else if(currentOption[i].value != x) {
794                         currentOption[i].value = x;
795                         if(currentCps) {
796                             snprintf(buf, MSG_SIZ,  "option %s=%.0f\n", currentOption[i].name, x);
797                             SendToProgram(buf, currentCps);
798                         } else *(int*) currentOption[i].target = x;
799                     }
800                     break;
801                 case CheckBox:
802                     j = 0;
803                     XtSetArg(args[0], XtNstate, &j);
804                     XtGetValues(currentOption[i].handle, args, 1);
805                     if(currentOption[i].value != j) {
806                         currentOption[i].value = j;
807                         if(currentCps) {
808                             snprintf(buf, MSG_SIZ,  "option %s=%d\n", currentOption[i].name, j);
809                             SendToProgram(buf, currentCps);
810                         } else *(Boolean*) currentOption[i].target = j;
811                     }
812                     break;
813                 case ComboBox:
814                     val = ((char**)currentOption[i].choice)[values[i]];
815                     if(currentCps) {
816                         if(currentOption[i].value == values[i]) break; // not changed
817                         currentOption[i].value = values[i];
818                         snprintf(buf, MSG_SIZ,  "option %s=%s\n", currentOption[i].name,
819                                 ((char**)currentOption[i].textValue)[values[i]]);
820                         SendToProgram(buf, currentCps);
821                     } else if(val && (*(char**) currentOption[i].target == NULL || strcmp(*(char**) currentOption[i].target, val))) {
822                       if(*(char**) currentOption[i].target) free(*(char**) currentOption[i].target);
823                       *(char**) currentOption[i].target = strdup(val);
824                     }
825                     break;
826                 case EndMark:
827                     if(currentOption[i].target) // callback for implementing necessary actions on OK (like redraw)
828                         res = ((OKCallback*) currentOption[i].target)(i);
829                     break;
830             default:
831                 printf("GenericReadout: unexpected case in switch.\n");
832                 case Button:
833                 case SaveButton:
834                 case Label:
835                 case Break:
836               break;
837             }
838             if(currentOption[i].type == EndMark) break;
839         }
840         return res;
841 }
842
843 void GenericCallback(w, client_data, call_data)
844      Widget w;
845      XtPointer client_data, call_data;
846 {
847     String name;
848     Arg args[16];
849     char buf[MSG_SIZ];
850     int data = (intptr_t) client_data;
851
852     currentOption = dialogOptions[data>>16]; data &= 0xFFFF;
853
854     XtSetArg(args[0], XtNlabel, &name);
855     XtGetValues(w, args, 1);
856
857     if (strcmp(name, _("cancel")) == 0) {
858         PopDown(data);
859         return;
860     }
861     if (strcmp(name, _("OK")) == 0) { // save buttons imply OK
862         if(GenericReadout(-1)) PopDown(data);
863         return;
864     }
865     if(currentCps) {
866         if(currentOption[data].type == SaveButton) GenericReadout(-1);
867         snprintf(buf, MSG_SIZ,  "option %s\n", name);
868         SendToProgram(buf, currentCps);
869     } else ((ButtonCallback*) currentOption[data].target)(data);
870 }
871
872 static char *oneLiner  = "<Key>Return:  redraw-display()\n";
873
874 int
875 GenericPopUp(Option *option, char *title, int dlgNr)
876 {
877     Arg args[16];
878     Widget popup, layout, dialog=NULL, edit=NULL, form,  last, b_ok, b_cancel, leftMargin = NULL, textField = NULL;
879     Window root, child;
880     int x, y, i, j, height=999, width=1, h, c, w;
881     int win_x, win_y, maxWidth, maxTextWidth;
882     unsigned int mask;
883     char def[MSG_SIZ], *msg;
884     static char pane[6] = "paneX";
885     Widget texts[100], forelast = NULL, anchor, widest, lastrow = NULL;
886
887     if(shellUp[dlgNr]) return 0; // already up          
888     if(dlgNr && shells[dlgNr]) {
889         XtPopup(shells[dlgNr], XtGrabNone);
890         shellUp[dlgNr] = True;
891         return 0;
892     }
893
894     dialogOptions[dlgNr] = option; // make available to callback
895     // post currentOption globally, so Spin and Combo callbacks can already use it
896     // WARNING: this kludge does not work for persistent dialogs, so that these cannot have spin or combo controls!
897     currentOption = option;
898
899     if(currentCps) { // Settings popup for engine: format through heuristic
900         int n = currentCps->nrOptions;
901         if(!n) { DisplayNote(_("Engine has no options")); return 0; }
902         if(n > 50) width = 4; else if(n>24) width = 2; else width = 1;
903         height = n / width + 1;
904         if(n && (currentOption[n-1].type == Button || currentOption[n-1].type == SaveButton)) currentOption[n].min = 1; // OK on same line
905         currentOption[n].type = EndMark; currentOption[n].target = NULL; // delimit list by callback-less end mark
906     }
907      i = 0;
908     XtSetArg(args[i], XtNresizable, True); i++;
909     popup = shells[dlgNr] =
910       XtCreatePopupShell(title, transientShellWidgetClass,
911                          shellWidget, args, i);
912
913     layout =
914       XtCreateManagedWidget(layoutName, formWidgetClass, popup,
915                             layoutArgs, XtNumber(layoutArgs));
916   for(c=0; c<width; c++) {
917     pane[4] = 'A'+c;
918     form =
919       XtCreateManagedWidget(pane, formWidgetClass, layout,
920                             formArgs, XtNumber(formArgs));
921     j=0;
922     XtSetArg(args[j], XtNfromHoriz, leftMargin);  j++;
923     XtSetValues(form, args, j);
924     leftMargin = form;
925
926     last = widest = NULL; anchor = lastrow;
927     for(h=0; h<height; h++) {
928         i = h + c*height;
929         if(option[i].type == EndMark) break;
930         lastrow = forelast;
931         forelast = last;
932         switch(option[i].type) {
933           case Fractional:
934             snprintf(def, MSG_SIZ,  "%.2f", *(float*)option[i].target);
935             option[i].value = *(float*)option[i].target;
936             goto tBox;
937           case Spin:
938             if(!currentCps) option[i].value = *(int*)option[i].target;
939             snprintf(def, MSG_SIZ,  "%d", option[i].value);
940           case TextBox:
941           case FileName:
942           case PathName:
943           tBox:
944             if(option[i].name[0]) {
945             j=0;
946             XtSetArg(args[j], XtNfromVert, last);  j++;
947             XtSetArg(args[j], XtNleft, XtChainLeft); j++;
948             XtSetArg(args[j], XtNright, XtChainLeft); j++;
949             XtSetArg(args[j], XtNborderWidth, 0);  j++;
950             XtSetArg(args[j], XtNjustify, XtJustifyLeft);  j++;
951             XtSetArg(args[j], XtNlabel, _(option[i].name));  j++;
952             texts[h] =
953             dialog = XtCreateManagedWidget(option[i].name, labelWidgetClass, form, args, j);
954             } else texts[h] = dialog = NULL;
955             w = option[i].type == Spin || option[i].type == Fractional ? 70 : option[i].max ? option[i].max : 205;
956             if(option[i].type == FileName || option[i].type == PathName) w -= 55;
957             j=0;
958             XtSetArg(args[j], XtNfromVert, last);  j++;
959             XtSetArg(args[j], XtNfromHoriz, dialog);  j++;
960             XtSetArg(args[j], XtNborderWidth, 1); j++;
961             XtSetArg(args[j], XtNwidth, w); j++;
962             if(option[i].type == TextBox && option[i].min) {
963                 XtSetArg(args[j], XtNheight, option[i].min); j++;
964                 if(option[i].value & 1) { XtSetArg(args[j], XtNscrollVertical, XawtextScrollAlways);  j++; }
965                 if(option[i].value & 2) { XtSetArg(args[j], XtNscrollHorizontal, XawtextScrollAlways);  j++; }
966                 if(option[i].value & 4) { XtSetArg(args[j], XtNautoFill, True);  j++; }
967                 if(option[i].value & 8) { XtSetArg(args[j], XtNwrap, XawtextWrapWord); j++; }
968             }
969             XtSetArg(args[j], XtNleft, XtChainLeft); j++;
970             XtSetArg(args[j], XtNeditType, XawtextEdit);  j++;
971             XtSetArg(args[j], XtNuseStringInPlace, False);  j++;
972             XtSetArg(args[j], XtNdisplayCaret, False);  j++;
973             XtSetArg(args[j], XtNright, XtChainRight);  j++;
974             XtSetArg(args[j], XtNresizable, True);  j++;
975             XtSetArg(args[j], XtNinsertPosition, 9999);  j++;
976             XtSetArg(args[j], XtNstring, option[i].type==Spin || option[i].type==Fractional ? def : 
977                                 currentCps ? option[i].textValue : *(char**)option[i].target);  j++;
978             edit = last;
979             option[i].handle = (void*)
980                 (textField = last = XtCreateManagedWidget("text", asciiTextWidgetClass, form, args, j));
981             XtAddEventHandler(last, ButtonPressMask, False, SetFocus, (XtPointer) popup);
982             if(option[i].min == 0 || option[i].type != TextBox)
983                 XtOverrideTranslations(last, XtParseTranslationTable(oneLiner));
984
985             if(option[i].type == TextBox || option[i].type == Fractional) break;
986
987             // add increment and decrement controls for spin
988             j=0;
989             XtSetArg(args[j], XtNfromVert, edit);  j++;
990             XtSetArg(args[j], XtNfromHoriz, last);  j++;
991             XtSetArg(args[j], XtNleft, XtChainRight); j++;
992             XtSetArg(args[j], XtNright, XtChainRight); j++;
993             if(option[i].type == FileName || option[i].type == PathName) {
994                 w = 50; msg = _("browse");
995             } else {
996                 XtSetArg(args[j], XtNheight, 10);  j++;
997                 w = 20; msg = "+";
998             }
999             XtSetArg(args[j], XtNwidth, w);  j++;
1000             edit = XtCreateManagedWidget(msg, commandWidgetClass, form, args, j);
1001             XtAddCallback(edit, XtNcallback, SpinCallback, (XtPointer)(intptr_t) i);
1002
1003             if(option[i].type != Spin) break;
1004
1005             j=0;
1006             XtSetArg(args[j], XtNfromVert, edit);  j++;
1007             XtSetArg(args[j], XtNfromHoriz, last);  j++;
1008             XtSetArg(args[j], XtNheight, 10);  j++;
1009             XtSetArg(args[j], XtNwidth, 20);  j++;
1010             XtSetArg(args[j], XtNleft, XtChainRight); j++;
1011             XtSetArg(args[j], XtNright, XtChainRight); j++;
1012             last = XtCreateManagedWidget("-", commandWidgetClass, form, args, j);
1013             XtAddCallback(last, XtNcallback, SpinCallback, (XtPointer)(intptr_t) i);
1014             break;
1015           case CheckBox:
1016             if(!currentCps) option[i].value = *(Boolean*)option[i].target;
1017             j=0;
1018             XtSetArg(args[j], XtNfromVert, last);  j++;
1019             XtSetArg(args[j], XtNwidth, 10);  j++;
1020             XtSetArg(args[j], XtNheight, 10);  j++;
1021             XtSetArg(args[j], XtNleft, XtChainLeft); j++;
1022             XtSetArg(args[j], XtNright, XtChainLeft); j++;
1023             XtSetArg(args[j], XtNstate, option[i].value);  j++;
1024             option[i].handle = (void*)
1025                 (dialog = XtCreateManagedWidget(" ", toggleWidgetClass, form, args, j));
1026           case Label:
1027             msg = option[i].name;
1028             if(*msg == NULLCHAR) msg = option[i].textValue;
1029             if(!msg) break;
1030             j=0;
1031             XtSetArg(args[j], XtNfromVert, last);  j++;
1032             XtSetArg(args[j], XtNfromHoriz, option[i].type != Label ? dialog : NULL);  j++;
1033             XtSetArg(args[j], XtNleft, XtChainLeft); j++;
1034             XtSetArg(args[j], XtNborderWidth, 0);  j++;
1035             XtSetArg(args[j], XtNjustify, XtJustifyLeft);  j++;
1036             XtSetArg(args[j], XtNlabel, _(msg));  j++;
1037             last = XtCreateManagedWidget(msg, labelWidgetClass, form, args, j);
1038             if(option[i].type == CheckBox)
1039                 XtAddEventHandler(last, ButtonPressMask, False, CheckCallback, (XtPointer)(intptr_t) i);
1040             break;
1041           case SaveButton:
1042           case Button:
1043             j=0;
1044             XtSetArg(args[j], XtNfromVert, option[i].min & 1 ? lastrow : last);  j++;
1045             XtSetArg(args[j], XtNlabel, _(option[i].name));  j++;
1046             if(option[i].min & 1) { XtSetArg(args[j], XtNfromHoriz, last);  j++; }
1047             else  { XtSetArg(args[j], XtNfromHoriz, NULL);  j++; lastrow = forelast; }
1048             if(option[i].max) { XtSetArg(args[j], XtNwidth, option[i].max);  j++; }
1049             if(option[i].textValue) { // special for buttons of New Variant dialog
1050                 XtSetArg(args[j], XtNsensitive, appData.noChessProgram || option[i].value < 0
1051                                          || strstr(first.variants, VariantName(option[i].value))); j++;
1052                 XtSetArg(args[j], XtNborderWidth, (gameInfo.variant == option[i].value)+1); j++;
1053             }
1054             option[i].handle = (void*)
1055                 (dialog = last = XtCreateManagedWidget(option[i].name, commandWidgetClass, form, args, j));
1056             if(option[i].choice && ((char*)option[i].choice)[0] == '#' && !currentCps) {
1057                 SetColor( *(char**) option[i-1].target, &option[i]);
1058                 XtAddEventHandler(option[i-1].handle, KeyReleaseMask, False, ColorChanged, (XtPointer)(intptr_t) i-1);
1059             }
1060             XtAddCallback(last, XtNcallback, GenericCallback,
1061                           (XtPointer)(intptr_t) i + (dlgNr<<16));
1062             if(option[i].textValue) SetColor( option[i].textValue, &option[i]);
1063             forelast = lastrow; // next button can go on same row
1064             break;
1065           case ComboBox:
1066             j=0;
1067             XtSetArg(args[j], XtNfromVert, last);  j++;
1068             XtSetArg(args[j], XtNleft, XtChainLeft); j++;
1069             XtSetArg(args[j], XtNright, XtChainLeft); j++;
1070             XtSetArg(args[j], XtNborderWidth, 0);  j++;
1071             XtSetArg(args[j], XtNjustify, XtJustifyLeft);  j++;
1072             XtSetArg(args[j], XtNlabel, _(option[i].name));  j++;
1073             texts[h] = dialog = XtCreateManagedWidget(option[i].name, labelWidgetClass, form, args, j);
1074
1075             if(currentCps) option[i].choice = (char**) option[i].textValue; else {
1076               for(j=0; option[i].choice[j]; j++)
1077                 if(*(char**)option[i].target && !strcmp(*(char**)option[i].target, option[i].choice[j])) break;
1078               option[i].value = j + (option[i].choice[j] == NULL);
1079             }
1080
1081             j=0;
1082             XtSetArg(args[j], XtNfromVert, last);  j++;
1083             XtSetArg(args[j], XtNfromHoriz, dialog);  j++;
1084             XtSetArg(args[j], XtNwidth, option[i].max && !currentCps ? option[i].max : 100);  j++;
1085             XtSetArg(args[j], XtNleft, XtChainLeft); j++;
1086             XtSetArg(args[j], XtNmenuName, XtNewString(option[i].name));  j++;
1087             XtSetArg(args[j], XtNlabel, _(((char**)option[i].textValue)[option[i].value]));  j++;
1088             option[i].handle = (void*)
1089                 (last = XtCreateManagedWidget(" ", menuButtonWidgetClass, form, args, j));
1090             CreateComboPopup(last, option[i].name, i, (char **) option[i].textValue);
1091             values[i] = option[i].value;
1092             break;
1093           case Break:
1094             width++;
1095             height = i+1;
1096             break;
1097         default:
1098             printf("GenericPopUp: unexpected case in switch.\n");
1099             break;
1100         }
1101     }
1102
1103     // make an attempt to align all spins and textbox controls
1104     maxWidth = maxTextWidth = 0;
1105     for(h=0; h<height; h++) {
1106         i = h + c*height;
1107         if(option[i].type == EndMark) break;
1108         if(option[i].type == Spin || option[i].type == TextBox || option[i].type == ComboBox
1109                                   || option[i].type == PathName || option[i].type == FileName) {
1110             Dimension w;
1111             if(!texts[h]) continue;
1112             j=0;
1113             XtSetArg(args[j], XtNwidth, &w);  j++;
1114             XtGetValues(texts[h], args, j);
1115             if(option[i].type == Spin) {
1116                 if(w > maxWidth) maxWidth = w;
1117                 widest = texts[h];
1118             } else {
1119                 if(w > maxTextWidth) maxTextWidth = w;
1120                 if(!widest) widest = texts[h];
1121             }
1122         }
1123     }
1124     if(maxTextWidth + 110 < maxWidth)
1125          maxTextWidth = maxWidth - 110;
1126     else maxWidth = maxTextWidth + 110;
1127     for(h=0; h<height; h++) {
1128         i = h + c*height;
1129         if(option[i].type == EndMark) break;
1130         if(!texts[h]) continue;
1131         j=0;
1132         if(option[i].type == Spin) {
1133             XtSetArg(args[j], XtNwidth, maxWidth);  j++;
1134             XtSetValues(texts[h], args, j);
1135         } else
1136         if(option[i].type == TextBox || option[i].type == ComboBox || option[i].type == PathName || option[i].type == FileName) {
1137             XtSetArg(args[j], XtNwidth, maxTextWidth);  j++;
1138             XtSetValues(texts[h], args, j);
1139         }
1140     }
1141   }
1142
1143   if(!(option[i].min & 2)) {
1144     j=0;
1145     if(option[i].min & 1) {
1146         for(j=i-1; option[j+1].min&1 && option[j].type == Button; j--) {
1147             XtSetArg(args[0], XtNtop, XtChainBottom);
1148             XtSetArg(args[1], XtNbottom, XtChainBottom);
1149             XtSetValues(option[j].handle, args, 2);
1150         }
1151         if(option[j].type == TextBox && option[j].name[0] == NULLCHAR) {
1152             XtSetArg(args[0], XtNbottom, XtChainBottom);
1153             XtSetValues(option[j].handle, args, 1);
1154         }
1155         j = 0;
1156         XtSetArg(args[j], XtNfromHoriz, last); last = forelast;
1157     } else
1158     XtSetArg(args[j], XtNfromHoriz, widest ? widest : dialog);  j++;
1159     XtSetArg(args[j], XtNfromVert, anchor ? anchor : last);  j++;
1160     XtSetArg(args[j], XtNbottom, XtChainBottom);  j++;
1161     XtSetArg(args[j], XtNtop, XtChainBottom);  j++;
1162     XtSetArg(args[j], XtNleft, XtChainRight);  j++;
1163     XtSetArg(args[j], XtNright, XtChainRight);  j++;
1164     b_ok = XtCreateManagedWidget(_("OK"), commandWidgetClass, form, args, j);
1165     XtAddCallback(b_ok, XtNcallback, GenericCallback, (XtPointer)(intptr_t) dlgNr + (dlgNr<<16));
1166
1167     XtSetArg(args[0], XtNfromHoriz, b_ok);
1168     b_cancel = XtCreateManagedWidget(_("cancel"), commandWidgetClass, form, args, j);
1169     XtAddCallback(b_cancel, XtNcallback, GenericCallback, (XtPointer)(intptr_t) dlgNr);
1170   }
1171
1172     XtRealizeWidget(popup);
1173     XSetWMProtocols(xDisplay, XtWindow(popup), &wm_delete_window, 1);
1174     snprintf(def, MSG_SIZ, "<Message>WM_PROTOCOLS: GenericPopDown(\"%d\") \n", dlgNr);
1175     XtAugmentTranslations(popup, XtParseTranslationTable(def));
1176     XQueryPointer(xDisplay, xBoardWindow, &root, &child,
1177                   &x, &y, &win_x, &win_y, &mask);
1178
1179     XtSetArg(args[0], XtNx, x - 10);
1180     XtSetArg(args[1], XtNy, y - 30);
1181     XtSetValues(popup, args, 2);
1182
1183     XtPopup(popup, dlgNr ? XtGrabNone : XtGrabExclusive);
1184     shellUp[dlgNr] = True;
1185     previous = NULL;
1186     if(textField)SetFocus(textField, popup, (XEvent*) NULL, False);
1187     if(dlgNr && wp[dlgNr] && wp[dlgNr]->width > 0) { // if persistent window-info available, reposition
1188         j = 0;
1189         XtSetArg(args[j], XtNheight, (Dimension) (wp[dlgNr]->height));  j++;
1190         XtSetArg(args[j], XtNwidth,  (Dimension) (wp[dlgNr]->width));  j++;
1191         XtSetArg(args[j], XtNx, (Position) (wp[dlgNr]->x));  j++;
1192         XtSetArg(args[j], XtNy, (Position) (wp[dlgNr]->y));  j++;
1193         XtSetValues(popup, args, j);
1194     }
1195     return 1;
1196 }
1197
1198
1199 void IcsOptionsProc(w, event, prms, nprms)
1200      Widget w;
1201      XEvent *event;
1202      String *prms;
1203      Cardinal *nprms;
1204 {
1205    GenericPopUp(icsOptions, _("ICS Options"), 0);
1206 }
1207
1208 void LoadOptionsProc(w, event, prms, nprms)
1209      Widget w;
1210      XEvent *event;
1211      String *prms;
1212      Cardinal *nprms;
1213 {
1214    GenericPopUp(loadOptions, _("Load Game Options"), 0);
1215 }
1216
1217 void SaveOptionsProc(w, event, prms, nprms)
1218      Widget w;
1219      XEvent *event;
1220      String *prms;
1221      Cardinal *nprms;
1222 {
1223    GenericPopUp(saveOptions, _("Save Game Options"), 0);
1224 }
1225
1226 void SoundOptionsProc(w, event, prms, nprms)
1227      Widget w;
1228      XEvent *event;
1229      String *prms;
1230      Cardinal *nprms;
1231 {
1232    soundFiles[2] = "*";
1233    GenericPopUp(soundOptions, _("Sound Options"), 0);
1234 }
1235
1236 void BoardOptionsProc(w, event, prms, nprms)
1237      Widget w;
1238      XEvent *event;
1239      String *prms;
1240      Cardinal *nprms;
1241 {
1242    GenericPopUp(boardOptions, _("Board Options"), 0);
1243 }
1244
1245 void EngineMenuProc(w, event, prms, nprms)
1246      Widget w;
1247      XEvent *event;
1248      String *prms;
1249      Cardinal *nprms;
1250 {
1251    GenericPopUp(adjudicationOptions, "Adjudicate non-ICS Games", 0);
1252 }
1253
1254 void UciMenuProc(w, event, prms, nprms)
1255      Widget w;
1256      XEvent *event;
1257      String *prms;
1258      Cardinal *nprms;
1259 {
1260    oldCores = appData.smpCores;
1261    oldPonder = appData.ponderNextMove;
1262    GenericPopUp(commonEngineOptions, _("Common Engine Settings"), 0);
1263 }
1264
1265 void NewVariantProc(w, event, prms, nprms)
1266      Widget w;
1267      XEvent *event;
1268      String *prms;
1269      Cardinal *nprms;
1270 {
1271    GenericPopUp(variantDescriptors, _("New Variant"), 0);
1272 }
1273
1274 void OptionsProc(w, event, prms, nprms)
1275      Widget w;
1276      XEvent *event;
1277      String *prms;
1278      Cardinal *nprms;
1279 {
1280    oldPonder = appData.ponderNextMove;
1281    GenericPopUp(generalOptions, _("General Options"), 0);
1282 }
1283
1284 void MatchOptionsProc(w, event, prms, nprms)
1285      Widget w;
1286      XEvent *event;
1287      String *prms;
1288      Cardinal *nprms;
1289 {
1290    NamesToList(firstChessProgramNames, engineList, engineMnemonic);
1291    comboCallback = &AddToTourney;
1292    matchOptions[5].min = -(appData.pairingEngine[0] != NULLCHAR); // with pairing engine, allow Swiss
1293    ASSIGN(tfName, appData.tourneyFile[0] ? appData.tourneyFile : MakeName(appData.defName));
1294    GenericPopUp(matchOptions, _("Match Options"), 0);
1295 }
1296
1297 Option textOptions[100];
1298 void PutText P((char *text, int pos));
1299
1300 void SendString(char *p)
1301 {
1302     char buf[MSG_SIZ], *q;
1303     if(q = strstr(p, "$input")) {
1304         if(!shellUp[4]) return;
1305         strncpy(buf, p, MSG_SIZ);
1306         strncpy(buf + (q-p), q+6, MSG_SIZ-(q-p));
1307         PutText(buf, q-p);
1308         return;
1309     }
1310     snprintf(buf, MSG_SIZ, "%s\n", p);
1311     SendToICS(buf);
1312 }
1313
1314 /* function called when the data to Paste is ready */
1315 static void
1316 SendTextCB(Widget w, XtPointer client_data, Atom *selection,
1317            Atom *type, XtPointer value, unsigned long *len, int *format)
1318 {
1319   char buf[MSG_SIZ], *p = (char*) textOptions[(int)(intptr_t) client_data].choice, *name = (char*) value, *q;
1320   if (value==NULL || *len==0) return; /* nothing selected, abort */
1321   name[*len]='\0';
1322   strncpy(buf, p, MSG_SIZ);
1323   q = strstr(p, "$name");
1324   snprintf(buf + (q-p), MSG_SIZ -(q-p), "%s%s", name, q+5);
1325   SendString(buf);
1326   XtFree(value);
1327 }
1328
1329 void SendText(int n)
1330 {
1331     char *p = (char*) textOptions[n].choice;
1332     if(strstr(p, "$name")) {
1333         XtGetSelectionValue(menuBarWidget,
1334           XA_PRIMARY, XA_STRING,
1335           /* (XtSelectionCallbackProc) */ SendTextCB,
1336           (XtPointer) (intptr_t) n, /* client_data passed to PastePositionCB */
1337           CurrentTime
1338         );
1339     } else SendString(p);
1340 }
1341
1342 void IcsTextProc(w, event, prms, nprms)
1343      Widget w;
1344      XEvent *event;
1345      String *prms;
1346      Cardinal *nprms;
1347 {
1348    int i=0, j;
1349    char *p, *q, *r;
1350    if((p = icsTextMenuString) == NULL) return;
1351    do {
1352         q = r = p; while(*p && *p != ';') p++;
1353         for(j=0; j<p-q; j++) textOptions[i].name[j] = *r++;
1354         textOptions[i].name[j++] = 0;
1355         if(!*p) break;
1356         if(*++p == '\n') p++; // optional linefeed after button-text terminating semicolon
1357         q = p;
1358         textOptions[i].choice = (char**) (r = textOptions[i].name + j);
1359         while(*p && (*p != ';' || p[1] != '\n')) textOptions[i].name[j++] = *p++;
1360         textOptions[i].name[j++] = 0;
1361         if(*p) p += 2;
1362         textOptions[i].max = 135;
1363         textOptions[i].min = i&1;
1364         textOptions[i].handle = NULL;
1365         textOptions[i].target = &SendText;
1366         textOptions[i].textValue = strstr(r, "$input") ? "#80FF80" : strstr(r, "$name") ? "#FF8080" : "#FFFFFF";
1367         textOptions[i].type = Button;
1368    } while(++i < 99 && *p);
1369    if(i == 0) return;
1370    textOptions[i].type = EndMark;
1371    textOptions[i].target = NULL;
1372    textOptions[i].min = 2;
1373    MarkMenu("menuView.ICStex", 3);
1374    GenericPopUp(textOptions, _("ICS text menu"), 3);
1375 }
1376
1377 static char *commentText;
1378 static int commentIndex;
1379 void ClearComment P((int n));
1380 extern char commentTranslations[];
1381
1382 int NewComCallback(int n)
1383 {
1384     ReplaceComment(commentIndex, commentText);
1385     return 1;
1386 }
1387
1388 void SaveChanges(int n)
1389 {
1390     GetWidgetText(&currentOption[0], &commentText);
1391     ReplaceComment(commentIndex, commentText);
1392 }
1393
1394 Option commentOptions[] = {
1395 { 0xD, 200, 250, NULL, (void*) &commentText, "", NULL, TextBox, "" },
1396 {   0,  0,   50, NULL, (void*) &ClearComment, NULL, NULL, Button, "clear" },
1397 {   0,  1,  100, NULL, (void*) &SaveChanges, NULL, NULL, Button, "save changes" },
1398 {   0,  1,    0, NULL, (void*) &NewComCallback, "", NULL, EndMark , "" }
1399 };
1400
1401 void ClearTextWidget(Option *opt)
1402 {
1403     XtCallActionProc(opt->handle, "select-all", NULL, NULL, 0);
1404     XtCallActionProc(opt->handle, "kill-selection", NULL, NULL, 0);
1405 }
1406
1407 void ClearComment(int n)
1408 {
1409     ClearTextWidget(&commentOptions[0]);
1410 }
1411
1412 void NewCommentPopup(char *title, char *text, int index)
1413 {
1414     Widget edit;
1415     Arg args[16];
1416
1417     if(shells[1]) { // if already exists, alter title and content
1418         XtSetArg(args[0], XtNtitle, title);
1419         XtSetValues(shells[1], args, 1);
1420         SetWidgetText(&commentOptions[0], text, 1);
1421     }
1422     if(commentText) free(commentText); commentText = strdup(text);
1423     commentIndex = index;
1424     MarkMenu("menuView.Show Comments", 1);
1425     if(GenericPopUp(commentOptions, title, 1))
1426         XtOverrideTranslations(commentOptions[0].handle, XtParseTranslationTable(commentTranslations));
1427 }
1428
1429 static char *tagsText, *msgText;
1430
1431 int NewTagsCallback(int n)
1432 {
1433     ReplaceTags(tagsText, &gameInfo);
1434     return 1;
1435 }
1436
1437 void changeTags(int n)
1438 {
1439     GetWidgetText(&currentOption[1], &tagsText);
1440     if(bookUp) SaveToBook(tagsText); else
1441     ReplaceTags(tagsText, &gameInfo);
1442 }
1443
1444 Option tagsOptions[] = {
1445 {   0,  0,    0, NULL, NULL, NULL, NULL, Label,  "" },
1446 { 0xD, 200, 200, NULL, (void*) &tagsText, "", NULL, TextBox, "" },
1447 {   0,  0,  100, NULL, (void*) &changeTags, NULL, NULL, Button, "save changes" },
1448 {   0,  1,    0, NULL, (void*) &NewTagsCallback, "", NULL, EndMark , "" }
1449 };
1450
1451 void NewTagsPopup(char *text, char *msg)
1452 {
1453     Widget edit;
1454     Arg args[16];
1455     char *title = bookUp ? _("Edit book") : _("Tags");
1456
1457     if(shells[2]) { // if already exists, alter title and content
1458         SetWidgetText(&tagsOptions[1], text, 2);
1459         XtSetArg(args[0], XtNtitle, title);
1460         XtSetValues(shells[2], args, 1);
1461     }
1462     if(tagsText) free(tagsText); tagsText = strdup(text);
1463     tagsOptions[0].textValue = msg;
1464     MarkMenu("menuView.Show Tags", 2);
1465     GenericPopUp(tagsOptions, title, 2);
1466 }
1467
1468 char *icsText;
1469
1470 Option boxOptions[] = {
1471 {   0, 30,  400, NULL, (void*) &icsText, "", NULL, TextBox, "" },
1472 {   0,  3,    0, NULL, NULL, "", NULL, EndMark , "" }
1473 };
1474
1475 void PutText(char *text, int pos)
1476 {
1477     Arg args[16];
1478     char buf[MSG_SIZ], *p;
1479
1480     if(strstr(text, "$add ") == text) {
1481         GetWidgetText(&boxOptions[0], &p);
1482         snprintf(buf, MSG_SIZ, "%s%s", p, text+5); text = buf;
1483         pos += strlen(p) - 5;
1484     }
1485     SetWidgetText(&boxOptions[0], text, 4);
1486     XtSetArg(args[0], XtNinsertPosition, pos);
1487     XtSetValues(boxOptions[0].handle, args, 1);
1488 //    SetFocus(boxOptions[0].handle, shells[4], NULL, False); // No idea why this does not work, and the following is needed:
1489     XSetInputFocus(xDisplay, XtWindow(boxOptions[0].handle), RevertToPointerRoot, CurrentTime);
1490 }
1491
1492 void InputBoxPopup()
1493 {
1494     MarkMenu("menuView.ICS Input Box", 4);
1495     if(GenericPopUp(boxOptions, _("ICS input box"), 4))
1496         XtOverrideTranslations(boxOptions[0].handle, XtParseTranslationTable(ICSInputTranslations));
1497 }
1498
1499 void TypeInProc(w, event, prms, nprms)
1500      Widget w;
1501      XEvent *event;
1502      String *prms;
1503      Cardinal *nprms;
1504 {
1505     Arg args[2];
1506     String val;
1507
1508     if(prms[0][0] == '1') {
1509         GetWidgetText(&boxOptions[0], &val);
1510         TypeInDoneEvent((char*)val);
1511     }
1512     PopDown(0);
1513 }
1514
1515 char moveTypeInTranslations[] =
1516     "<Key>Return: TypeInProc(1) \n"
1517     "<Key>Escape: TypeInProc(0) \n";
1518
1519 void PopUpMoveDialog(char firstchar)
1520 {
1521     static char buf[2];
1522     buf[0] = firstchar; icsText = buf;
1523     if(GenericPopUp(boxOptions, _("Type a move"), 0))
1524         XtOverrideTranslations(boxOptions[0].handle, XtParseTranslationTable(moveTypeInTranslations));
1525 }
1526
1527 void MoveTypeInProc(Widget widget, caddr_t unused, XEvent *event)
1528 {
1529     char buf[10], keys[32];
1530     KeySym sym;
1531     KeyCode metaL, metaR;
1532     int n = XLookupString(&(event->xkey), buf, 10, &sym, NULL);
1533     XQueryKeymap(xDisplay,keys);
1534     metaL = XKeysymToKeycode(xDisplay, XK_Meta_L);
1535     metaR = XKeysymToKeycode(xDisplay, XK_Meta_R);
1536     if ( n == 1 && *buf > 32 && !(keys[metaL>>3]&1<<(metaL&7)) && !(keys[metaR>>3]&1<<(metaR&7))) // printable, no alt
1537         PopUpMoveDialog(*buf);
1538
1539 }
1540
1541 void
1542 SettingsPopUp(ChessProgramState *cps)
1543 {
1544    currentCps = cps;
1545    GenericPopUp(cps->option, _("Engine Settings"), 0);
1546 }
1547
1548 void FirstSettingsProc(w, event, prms, nprms)
1549      Widget w;
1550      XEvent *event;
1551      String *prms;
1552      Cardinal *nprms;
1553 {
1554     SettingsPopUp(&first);
1555 }
1556
1557 void SecondSettingsProc(w, event, prms, nprms)
1558      Widget w;
1559      XEvent *event;
1560      String *prms;
1561      Cardinal *nprms;
1562 {
1563    if(WaitForEngine(&second, SettingsMenuIfReady)) return;
1564    SettingsPopUp(&second);
1565 }
1566
1567 int InstallOK(int n)
1568 {
1569     PopDown(0); // early popdown, to allow FreezeUI to instate grab
1570     if(engineChoice[0] == engineNr[0][0])  Load(&first, 0); else Load(&second, 1);
1571     return 1;
1572 }
1573
1574 Option installOptions[] = {
1575 {   0,  0,    0, NULL, (void*) &engineLine, (char*) engineMnemonic, engineList, ComboBox, N_("Select engine from list:") },
1576 {   0,  0,    0, NULL, NULL, NULL, NULL, Label, N_("or specify one below:") },
1577 {   0,  0,    0, NULL, (void*) &nickName, NULL, NULL, TextBox, N_("Nickname (optional):") },
1578 {   0,  0,    0, NULL, (void*) &useNick, NULL, NULL, CheckBox, N_("Use nickname in PGN player tags of engine-engine games") },
1579 {   0,  0,    0, NULL, (void*) &engineDir, NULL, NULL, PathName, N_("Engine Directory:") },
1580 {   0,  0,    0, NULL, (void*) &engineName, NULL, NULL, FileName, N_("Engine Command:") },
1581 {   0,  0,    0, NULL, NULL, NULL, NULL, Label, N_("(Directory will be derived from engine path when empty)") },
1582 {   0,  0,    0, NULL, (void*) &isUCI, NULL, NULL, CheckBox, N_("UCI") },
1583 {   0,  0,    0, NULL, (void*) &v1, NULL, NULL, CheckBox, N_("WB protocol v1 (do not wait for engine features)") },
1584 {   0,  0,    0, NULL, (void*) &hasBook, NULL, NULL, CheckBox, N_("Must not use GUI book") },
1585 {   0,  0,    0, NULL, (void*) &addToList, NULL, NULL, CheckBox, N_("Add this engine to the list") },
1586 {   0,  0,    0, NULL, (void*) &storeVariant, NULL, NULL, CheckBox, N_("Force current variant with this engine") },
1587 {   0,  0,    0, NULL, (void*) &engineChoice, (char*) engineNr, engineNr, ComboBox, N_("Load mentioned engine as") },
1588 {   0,  1,    0, NULL, (void*) &InstallOK, "", NULL, EndMark , "" }
1589 };
1590
1591 void LoadEngineProc(w, event, prms, nprms)
1592      Widget w;
1593      XEvent *event;
1594      String *prms;
1595      Cardinal *nprms;
1596 {
1597    isUCI = storeVariant = v1 = useNick = False; addToList = hasBook = True; // defaults
1598    if(engineChoice) free(engineChoice); engineChoice = strdup(engineNr[0]);
1599    if(engineLine)   free(engineLine);   engineLine = strdup("");
1600    if(engineDir)    free(engineDir);    engineDir = strdup("");
1601    if(nickName)     free(nickName);     nickName = strdup("");
1602    if(params)       free(params);       params = strdup("");
1603    NamesToList(firstChessProgramNames, engineList, engineMnemonic);
1604    GenericPopUp(installOptions, _("Load engine"), 0);
1605 }
1606
1607 void EditBookProc(w, event, prms, nprms)
1608      Widget w;
1609      XEvent *event;
1610      String *prms;
1611      Cardinal *nprms;
1612 {
1613     EditBookEvent();
1614 }
1615
1616 void SetRandom P((int n));
1617
1618 int ShuffleOK(int n)
1619 {
1620     ResetGameEvent();
1621     return 1;
1622 }
1623
1624 Option shuffleOptions[] = {
1625 {   0,  0,   50, NULL, (void*) &shuffleOpenings, NULL, NULL, CheckBox, "shuffle" },
1626 { 0,-1,2000000000, NULL, (void*) &appData.defaultFrcPosition, "", NULL, Spin, N_("Start-position number:") },
1627 {   0,  0,    0, NULL, (void*) &SetRandom, NULL, NULL, Button, "randomize" },
1628 {   0,  1,    0, NULL, (void*) &SetRandom, NULL, NULL, Button, "pick fixed" },
1629 {   0,  1,    0, NULL, (void*) &ShuffleOK, "", NULL, EndMark , "" }
1630 };
1631
1632 void SetRandom(int n)
1633 {
1634     int r = n==2 ? -1 : rand() & (1<<30)-1;
1635     char buf[MSG_SIZ];
1636     Arg args[2];
1637     snprintf(buf, MSG_SIZ,  "%d", r);
1638     SetWidgetText(&shuffleOptions[1], buf, 0);
1639     SetWidgetState(&shuffleOptions[0], True);
1640 }
1641
1642 void ShuffleMenuProc(w, event, prms, nprms)
1643      Widget w;
1644      XEvent *event;
1645      String *prms;
1646      Cardinal *nprms;
1647 {
1648     GenericPopUp(shuffleOptions, _("New Shuffle Game"), 0);
1649 }
1650
1651 int tmpMoves, tmpTc, tmpInc, tmpOdds1, tmpOdds2, tcType;
1652
1653 void ShowTC(int n)
1654 {
1655 }
1656
1657 void SetTcType P((int n));
1658
1659 char *Value(int n)
1660 {
1661         static char buf[MSG_SIZ];
1662         snprintf(buf, MSG_SIZ, "%d", n);
1663         return buf;
1664 }
1665
1666 int TcOK(int n)
1667 {
1668     char *tc;
1669     if(tcType == 0 && tmpMoves <= 0) return 0;
1670     if(tcType == 2 && tmpInc <= 0) return 0;
1671     GetWidgetText(&currentOption[4], &tc); // get original text, in case it is min:sec
1672     switch(tcType) {
1673       case 0:
1674         if(!ParseTimeControl(tc, -1, tmpMoves)) return 0;
1675         appData.movesPerSession = tmpMoves;
1676         ASSIGN(appData.timeControl, tc);
1677         appData.timeIncrement = -1;
1678         break;
1679       case 1:
1680         if(!ParseTimeControl(tc, tmpInc, 0)) return 0;
1681         ASSIGN(appData.timeControl, tc);
1682         appData.timeIncrement = tmpInc;
1683         break;
1684       case 2:
1685         searchTime = tmpInc;
1686     }
1687     appData.firstTimeOdds = first.timeOdds = tmpOdds1;
1688     appData.secondTimeOdds = second.timeOdds = tmpOdds2;
1689     Reset(True, True);
1690     return 1;
1691 }
1692
1693 Option tcOptions[] = {
1694 {   0,  0,    0, NULL, (void*) &SetTcType, NULL, NULL, Button, N_("classical") },
1695 {   0,  1,    0, NULL, (void*) &SetTcType, NULL, NULL, Button, N_("incremental") },
1696 {   0,  1,    0, NULL, (void*) &SetTcType, NULL, NULL, Button, N_("fixed max") },
1697 {   0,  0,  200, NULL, (void*) &tmpMoves, NULL, NULL, Spin, N_("Moves per session:") },
1698 {   0,  0,10000, NULL, (void*) &tmpTc, NULL, NULL, Spin, N_("Initial time (min):") },
1699 {   0, 0, 10000, NULL, (void*) &tmpInc, NULL, NULL, Spin, N_("Increment or max (sec/move):") },
1700 {   0,  0,    0, NULL, NULL, NULL, NULL, Label, N_("Time-Odds factors:") },
1701 {   0,  1, 1000, NULL, (void*) &tmpOdds1, NULL, NULL, Spin, N_("Engine #1") },
1702 {   0,  1, 1000, NULL, (void*) &tmpOdds2, NULL, NULL, Spin, N_("Engine #2 / Human") },
1703 {   0,  0,    0, NULL, (void*) &TcOK, "", NULL, EndMark , "" }
1704 };
1705
1706 void SetTcType(int n)
1707 {
1708     switch(tcType = n) {
1709       case 0:
1710         SetWidgetText(&tcOptions[3], Value(tmpMoves), 0);
1711         SetWidgetText(&tcOptions[4], Value(tmpTc), 0);
1712         SetWidgetText(&tcOptions[5], _("Unused"), 0);
1713         break;
1714       case 1:
1715         SetWidgetText(&tcOptions[3], _("Unused"), 0);
1716         SetWidgetText(&tcOptions[4], Value(tmpTc), 0);
1717         SetWidgetText(&tcOptions[5], Value(tmpInc), 0);
1718         break;
1719       case 2:
1720         SetWidgetText(&tcOptions[3], _("Unused"), 0);
1721         SetWidgetText(&tcOptions[4], _("Unused"), 0);
1722         SetWidgetText(&tcOptions[5], Value(tmpInc), 0);
1723     }
1724 }
1725
1726 void TimeControlProc(w, event, prms, nprms)
1727      Widget w;
1728      XEvent *event;
1729      String *prms;
1730      Cardinal *nprms;
1731 {
1732    tmpMoves = appData.movesPerSession;
1733    tmpInc = appData.timeIncrement; if(tmpInc < 0) tmpInc = 0;
1734    tmpOdds1 = tmpOdds2 = 1; tcType = 0;
1735    tmpTc = atoi(appData.timeControl);
1736    GenericPopUp(tcOptions, _("Time Control"), 0);
1737 }
1738
1739 //---------------------------- Chat Windows ----------------------------------------------
1740
1741 void OutputChatMessage(int partner, char *mess)
1742 {
1743     return; // dummy
1744 }
1745