Use ListBox in stead of ComboBox in Load Engine dialog
[xboard.git] / dialogs.c
1 /*
2  * dialogs.c -- platform-independent code for dialogs of XBoard
3  *
4  * Copyright 2000, 2009, 2010, 2011, 2012 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 "common.h"
51 #include "backend.h"
52 #include "xboard.h"
53 #include "menus.h"
54 #include "dialogs.h"
55 #include "gettext.h"
56
57 #ifdef ENABLE_NLS
58 # define  _(s) gettext (s)
59 # define N_(s) gettext_noop (s)
60 #else
61 # define  _(s) (s)
62 # define N_(s)  s
63 #endif
64
65
66 int values[MAX_OPTIONS];
67 ChessProgramState *currentCps;
68
69 //----------------------------Generic dialog --------------------------------------------
70
71 // cloned from Engine Settings dialog (and later merged with it)
72
73 char *marked[NrOfDialogs];
74 Boolean shellUp[NrOfDialogs];
75
76 void
77 MarkMenu (char *item, int dlgNr)
78 {
79     MarkMenuItem(marked[dlgNr] = item, True);
80 }
81
82 void
83 AddLine (Option *opt, char *s)
84 {
85     AppendText(opt, s);
86     AppendText(opt, "\n");
87 }
88
89 //---------------------------------------------- Update dialog controls ------------------------------------
90
91 int
92 SetCurrentComboSelection (Option *opt)
93 {
94     int j;
95     if(!opt->textValue) opt->value = *(int*)opt->target; /* numeric */else {
96         for(j=0; opt->choice[j]; j++) // look up actual value in list of possible values, to get selection nr
97             if(*(char**)opt->target && !strcmp(*(char**)opt->target, ((char**)opt->textValue)[j])) break;
98         opt->value = j + (opt->choice[j] == NULL);
99     }
100     return opt->value;
101 }
102
103 void
104 GenericUpdate (Option *opts, int selected)
105 {
106     int i, j;
107     char buf[MSG_SIZ];
108     float x;
109         for(i=0; ; i++) {
110             if(selected >= 0) { if(i < selected) continue; else if(i > selected) break; }
111             switch(opts[i].type) {
112                 case TextBox:
113                 case FileName:
114                 case PathName:
115                     SetWidgetText(&opts[i],  *(char**) opts[i].target, -1);
116                     break;
117                 case Spin:
118                     sprintf(buf, "%d", *(int*) opts[i].target);
119                     SetWidgetText(&opts[i], buf, -1);
120                     break;
121                 case Fractional:
122                     sprintf(buf, "%4.2f", *(float*) opts[i].target);
123                     SetWidgetText(&opts[i], buf, -1);
124                     break;
125                 case CheckBox:
126                     SetWidgetState(&opts[i],  *(Boolean*) opts[i].target);
127                     break;
128                 case ComboBox:
129                   if(opts[i].min & COMBO_CALLBACK) break;
130                   SetCurrentComboSelection(opts+i);
131                     // TODO: actually display this (but it is never used that way...)
132                     break;
133                 case EndMark:
134                     return;
135             default:
136                 printf("GenericUpdate: unexpected case in switch.\n");
137                 case ListBox:
138                 case Button:
139                 case SaveButton:
140                 case Label:
141                 case Break:
142               break;
143             }
144         }
145 }
146
147 //------------------------------------------- Read out dialog controls ------------------------------------
148
149 int
150 GenericReadout (Option *opts, int selected)
151 {
152     int i, j, res=1;
153     char *val;
154     char buf[MSG_SIZ], **dest;
155     float x;
156         for(i=0; ; i++) { // send all options that had to be OK-ed to engine
157             if(selected >= 0) { if(i < selected) continue; else if(i > selected) break; }
158             switch(opts[i].type) {
159                 case TextBox:
160                 case FileName:
161                 case PathName:
162                     GetWidgetText(&opts[i], &val);
163                     dest = currentCps ? &(opts[i].textValue) : (char**) opts[i].target;
164                     if(*dest == NULL || strcmp(*dest, val)) {
165                         if(currentCps) {
166                             snprintf(buf, MSG_SIZ,  "option %s=%s\n", opts[i].name, val);
167                             SendToProgram(buf, currentCps);
168                         } else {
169                             if(*dest) free(*dest);
170                             *dest = malloc(strlen(val)+1);
171                         }
172                         safeStrCpy(*dest, val, MSG_SIZ - (*dest - opts[i].name)); // copy text there
173                     }
174                     break;
175                 case Spin:
176                 case Fractional:
177                     GetWidgetText(&opts[i], &val);
178                     x = 0.0; // Initialise because sscanf() will fail if non-numeric text is entered
179                     sscanf(val, "%f", &x);
180                     if(x > opts[i].max) x = opts[i].max;
181                     if(x < opts[i].min) x = opts[i].min;
182                     if(opts[i].type == Fractional)
183                         *(float*) opts[i].target = x; // engines never have float options!
184                     else if(opts[i].value != x) {
185                         opts[i].value = x;
186                         if(currentCps) {
187                             snprintf(buf, MSG_SIZ,  "option %s=%.0f\n", opts[i].name, x);
188                             SendToProgram(buf, currentCps);
189                         } else *(int*) opts[i].target = x;
190                     }
191                     break;
192                 case CheckBox:
193                     j = 0;
194                     GetWidgetState(&opts[i], &j);
195                     if(opts[i].value != j) {
196                         opts[i].value = j;
197                         if(currentCps) {
198                             snprintf(buf, MSG_SIZ,  "option %s=%d\n", opts[i].name, j);
199                             SendToProgram(buf, currentCps);
200                         } else *(Boolean*) opts[i].target = j;
201                     }
202                     break;
203                 case ComboBox:
204                     if(opts[i].min & COMBO_CALLBACK) break;
205                     if(!opts[i].textValue) { *(int*)opts[i].target == opts[i].value; break; } // numeric
206                     val = ((char**)opts[i].textValue)[values[i]];
207                     if(currentCps) {
208                         if(opts[i].value == values[i]) break; // not changed
209                         opts[i].value = values[i];
210                         snprintf(buf, MSG_SIZ,  "option %s=%s\n", opts[i].name, opts[i].choice[values[i]]);
211                         SendToProgram(buf, currentCps);
212                     } else if(val && (*(char**) opts[i].target == NULL || strcmp(*(char**) opts[i].target, val))) {
213                       if(*(char**) opts[i].target) free(*(char**) opts[i].target);
214                       *(char**) opts[i].target = strdup(val);
215                     }
216                     break;
217                 case EndMark:
218                     if(opts[i].target) // callback for implementing necessary actions on OK (like redraw)
219                         res = ((OKCallback*) opts[i].target)(i);
220                     break;
221             default:
222                 printf("GenericReadout: unexpected case in switch.\n");
223                 case ListBox:
224                 case Button:
225                 case SaveButton:
226                 case Label:
227                 case Break:
228               break;
229             }
230             if(opts[i].type == EndMark) break;
231         }
232         return res;
233 }
234
235 //------------------------------------------- Match Options ------------------------------------------------------
236
237 char *engineName, *engineChoice, *tfName;
238 char *engineList[MAXENGINES] = {" "}, *engineMnemonic[MAXENGINES] = {""};
239
240 static void AddToTourney P((int n));
241 static void CloneTourney P((void));
242 static void ReplaceParticipant P((void));
243 static void UpgradeParticipant P((void));
244
245 static int
246 MatchOK (int n)
247 {
248     ASSIGN(appData.participants, engineName);
249     if(!CreateTourney(tfName) || matchMode) return matchMode || !appData.participants[0];
250     PopDown(TransientDlg); // early popdown to prevent FreezeUI called through MatchEvent from causing XtGrab warning
251     MatchEvent(2); // start tourney
252     return FALSE;  // no double PopDown!
253 }
254
255 static Option matchOptions[] = {
256 { 0,  0,          0, NULL, (void*) &tfName, ".trn", NULL, FileName, N_("Tournament file:") },
257 { 0,  0,          0, NULL, (void*) &appData.roundSync, "", NULL, CheckBox, N_("Sync after round") },
258 { 0, SAME_ROW|LL, 0, NULL, NULL, "", NULL, Label, N_("    (for concurrent playing of a single") },
259 { 0,  0,          0, NULL, (void*) &appData.cycleSync, "", NULL, CheckBox, N_("Sync after cycle") },
260 { 0, SAME_ROW|LL, 0, NULL, NULL, "", NULL, Label, N_("      tourney with multiple XBoards)") },
261 { 150, T_VSCRL | T_FILL | T_WRAP,
262                   0, NULL, (void*) &engineName, "", NULL, TextBox, N_("Tourney participants:") },
263 { 0,  COMBO_CALLBACK | NO_GETTEXT,
264                   0, NULL, (void*) &AddToTourney, (char*) (engineMnemonic+1), (engineMnemonic+1), ComboBox, N_("Select Engine:") },
265 { 0,  0,         10, NULL, (void*) &appData.tourneyType, "", NULL, Spin, N_("Tourney type (0 = round-robin, 1 = gauntlet):") },
266 { 0,  1, 1000000000, NULL, (void*) &appData.tourneyCycles, "", NULL, Spin, N_("Number of tourney cycles (or Swiss rounds):") },
267 { 0,  1, 1000000000, NULL, (void*) &appData.defaultMatchGames, "", NULL, Spin, N_("Default Number of Games in Match (or Pairing):") },
268 { 0,  0, 1000000000, NULL, (void*) &appData.matchPause, "", NULL, Spin, N_("Pause between Match Games (msec):") },
269 { 0,  0,          0, NULL, (void*) &appData.saveGameFile, ".pgn", NULL, FileName, N_("Save Tourney Games on:") },
270 { 0,  0,          0, NULL, (void*) &appData.loadGameFile, ".pgn", NULL, FileName, N_("Game File with Opening Lines:") },
271 { 0, -2, 1000000000, NULL, (void*) &appData.loadGameIndex, "", NULL, Spin, N_("Game Number (-1 or -2 = Auto-Increment):") },
272 { 0,  0,          0, NULL, (void*) &appData.loadPositionFile, ".fen", NULL, FileName, N_("File with Start Positions:") },
273 { 0, -2, 1000000000, NULL, (void*) &appData.loadPositionIndex, "", NULL, Spin, N_("Position Number (-1 or -2 = Auto-Increment):") },
274 { 0,  0, 1000000000, NULL, (void*) &appData.rewindIndex, "", NULL, Spin, N_("Rewind Index after this many Games (0 = never):") },
275 { 0,  0,          0, NULL, (void*) &appData.defNoBook, "", NULL, CheckBox, N_("Disable own engine books by default") },
276 { 0,  0,          0, NULL, (void*) &ReplaceParticipant, NULL, NULL, Button, N_("Replace Engine") },
277 { 0, SAME_ROW,    0, NULL, (void*) &UpgradeParticipant, NULL, NULL, Button, N_("Upgrade Engine") },
278 { 0, SAME_ROW,    0, NULL, (void*) &CloneTourney, NULL, NULL, Button, N_("Clone Tourney") },
279 { 0, SAME_ROW,    0, NULL, (void*) &MatchOK, "", NULL, EndMark , "" }
280 };
281
282 static void
283 ReplaceParticipant ()
284 {
285     GenericReadout(matchOptions, 5);
286     Substitute(strdup(engineName), True);
287 }
288
289 static void
290 UpgradeParticipant ()
291 {
292     GenericReadout(matchOptions, 5);
293     Substitute(strdup(engineName), False);
294 }
295
296 static void
297 CloneTourney ()
298 {
299     FILE *f;
300     char *name;
301     GetWidgetText(matchOptions, &name);
302     if(name && name[0] && (f = fopen(name, "r")) ) {
303         char *saveSaveFile;
304         saveSaveFile = appData.saveGameFile; appData.saveGameFile = NULL; // this is a persistent option, protect from change
305         ParseArgsFromFile(f);
306         engineName = appData.participants; GenericUpdate(matchOptions, -1);
307         FREE(appData.saveGameFile); appData.saveGameFile = saveSaveFile;
308     } else DisplayError(_("First you must specify an existing tourney file to clone"), 0);
309 }
310
311 static void
312 AddToTourney (int n)
313 {
314     AddLine(&matchOptions[5], engineMnemonic[values[6]+1]);
315 }
316
317 void
318 MatchOptionsProc ()
319 {
320    NamesToList(firstChessProgramNames, engineList, engineMnemonic, "all");
321    matchOptions[7].min = -(appData.pairingEngine[0] != NULLCHAR); // with pairing engine, allow Swiss
322    ASSIGN(tfName, appData.tourneyFile[0] ? appData.tourneyFile : MakeName(appData.defName));
323    ASSIGN(engineName, appData.participants);
324    GenericPopUp(matchOptions, _("Match Options"), TransientDlg, BoardWindow, MODAL, 0);
325 }
326
327 // ------------------------------------------- General Options --------------------------------------------------
328
329 static int oldShow, oldBlind, oldPonder;
330
331 static int
332 GeneralOptionsOK (int n)
333 {
334         int newPonder = appData.ponderNextMove;
335         appData.ponderNextMove = oldPonder;
336         PonderNextMoveEvent(newPonder);
337         if(!appData.highlightLastMove) ClearHighlights(), ClearPremoveHighlights();
338         if(oldShow != appData.showCoords || oldBlind != appData.blindfold) DrawPosition(TRUE, NULL);
339         return 1;
340 }
341
342 static Option generalOptions[] = {
343 { 0,  0, 0, NULL, (void*) &appData.whitePOV, "", NULL, CheckBox, N_("Absolute Analysis Scores") },
344 { 0,  0, 0, NULL, (void*) &appData.sweepSelect, "", NULL, CheckBox, N_("Almost Always Queen (Detour Under-Promote)") },
345 { 0,  0, 0, NULL, (void*) &appData.animateDragging, "", NULL, CheckBox, N_("Animate Dragging") },
346 { 0,  0, 0, NULL, (void*) &appData.animate, "", NULL, CheckBox, N_("Animate Moving") },
347 { 0,  0, 0, NULL, (void*) &appData.autoCallFlag, "", NULL, CheckBox, N_("Auto Flag") },
348 { 0,  0, 0, NULL, (void*) &appData.autoFlipView, "", NULL, CheckBox, N_("Auto Flip View") },
349 { 0,  0, 0, NULL, (void*) &appData.blindfold, "", NULL, CheckBox, N_("Blindfold") },
350 { 0,  0, 0, NULL, (void*) &appData.dropMenu, "", NULL, CheckBox, N_("Drop Menu") },
351 { 0,  0, 0, NULL, (void*) &appData.hideThinkingFromHuman, "", NULL, CheckBox, N_("Hide Thinking from Human") },
352 { 0,  0, 0, NULL, (void*) &appData.highlightLastMove, "", NULL, CheckBox, N_("Highlight Last Move") },
353 { 0,  0, 0, NULL, (void*) &appData.highlightMoveWithArrow, "", NULL, CheckBox, N_("Highlight with Arrow") },
354 { 0,  0, 0, NULL, (void*) &appData.ringBellAfterMoves, "", NULL, CheckBox, N_("Move Sound") },
355 { 0,  0, 0, NULL, (void*) &appData.oneClick, "", NULL, CheckBox, N_("One-Click Moving") },
356 { 0,  0, 0, NULL, (void*) &appData.periodicUpdates, "", NULL, CheckBox, N_("Periodic Updates (in Analysis Mode)") },
357 { 0,  0, 0, NULL, (void*) &appData.ponderNextMove, "", NULL, CheckBox, N_("Ponder Next Move") },
358 { 0,  0, 0, NULL, (void*) &appData.popupExitMessage, "", NULL, CheckBox, N_("Popup Exit Messages") },
359 { 0,  0, 0, NULL, (void*) &appData.popupMoveErrors, "", NULL, CheckBox, N_("Popup Move Errors") },
360 { 0,  0, 0, NULL, (void*) &appData.showEvalInMoveHistory, "", NULL, CheckBox, N_("Scores in Move List") },
361 { 0,  0, 0, NULL, (void*) &appData.showCoords, "", NULL, CheckBox, N_("Show Coordinates") },
362 { 0,  0, 0, NULL, (void*) &appData.markers, "", NULL, CheckBox, N_("Show Target Squares") },
363 { 0,  0, 0, NULL, (void*) &appData.useStickyWindows, "", NULL, CheckBox, N_("Sticky Windows") },
364 { 0,  0, 0, NULL, (void*) &appData.testLegality, "", NULL, CheckBox, N_("Test Legality") },
365 { 0,  0, 0, NULL, (void*) &appData.topLevel, "", NULL, CheckBox, N_("Top-Level Dialogs") },
366 { 0, 0,10,  NULL, (void*) &appData.flashCount, "", NULL, Spin, N_("Flash Moves (0 = no flashing):") },
367 { 0, 1,10,  NULL, (void*) &appData.flashRate, "", NULL, Spin, N_("Flash Rate (high = fast):") },
368 { 0, 5,100, NULL, (void*) &appData.animSpeed, "", NULL, Spin, N_("Animation Speed (high = slow):") },
369 { 0, 1,5,   NULL, (void*) &appData.zoom, "", NULL, Spin, N_("Zoom factor in Evaluation Graph:") },
370 { 0,  0, 0, NULL, (void*) &GeneralOptionsOK, "", NULL, EndMark , "" }
371 };
372
373 void
374 OptionsProc ()
375 {
376    oldPonder = appData.ponderNextMove;
377    oldShow = appData.showCoords; oldBlind = appData.blindfold;
378    GenericPopUp(generalOptions, _("General Options"), TransientDlg, BoardWindow, MODAL, 0);
379 }
380
381 //---------------------------------------------- New Variant ------------------------------------------------
382
383 static void Pick P((int n));
384
385 static char warning[MSG_SIZ];
386
387 static Option variantDescriptors[] = {
388 { 0, 0, 275, NULL, NULL, NULL, NULL, Label, warning },
389 { VariantNormal,        0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("normal")},
390 { VariantFairy,  SAME_ROW, 135, NULL, (void*) &Pick, "#BFBFBF", NULL, Button, N_("fairy")},
391 { VariantFischeRandom,  0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("FRC")},
392 { VariantSChess, SAME_ROW, 135, NULL, (void*) &Pick, "#FFBFBF", NULL, Button, N_("Seirawan")},
393 { VariantWildCastle,    0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("wild castle")},
394 { VariantSuper,  SAME_ROW, 135, NULL, (void*) &Pick, "#FFBFBF", NULL, Button, N_("Superchess")},
395 { VariantNoCastle,      0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("no castle")},
396 { VariantCrazyhouse,SAME_ROW,135,NULL,(void*) &Pick, "#FFBFBF", NULL, Button, N_("crazyhouse")},
397 { VariantKnightmate,    0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("knightmate")},
398 { VariantBughouse,SAME_ROW,135, NULL, (void*) &Pick, "#FFBFBF", NULL, Button, N_("bughouse")},
399 { VariantBerolina,      0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("berolina")},
400 { VariantShogi,  SAME_ROW, 135, NULL, (void*) &Pick, "#BFFFFF", NULL, Button, N_("shogi (9x9)")},
401 { VariantCylinder,      0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("cylinder")},
402 { VariantXiangqi, SAME_ROW,135, NULL, (void*) &Pick, "#BFFFFF", NULL, Button, N_("xiangqi (9x10)")},
403 { VariantShatranj,      0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("shatranj")},
404 { VariantCourier, SAME_ROW,135, NULL, (void*) &Pick, "#BFFFBF", NULL, Button, N_("courier (12x8)")},
405 { VariantMakruk,        0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("makruk")},
406 { VariantGreat,  SAME_ROW, 135, NULL, (void*) &Pick, "#BFBFFF", NULL, Button, N_("Great Shatranj (10x8)")},
407 { VariantAtomic,        0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("atomic")},
408 { VariantFalcon, SAME_ROW, 135, NULL, (void*) &Pick, "#BFBFFF", NULL, Button, N_("falcon (10x8)")},
409 { VariantTwoKings,      0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("two kings")},
410 { VariantCapablanca,SAME_ROW,135,NULL,(void*) &Pick, "#BFBFFF", NULL, Button, N_("Capablanca (10x8)")},
411 { Variant3Check,        0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("3-checks")},
412 { VariantGothic, SAME_ROW, 135, NULL, (void*) &Pick, "#BFBFFF", NULL, Button, N_("Gothic (10x8)")},
413 { VariantSuicide,       0, 135, NULL, (void*) &Pick, "#FFFFBF", NULL, Button, N_("suicide")},
414 { VariantJanus,  SAME_ROW, 135, NULL, (void*) &Pick, "#BFBFFF", NULL, Button, N_("janus (10x8)")},
415 { VariantGiveaway,      0, 135, NULL, (void*) &Pick, "#FFFFBF", NULL, Button, N_("give-away")},
416 { VariantCapaRandom,SAME_ROW,135,NULL,(void*) &Pick, "#BFBFFF", NULL, Button, N_("CRC (10x8)")},
417 { VariantLosers,        0, 135, NULL, (void*) &Pick, "#FFFFBF", NULL, Button, N_("losers")},
418 { VariantGrand,  SAME_ROW, 135, NULL, (void*) &Pick, "#5070FF", NULL, Button, N_("grand (10x10)")},
419 { VariantSpartan,       0, 135, NULL, (void*) &Pick, "#FF0000", NULL, Button, N_("Spartan")},
420 { 0, 0, 0, NULL, NULL, NULL, NULL, Label, N_("Board size ( -1 = default for selected variant):")},
421 { 0, -1, BOARD_RANKS-1, NULL, (void*) &appData.NrRanks, "", NULL, Spin, N_("Number of Board Ranks:") },
422 { 0, -1, BOARD_FILES, NULL, (void*) &appData.NrFiles, "", NULL, Spin, N_("Number of Board Files:") },
423 { 0, -1, BOARD_RANKS-1, NULL, (void*) &appData.holdingsSize, "", NULL, Spin, N_("Holdings Size:") },
424 { 0, 0, 0, NULL, NULL, NULL, NULL, Label,
425                                 N_("WARNING: variants with un-orthodox\n"
426                                   "pieces only have built-in bitmaps\n"
427                                   "for -boardSize middling, bulky and\n"
428                                   "petite, and substitute king or amazon\n"
429                                   "for missing bitmaps. (See manual.)")},
430 { 0, NO_OK, 0, NULL, NULL, "", NULL, EndMark , "" }
431 };
432
433 static void
434 Pick (int n)
435 {
436         VariantClass v = variantDescriptors[n].value;
437         if(!appData.noChessProgram) {
438             char *name = VariantName(v), buf[MSG_SIZ];
439             if (first.protocolVersion > 1 && StrStr(first.variants, name) == NULL) {
440                 /* [HGM] in protocol 2 we check if variant is suported by engine */
441               snprintf(buf, MSG_SIZ,  _("Variant %s not supported by %s"), name, first.tidy);
442                 DisplayError(buf, 0);
443                 return; /* ignore OK if first engine does not support it */
444             } else
445             if (second.initDone && second.protocolVersion > 1 && StrStr(second.variants, name) == NULL) {
446               snprintf(buf, MSG_SIZ,  _("Warning: second engine (%s) does not support this!"), second.tidy);
447                 DisplayError(buf, 0);   /* use of second engine is optional; only warn user */
448             }
449         }
450
451         GenericReadout(variantDescriptors, -1); // make sure ranks and file settings are read
452
453         gameInfo.variant = v;
454         appData.variant = VariantName(v);
455
456         shuffleOpenings = FALSE; /* [HGM] shuffle: possible shuffle reset when we switch */
457         startedFromPositionFile = FALSE; /* [HGM] loadPos: no longer valid in new variant */
458         appData.pieceToCharTable = NULL;
459         appData.pieceNickNames = "";
460         appData.colorNickNames = "";
461         Reset(True, True);
462         PopDown(TransientDlg);
463         return;
464 }
465
466 void
467 NewVariantProc ()
468 {
469    sprintf(warning, _("All variants not supported by first engine\n(currently %s) are disabled"), first.tidy);
470    GenericPopUp(variantDescriptors, _("New Variant"), TransientDlg, BoardWindow, MODAL, 0);
471 }
472
473 //------------------------------------------- Common Engine Options -------------------------------------
474
475 static int oldCores;
476
477 static int
478 CommonOptionsOK (int n)
479 {
480         int newPonder = appData.ponderNextMove;
481         // make sure changes are sent to first engine by re-initializing it
482         // if it was already started pre-emptively at end of previous game
483         if(gameMode == BeginningOfGame) Reset(True, True); else {
484             // Some changed setting need immediate sending always.
485             if(oldCores != appData.smpCores)
486                 NewSettingEvent(False, &(first.maxCores), "cores", appData.smpCores);
487             appData.ponderNextMove = oldPonder;
488             PonderNextMoveEvent(newPonder);
489         }
490         return 1;
491 }
492
493 static Option commonEngineOptions[] = {
494 { 0,  0,    0, NULL, (void*) &appData.ponderNextMove, "", NULL, CheckBox, N_("Ponder Next Move") },
495 { 0,  0, 1000, NULL, (void*) &appData.smpCores, "", NULL, Spin, N_("Maximum Number of CPUs per Engine:") },
496 { 0,  0,    0, NULL, (void*) &appData.polyglotDir, "", NULL, PathName, N_("Polygot Directory:") },
497 { 0,  0,16000, NULL, (void*) &appData.defaultHashSize, "", NULL, Spin, N_("Hash-Table Size (MB):") },
498 { 0,  0,    0, NULL, (void*) &appData.defaultPathEGTB, "", NULL, PathName, N_("Nalimov EGTB Path:") },
499 { 0,  0, 1000, NULL, (void*) &appData.defaultCacheSizeEGTB, "", NULL, Spin, N_("EGTB Cache Size (MB):") },
500 { 0,  0,    0, NULL, (void*) &appData.usePolyglotBook, "", NULL, CheckBox, N_("Use GUI Book") },
501 { 0,  0,    0, NULL, (void*) &appData.polyglotBook, ".bin", NULL, FileName, N_("Opening-Book Filename:") },
502 { 0,  0,  100, NULL, (void*) &appData.bookDepth, "", NULL, Spin, N_("Book Depth (moves):") },
503 { 0,  0,  100, NULL, (void*) &appData.bookStrength, "", NULL, Spin, N_("Book Variety (0) vs. Strength (100):") },
504 { 0,  0,    0, NULL, (void*) &appData.firstHasOwnBookUCI, "", NULL, CheckBox, N_("Engine #1 Has Own Book") },
505 { 0,  0,    0, NULL, (void*) &appData.secondHasOwnBookUCI, "", NULL, CheckBox, N_("Engine #2 Has Own Book          ") },
506 { 0,SAME_ROW,0,NULL, (void*) &CommonOptionsOK, "", NULL, EndMark , "" }
507 };
508
509 void
510 UciMenuProc ()
511 {
512    oldCores = appData.smpCores;
513    oldPonder = appData.ponderNextMove;
514    GenericPopUp(commonEngineOptions, _("Common Engine Settings"), TransientDlg, BoardWindow, MODAL, 0);
515 }
516
517 //------------------------------------------ Adjudication Options --------------------------------------
518
519 static Option adjudicationOptions[] = {
520 { 0, 0,    0, NULL, (void*) &appData.checkMates, "", NULL, CheckBox, N_("Detect all Mates") },
521 { 0, 0,    0, NULL, (void*) &appData.testClaims, "", NULL, CheckBox, N_("Verify Engine Result Claims") },
522 { 0, 0,    0, NULL, (void*) &appData.materialDraws, "", NULL, CheckBox, N_("Draw if Insufficient Mating Material") },
523 { 0, 0,    0, NULL, (void*) &appData.trivialDraws, "", NULL, CheckBox, N_("Adjudicate Trivial Draws (3-Move Delay)") },
524 { 0, 0,100,   NULL, (void*) &appData.ruleMoves, "", NULL, Spin, N_("N-Move Rule:") },
525 { 0, 0,    6, NULL, (void*) &appData.drawRepeats, "", NULL, Spin, N_("N-fold Repeats:") },
526 { 0, 0,1000,  NULL, (void*) &appData.adjudicateDrawMoves, "", NULL, Spin, N_("Draw after N Moves Total:") },
527 { 0, -5000,0, NULL, (void*) &appData.adjudicateLossThreshold, "", NULL, Spin, N_("Win / Loss Threshold:") },
528 { 0, 0,    0, NULL, (void*) &first.scoreIsAbsolute, "", NULL, CheckBox, N_("Negate Score of Engine #1") },
529 { 0, 0,    0, NULL, (void*) &second.scoreIsAbsolute, "", NULL, CheckBox, N_("Negate Score of Engine #2") },
530 { 0,SAME_ROW, 0, NULL, NULL, "", NULL, EndMark , "" }
531 };
532
533 void
534 EngineMenuProc ()
535 {
536    GenericPopUp(adjudicationOptions, _("Adjudicate non-ICS Games"), TransientDlg, BoardWindow, MODAL, 0);
537 }
538
539 //--------------------------------------------- ICS Options ---------------------------------------------
540
541 static int
542 IcsOptionsOK (int n)
543 {
544     ParseIcsTextColors();
545     return 1;
546 }
547
548 Option icsOptions[] = {
549 { 0, 0, 0, NULL, (void*) &appData.autoKibitz, "",  NULL, CheckBox, N_("Auto-Kibitz") },
550 { 0, 0, 0, NULL, (void*) &appData.autoComment, "", NULL, CheckBox, N_("Auto-Comment") },
551 { 0, 0, 0, NULL, (void*) &appData.autoObserve, "", NULL, CheckBox, N_("Auto-Observe") },
552 { 0, 0, 0, NULL, (void*) &appData.autoRaiseBoard, "", NULL, CheckBox, N_("Auto-Raise Board") },
553 { 0, 0, 0, NULL, (void*) &appData.bgObserve, "",   NULL, CheckBox, N_("Background Observe while Playing") },
554 { 0, 0, 0, NULL, (void*) &appData.dualBoard, "",   NULL, CheckBox, N_("Dual Board for Background-Observed Game") },
555 { 0, 0, 0, NULL, (void*) &appData.getMoveList, "", NULL, CheckBox, N_("Get Move List") },
556 { 0, 0, 0, NULL, (void*) &appData.quietPlay, "",   NULL, CheckBox, N_("Quiet Play") },
557 { 0, 0, 0, NULL, (void*) &appData.seekGraph, "",   NULL, CheckBox, N_("Seek Graph") },
558 { 0, 0, 0, NULL, (void*) &appData.autoRefresh, "", NULL, CheckBox, N_("Auto-Refresh Seek Graph") },
559 { 0, 0, 0, NULL, (void*) &appData.premove, "",     NULL, CheckBox, N_("Premove") },
560 { 0, 0, 0, NULL, (void*) &appData.premoveWhite, "", NULL, CheckBox, N_("Premove for White") },
561 { 0, 0, 0, NULL, (void*) &appData.premoveWhiteText, "", NULL, TextBox, N_("First White Move:") },
562 { 0, 0, 0, NULL, (void*) &appData.premoveBlack, "", NULL, CheckBox, N_("Premove for Black") },
563 { 0, 0, 0, NULL, (void*) &appData.premoveBlackText, "", NULL, TextBox, N_("First Black Move:") },
564 { 0, SAME_ROW, 0, NULL, NULL, NULL, NULL, Break, "" },
565 { 0, 0, 0, NULL, (void*) &appData.icsAlarm, "", NULL, CheckBox, N_("Alarm") },
566 { 0, 0, 100000000, NULL, (void*) &appData.icsAlarmTime, "", NULL, Spin, N_("Alarm Time (msec):") },
567 //{ 0, 0, 0, NULL, (void*) &appData.chatBoxes, "", NULL, TextBox, N_("Startup Chat Boxes:") },
568 { 0, 0, 0, NULL, (void*) &appData.colorize, "", NULL, CheckBox, N_("Colorize Messages") },
569 { 0, 0, 0, NULL, (void*) &appData.colorShout, "", NULL, TextBox, N_("Shout Text Colors:") },
570 { 0, 0, 0, NULL, (void*) &appData.colorSShout, "", NULL, TextBox, N_("S-Shout Text Colors:") },
571 { 0, 0, 0, NULL, (void*) &appData.colorChannel1, "", NULL, TextBox, N_("Channel #1 Text Colors:") },
572 { 0, 0, 0, NULL, (void*) &appData.colorChannel, "", NULL, TextBox, N_("Other Channel Text Colors:") },
573 { 0, 0, 0, NULL, (void*) &appData.colorKibitz, "", NULL, TextBox, N_("Kibitz Text Colors:") },
574 { 0, 0, 0, NULL, (void*) &appData.colorTell, "", NULL, TextBox, N_("Tell Text Colors:") },
575 { 0, 0, 0, NULL, (void*) &appData.colorChallenge, "", NULL, TextBox, N_("Challenge Text Colors:") },
576 { 0, 0, 0, NULL, (void*) &appData.colorRequest, "", NULL, TextBox, N_("Request Text Colors:") },
577 { 0, 0, 0, NULL, (void*) &appData.colorSeek, "", NULL, TextBox, N_("Seek Text Colors:") },
578 { 0, 0, 0, NULL, (void*) &IcsOptionsOK, "", NULL, EndMark , "" }
579 };
580
581 void
582 IcsOptionsProc ()
583 {
584    GenericPopUp(icsOptions, _("ICS Options"), TransientDlg, BoardWindow, MODAL, 0);
585 }
586
587 //-------------------------------------------- Load Game Options ---------------------------------
588
589 static char *modeNames[] = { N_("Exact position match"), N_("Shown position is subset"), N_("Same material with exactly same Pawn chain"), 
590                       N_("Same material"), N_("Material range (top board half optional)"), N_("Material difference (optional stuff balanced)"), NULL };
591 static char *modeValues[] = { "1", "2", "3", "4", "5", "6" };
592 static char *searchMode;
593
594 static int
595 LoadOptionsOK ()
596 {
597     appData.searchMode = atoi(searchMode);
598     return 1;
599 }
600
601 static Option loadOptions[] = {
602 { 0,  0, 0,     NULL, (void*) &appData.autoDisplayTags, "", NULL, CheckBox, N_("Auto-Display Tags") },
603 { 0,  0, 0,     NULL, (void*) &appData.autoDisplayComment, "", NULL, CheckBox, N_("Auto-Display Comment") },
604 { 0, LR, 0,     NULL, NULL, NULL, NULL, Label, N_("Auto-Play speed of loaded games\n(0 = instant, -1 = off):") },
605 { 0, -1,10000000, NULL, (void*) &appData.timeDelay, "", NULL, Fractional, N_("Seconds per Move:") },
606 { 0, LR, 0,     NULL, NULL, NULL, NULL, Label,  N_("\noptions to use in game-viewer mode:") },
607 { 0, 0,300,     NULL, (void*) &appData.viewerOptions, "", NULL, TextBox,  "" },
608 { 0, LR,  0,    NULL, NULL, NULL, NULL, Label,  N_("\nThresholds for position filtering in game list:") },
609 { 0, 0,5000,    NULL, (void*) &appData.eloThreshold1, "", NULL, Spin, N_("Elo of strongest player at least:") },
610 { 0, 0,5000,    NULL, (void*) &appData.eloThreshold2, "", NULL, Spin, N_("Elo of weakest player at least:") },
611 { 0, 0,5000,    NULL, (void*) &appData.dateThreshold, "", NULL, Spin, N_("No games before year:") },
612 { 0, 1,50,      NULL, (void*) &appData.stretch, "", NULL, Spin, N_("Minimum nr consecutive positions:") },
613 { 0, 0,205,     NULL, (void*) &searchMode, (char*) modeValues, modeNames, ComboBox, N_("Search mode:") },
614 { 0, 0, 0,      NULL, (void*) &appData.ignoreColors, "", NULL, CheckBox, N_("Also match reversed colors") },
615 { 0, 0, 0,      NULL, (void*) &appData.findMirror, "", NULL, CheckBox, N_("Also match left-right flipped position") },
616 { 0,  0, 0,     NULL, (void*) &LoadOptionsOK, "", NULL, EndMark , "" }
617 };
618
619 void
620 LoadOptionsPopUp (DialogClass parent)
621 {
622    ASSIGN(searchMode, modeValues[appData.searchMode-1]);
623    GenericPopUp(loadOptions, _("Load Game Options"), TransientDlg, parent, MODAL, 0);
624 }
625
626 void
627 LoadOptionsProc ()
628 {   // called from menu
629     LoadOptionsPopUp(BoardWindow);
630 }
631
632 //------------------------------------------- Save Game Options --------------------------------------------
633
634 static Option saveOptions[] = {
635 { 0, 0, 0, NULL, (void*) &appData.autoSaveGames, "", NULL, CheckBox, N_("Auto-Save Games") },
636 { 0, 0, 0, NULL, (void*) &appData.saveGameFile, ".pgn", NULL, FileName,  N_("Save Games on File:") },
637 { 0, 0, 0, NULL, (void*) &appData.savePositionFile, ".fen", NULL, FileName,  N_("Save Final Positions on File:") },
638 { 0, 0, 0, NULL, (void*) &appData.pgnEventHeader, "", NULL, TextBox,  N_("PGN Event Header:") },
639 { 0, 0, 0, NULL, (void*) &appData.oldSaveStyle, "", NULL, CheckBox, N_("Old Save Style (as opposed to PGN)") },
640 { 0, 0, 0, NULL, (void*) &appData.numberTag, "", NULL, CheckBox, N_("Include Number Tag in tourney PGN") },
641 { 0, 0, 0, NULL, (void*) &appData.saveExtendedInfoInPGN, "", NULL, CheckBox, N_("Save Score/Depth Info in PGN") },
642 { 0, 0, 0, NULL, (void*) &appData.saveOutOfBookInfo, "", NULL, CheckBox, N_("Save Out-of-Book Info in PGN           ") },
643 { 0, SAME_ROW, 0, NULL, NULL, "", NULL, EndMark , "" }
644 };
645
646 void
647 SaveOptionsProc ()
648 {
649    GenericPopUp(saveOptions, _("Save Game Options"), TransientDlg, BoardWindow, MODAL, 0);
650 }
651
652 //----------------------------------------------- Sound Options ---------------------------------------------
653
654 static void Test P((int n));
655 static char *trialSound;
656
657 static char *soundNames[] = {
658         N_("No Sound"),
659         N_("Default Beep"),
660         N_("Above WAV File"),
661         N_("Car Horn"),
662         N_("Cymbal"),
663         N_("Ding"),
664         N_("Gong"),
665         N_("Laser"),
666         N_("Penalty"),
667         N_("Phone"),
668         N_("Pop"),
669         N_("Slap"),
670         N_("Wood Thunk"),
671         NULL,
672         N_("User File")
673 };
674
675 static char *soundFiles[] = { // sound files corresponding to above names
676         "",
677         "$",
678         NULL, // kludge alert: as first thing in the dialog readout this is replaced with the user-given .WAV filename
679         "honkhonk.wav",
680         "cymbal.wav",
681         "ding1.wav",
682         "gong.wav",
683         "laser.wav",
684         "penalty.wav",
685         "phone.wav",
686         "pop2.wav",
687         "slap.wav",
688         "woodthunk.wav",
689         NULL,
690         NULL
691 };
692
693 static Option soundOptions[] = {
694 { 0, 0, 0, NULL, (void*) &appData.soundProgram, "", NULL, TextBox, N_("Sound Program:") },
695 { 0, 0, 0, NULL, (void*) &appData.soundDirectory, "", NULL, PathName, N_("Sounds Directory:") },
696 { 0, 0, 0, NULL, (void*) (soundFiles+2) /* kludge! */, ".wav", NULL, FileName, N_("User WAV File:") },
697 { 0, 0, 0, NULL, (void*) &trialSound, (char*) soundFiles, soundNames, ComboBox, N_("Try-Out Sound:") },
698 { 0, SAME_ROW, 0, NULL, (void*) &Test, NULL, NULL, Button, N_("Play") },
699 { 0, 0, 0, NULL, (void*) &appData.soundMove, (char*) soundFiles, soundNames, ComboBox, N_("Move:") },
700 { 0, 0, 0, NULL, (void*) &appData.soundIcsWin, (char*) soundFiles, soundNames, ComboBox, N_("Win:") },
701 { 0, 0, 0, NULL, (void*) &appData.soundIcsLoss, (char*) soundFiles, soundNames, ComboBox, N_("Lose:") },
702 { 0, 0, 0, NULL, (void*) &appData.soundIcsDraw, (char*) soundFiles, soundNames, ComboBox, N_("Draw:") },
703 { 0, 0, 0, NULL, (void*) &appData.soundIcsUnfinished, (char*) soundFiles, soundNames, ComboBox, N_("Unfinished:") },
704 { 0, 0, 0, NULL, (void*) &appData.soundIcsAlarm, (char*) soundFiles, soundNames, ComboBox, N_("Alarm:") },
705 { 0, 0, 0, NULL, (void*) &appData.soundShout, (char*) soundFiles, soundNames, ComboBox, N_("Shout:") },
706 { 0, 0, 0, NULL, (void*) &appData.soundSShout, (char*) soundFiles, soundNames, ComboBox, N_("S-Shout:") },
707 { 0, 0, 0, NULL, (void*) &appData.soundChannel, (char*) soundFiles, soundNames, ComboBox, N_("Channel:") },
708 { 0, 0, 0, NULL, (void*) &appData.soundChannel1, (char*) soundFiles, soundNames, ComboBox, N_("Channel 1:") },
709 { 0, 0, 0, NULL, (void*) &appData.soundTell, (char*) soundFiles, soundNames, ComboBox, N_("Tell:") },
710 { 0, 0, 0, NULL, (void*) &appData.soundKibitz, (char*) soundFiles, soundNames, ComboBox, N_("Kibitz:") },
711 { 0, 0, 0, NULL, (void*) &appData.soundChallenge, (char*) soundFiles, soundNames, ComboBox, N_("Challenge:") },
712 { 0, 0, 0, NULL, (void*) &appData.soundRequest, (char*) soundFiles, soundNames, ComboBox, N_("Request:") },
713 { 0, 0, 0, NULL, (void*) &appData.soundSeek, (char*) soundFiles, soundNames, ComboBox, N_("Seek:") },
714 { 0, SAME_ROW, 0, NULL, NULL, "", NULL, EndMark , "" }
715 };
716
717 static void
718 Test (int n)
719 {
720     GenericReadout(soundOptions, 2);
721     if(soundFiles[values[3]]) PlaySound(soundFiles[values[3]]);
722 }
723
724 void
725 SoundOptionsProc ()
726 {
727    free(soundFiles[2]);
728    soundFiles[2] = strdup("*");
729    GenericPopUp(soundOptions, _("Sound Options"), TransientDlg, BoardWindow, MODAL, 0);
730 }
731
732 //--------------------------------------------- Board Options --------------------------------------
733
734 static void DefColor P((int n));
735 static void AdjustColor P((int i));
736
737 static int
738 BoardOptionsOK (int n)
739 {
740     if(appData.overrideLineGap >= 0) lineGap = appData.overrideLineGap; else lineGap = defaultLineGap;
741     useImages = useImageSqs = 0;
742     InitDrawingParams();
743     InitDrawingSizes(-1, 0);
744     DrawPosition(True, NULL);
745     return 1;
746 }
747
748 static Option boardOptions[] = {
749 { 0,          0, 70, NULL, (void*) &appData.whitePieceColor, "", NULL, TextBox, N_("White Piece Color:") },
750 { 1000, SAME_ROW, 0, NULL, (void*) &DefColor, NULL, (char**) "#FFFFCC", Button, "      " },
751 /* TRANSLATORS: R = single letter for the color red */
752 {    1, SAME_ROW, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, N_("R") },
753 /* TRANSLATORS: G = single letter for the color green */
754 {    2, SAME_ROW, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, N_("G") },
755 /* TRANSLATORS: B = single letter for the color blue */
756 {    3, SAME_ROW, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, N_("B") },
757 /* TRANSLATORS: D = single letter to make a color darker */
758 {    4, SAME_ROW, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, N_("D") },
759 { 0,          0, 70, NULL, (void*) &appData.blackPieceColor, "", NULL, TextBox, N_("Black Piece Color:") },
760 { 1000, SAME_ROW, 0, NULL, (void*) &DefColor, NULL, (char**) "#202020", Button, "      " },
761 {    1, SAME_ROW, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, N_("R") },
762 {    2, SAME_ROW, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, N_("G") },
763 {    3, SAME_ROW, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, N_("B") },
764 {    4, SAME_ROW, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, N_("D") },
765 { 0,          0, 70, NULL, (void*) &appData.lightSquareColor, "", NULL, TextBox, N_("Light Square Color:") },
766 { 1000, SAME_ROW, 0, NULL, (void*) &DefColor, NULL, (char**) "#C8C365", Button, "      " },
767 {    1, SAME_ROW, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, N_("R") },
768 {    2, SAME_ROW, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, N_("G") },
769 {    3, SAME_ROW, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, N_("B") },
770 {    4, SAME_ROW, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, N_("D") },
771 { 0,          0, 70, NULL, (void*) &appData.darkSquareColor, "", NULL, TextBox, N_("Dark Square Color:") },
772 { 1000, SAME_ROW, 0, NULL, (void*) &DefColor, NULL, (char**) "#77A26D", Button, "      " },
773 {    1, SAME_ROW, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, N_("R") },
774 {    2, SAME_ROW, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, N_("G") },
775 {    3, SAME_ROW, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, N_("B") },
776 {    4, SAME_ROW, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, N_("D") },
777 { 0,          0, 70, NULL, (void*) &appData.highlightSquareColor, "", NULL, TextBox, N_("Highlight Color:") },
778 { 1000, SAME_ROW, 0, NULL, (void*) &DefColor, NULL, (char**) "#FFFF00", Button, "      " },
779 {    1, SAME_ROW, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, N_("R") },
780 {    2, SAME_ROW, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, N_("G") },
781 {    3, SAME_ROW, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, N_("B") },
782 {    4, SAME_ROW, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, N_("D") },
783 { 0,          0, 70, NULL, (void*) &appData.premoveHighlightColor, "", NULL, TextBox, N_("Premove Highlight Color:") },
784 { 1000, SAME_ROW, 0, NULL, (void*) &DefColor, NULL, (char**) "#FF0000", Button, "      " },
785 {    1, SAME_ROW, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, N_("R") },
786 {    2, SAME_ROW, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, N_("G") },
787 {    3, SAME_ROW, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, N_("B") },
788 {    4, SAME_ROW, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, N_("D") },
789 { 0, 0, 0, NULL, (void*) &appData.upsideDown, "", NULL, CheckBox, N_("Flip Pieces Shogi Style        (Colored buttons restore default)") },
790 //{ 0, 0, 0, NULL, (void*) &appData.allWhite, "", NULL, CheckBox, N_("Use Outline Pieces for Black") },
791 { 0, 0, 0, NULL, (void*) &appData.monoMode, "", NULL, CheckBox, N_("Mono Mode") },
792 { 0,-1, 5, NULL, (void*) &appData.overrideLineGap, "", NULL, Spin, N_("Line Gap ( -1 = default for board size):") },
793 { 0, 0, 0, NULL, (void*) &appData.useBitmaps, "", NULL, CheckBox, N_("Use Board Textures") },
794 { 0, 0, 0, NULL, (void*) &appData.liteBackTextureFile, ".xpm", NULL, FileName, N_("Light-Squares Texture File:") },
795 { 0, 0, 0, NULL, (void*) &appData.darkBackTextureFile, ".xpm", NULL, FileName, N_("Dark-Squares Texture File:") },
796 { 0, 0, 0, NULL, (void*) &appData.bitmapDirectory, "", NULL, PathName, N_("Directory with Bitmap Pieces:") },
797 { 0, 0, 0, NULL, (void*) &appData.pixmapDirectory, "", NULL, PathName, N_("Directory with Pixmap Pieces:") },
798 { 0, 0, 0, NULL, (void*) &BoardOptionsOK, "", NULL, EndMark , "" }
799 };
800
801 static void
802 SetColorText (int n, char *buf)
803 {
804     SetWidgetText(&boardOptions[n-1], buf, TransientDlg);
805     SetColor(buf, &boardOptions[n]);
806 }
807
808 static void
809 DefColor (int n)
810 {
811     SetColorText(n, (char*) boardOptions[n].choice);
812 }
813
814 void
815 RefreshColor (int source, int n)
816 {
817     int col, j, r, g, b, step = 10;
818     char *s, buf[MSG_SIZ]; // color string
819     GetWidgetText(&boardOptions[source], &s);
820     if(sscanf(s, "#%x", &col) != 1) return;   // malformed
821     b = col & 0xFF; g = col & 0xFF00; r = col & 0xFF0000;
822     switch(n) {
823         case 1: r += 0x10000*step;break;
824         case 2: g += 0x100*step;  break;
825         case 3: b += step;        break;
826         case 4: r -= 0x10000*step; g -= 0x100*step; b -= step; break;
827     }
828     if(r < 0) r = 0; if(g < 0) g = 0; if(b < 0) b = 0;
829     if(r > 0xFF0000) r = 0xFF0000; if(g > 0xFF00) g = 0xFF00; if(b > 0xFF) b = 0xFF;
830     col = r | g | b;
831     snprintf(buf, MSG_SIZ, "#%06x", col);
832     for(j=1; j<7; j++) if(buf[j] >= 'a') buf[j] -= 32; // capitalize
833     SetColorText(source+1, buf);
834 }
835
836 static void
837 AdjustColor (int i)
838 {
839     int n = boardOptions[i].value;
840     RefreshColor(i-n-1, n);
841 }
842
843 void
844 BoardOptionsProc ()
845 {
846    GenericPopUp(boardOptions, _("Board Options"), TransientDlg, BoardWindow, MODAL, 0);
847 }
848
849 //-------------------------------------------- ICS Text Menu Options ------------------------------
850
851 Option textOptions[100];
852 static void PutText P((char *text, int pos));
853
854 void
855 SendString (char *p)
856 {
857     char buf[MSG_SIZ], *q;
858     if(q = strstr(p, "$input")) {
859         if(!shellUp[TextMenuDlg]) return;
860         strncpy(buf, p, MSG_SIZ);
861         strncpy(buf + (q-p), q+6, MSG_SIZ-(q-p));
862         PutText(buf, q-p);
863         return;
864     }
865     snprintf(buf, MSG_SIZ, "%s\n", p);
866     SendToICS(buf);
867 }
868
869 void
870 IcsTextProc ()
871 {
872    int i=0, j;
873    char *p, *q, *r;
874    if((p = icsTextMenuString) == NULL) return;
875    do {
876         q = r = p; while(*p && *p != ';') p++;
877         for(j=0; j<p-q; j++) textOptions[i].name[j] = *r++;
878         textOptions[i].name[j++] = 0;
879         if(!*p) break;
880         if(*++p == '\n') p++; // optional linefeed after button-text terminating semicolon
881         q = p;
882         textOptions[i].choice = (char**) (r = textOptions[i].name + j);
883         while(*p && (*p != ';' || p[1] != '\n')) textOptions[i].name[j++] = *p++;
884         textOptions[i].name[j++] = 0;
885         if(*p) p += 2;
886         textOptions[i].max = 135;
887         textOptions[i].min = i&1;
888         textOptions[i].handle = NULL;
889         textOptions[i].target = &SendText;
890         textOptions[i].textValue = strstr(r, "$input") ? "#80FF80" : strstr(r, "$name") ? "#FF8080" : "#FFFFFF";
891         textOptions[i].type = Button;
892    } while(++i < 99 && *p);
893    if(i == 0) return;
894    textOptions[i].type = EndMark;
895    textOptions[i].target = NULL;
896    textOptions[i].min = 2;
897    MarkMenu("View.ICStextmenu", TextMenuDlg);
898    GenericPopUp(textOptions, _("ICS text menu"), TextMenuDlg, BoardWindow, NONMODAL, 1);
899 }
900
901 //---------------------------------------------------- Edit Comment -----------------------------------
902
903 static char *commentText;
904 static int commentIndex;
905 static void ClearComment P((int n));
906 static void SaveChanges P((int n));
907
908 static int
909 NewComCallback (int n)
910 {
911     ReplaceComment(commentIndex, commentText);
912     return 1;
913 }
914
915 Option commentOptions[] = {
916 { 200, T_VSCRL | T_FILL | T_WRAP | T_TOP, 250, NULL, (void*) &commentText, "", NULL, TextBox, "" },
917 { 0,     0,     50, NULL, (void*) &ClearComment, NULL, NULL, Button, N_("clear") },
918 { 0, SAME_ROW, 100, NULL, (void*) &SaveChanges, NULL, NULL, Button, N_("save changes") },
919 { 0, SAME_ROW,  0,  NULL, (void*) &NewComCallback, "", NULL, EndMark , "" }
920 };
921
922 static void
923 SaveChanges (int n)
924 {
925     GenericReadout(commentOptions, 0);
926     ReplaceComment(commentIndex, commentText);
927 }
928
929 static void
930 ClearComment (int n)
931 {
932     SetWidgetText(&commentOptions[0], "", CommentDlg);
933 }
934
935 void
936 NewCommentPopup (char *title, char *text, int index)
937 {
938     if(DialogExists(CommentDlg)) { // if already exists, alter title and content
939         SetDialogTitle(CommentDlg, title);
940         SetWidgetText(&commentOptions[0], text, CommentDlg);
941     }
942     if(commentText) free(commentText); commentText = strdup(text);
943     commentIndex = index;
944     MarkMenu("View.Comments", CommentDlg);
945     if(GenericPopUp(commentOptions, title, CommentDlg, BoardWindow, NONMODAL, 1))
946         AddHandler(&commentOptions[0], 1);
947 }
948
949 void
950 EditCommentProc ()
951 {
952     int j;
953     if (PopDown(CommentDlg)) { // popdown succesful
954 //      MarkMenuItem("Edit.EditComment", False);
955 //      MarkMenuItem("View.Comments", False);
956     } else // was not up
957         EditCommentEvent();
958 }
959
960 //------------------------------------------------------ Edit Tags ----------------------------------
961
962 static void changeTags P((int n));
963 static char *tagsText;
964
965 static int
966 NewTagsCallback (int n)
967 {
968     ReplaceTags(tagsText, &gameInfo);
969     return 1;
970 }
971
972 static Option tagsOptions[] = {
973 {   0,   0,   0, NULL, NULL, NULL, NULL, Label,  NULL },
974 { 200, T_VSCRL | T_FILL | T_WRAP | T_TOP, 200, NULL, (void*) &tagsText, "", NULL, TextBox, "" },
975 {   0,   0, 100, NULL, (void*) &changeTags, NULL, NULL, Button, N_("save changes") },
976 { 0,SAME_ROW, 0, NULL, (void*) &NewTagsCallback, "", NULL, EndMark , "" }
977 };
978
979 static void
980 changeTags (int n)
981 {
982     GenericReadout(tagsOptions, 1);
983     if(bookUp) SaveToBook(tagsText); else
984     ReplaceTags(tagsText, &gameInfo);
985 }
986
987 void
988 NewTagsPopup (char *text, char *msg)
989 {
990     char *title = bookUp ? _("Edit book") : _("Tags");
991
992     if(DialogExists(TagsDlg)) { // if already exists, alter title and content
993         SetWidgetText(&tagsOptions[1], text, TagsDlg);
994         SetDialogTitle(TagsDlg, title);
995     }
996     if(tagsText) free(tagsText); tagsText = strdup(text);
997     tagsOptions[0].name = msg;
998     MarkMenu("View.Tags", TagsDlg);
999     GenericPopUp(tagsOptions, title, TagsDlg, BoardWindow, NONMODAL, 1);
1000 }
1001
1002 //---------------------------------------------- ICS Input Box ----------------------------------
1003
1004 char *icsText;
1005
1006 // [HGM] code borrowed from winboard.c (which should thus go to backend.c!)
1007 #define HISTORY_SIZE 64
1008 static char *history[HISTORY_SIZE];
1009 static int histIn = 0, histP = 0;
1010
1011 static void
1012 SaveInHistory (char *cmd)
1013 {
1014   if (history[histIn] != NULL) {
1015     free(history[histIn]);
1016     history[histIn] = NULL;
1017   }
1018   if (*cmd == NULLCHAR) return;
1019   history[histIn] = StrSave(cmd);
1020   histIn = (histIn + 1) % HISTORY_SIZE;
1021   if (history[histIn] != NULL) {
1022     free(history[histIn]);
1023     history[histIn] = NULL;
1024   }
1025   histP = histIn;
1026 }
1027
1028 static char *
1029 PrevInHistory (char *cmd)
1030 {
1031   int newhp;
1032   if (histP == histIn) {
1033     if (history[histIn] != NULL) free(history[histIn]);
1034     history[histIn] = StrSave(cmd);
1035   }
1036   newhp = (histP - 1 + HISTORY_SIZE) % HISTORY_SIZE;
1037   if (newhp == histIn || history[newhp] == NULL) return NULL;
1038   histP = newhp;
1039   return history[histP];
1040 }
1041
1042 static char *
1043 NextInHistory ()
1044 {
1045   if (histP == histIn) return NULL;
1046   histP = (histP + 1) % HISTORY_SIZE;
1047   return history[histP];   
1048 }
1049 // end of borrowed code
1050
1051 Option boxOptions[] = {
1052 {  30,  0,  400, NULL, (void*) &icsText, "", NULL, TextBox, "" },
1053 {  0,SAME_ROW | NO_OK, 0, NULL, NULL, "", NULL, EndMark , "" }
1054 };
1055
1056 void
1057 ICSInputSendText ()
1058 {
1059     char *val;
1060
1061     GetWidgetText(&boxOptions[0], &val);
1062     SaveInHistory(val);
1063     SendMultiLineToICS(val);
1064     SetWidgetText(&boxOptions[0], val, InputBoxDlg);
1065 }
1066
1067 void
1068 IcsKey (int n)
1069 {   // [HGM] input: let up-arrow recall previous line from history
1070     char *val;
1071
1072     if (!shellUp[InputBoxDlg]) return;
1073     switch(n) {
1074       case 0:
1075         ICSInputSendText();
1076         return;
1077       case 1:
1078         GetWidgetText(&boxOptions[0], &val);
1079         val = PrevInHistory(val);
1080         break;
1081       case -1:
1082         val = NextInHistory();
1083     }
1084     SetWidgetText(&boxOptions[0], val ? val : "", InputBoxDlg);
1085 }
1086
1087 static void
1088 PutText (char *text, int pos)
1089 {
1090     char buf[MSG_SIZ], *p;
1091
1092     if(strstr(text, "$add ") == text) {
1093         GetWidgetText(&boxOptions[0], &p);
1094         snprintf(buf, MSG_SIZ, "%s%s", p, text+5); text = buf;
1095         pos += strlen(p) - 5;
1096     }
1097     SetWidgetText(&boxOptions[0], text, TextMenuDlg);
1098     SetInsertPos(&boxOptions[0], pos);
1099 }
1100
1101 void
1102 ICSInputBoxPopUp ()
1103 {
1104     MarkMenu("View.ICSInputBox", InputBoxDlg);
1105     if(GenericPopUp(boxOptions, _("ICS input box"), InputBoxDlg, BoardWindow, NONMODAL, 0))
1106         AddHandler(&boxOptions[0], 3);
1107 }
1108
1109 void
1110 IcsInputBoxProc ()
1111 {
1112     if (!PopDown(InputBoxDlg)) ICSInputBoxPopUp();
1113 }
1114
1115 //--------------------------------------------- Move Type In ------------------------------------------
1116
1117 static int TypeInOK P((int n));
1118
1119 Option typeOptions[] = {
1120 { 30,  0,            400, NULL, (void*) &icsText, "", NULL, TextBox, "" },
1121 { 0, SAME_ROW | NO_OK, 0, NULL, (void*) &TypeInOK, "", NULL, EndMark , "" }
1122 };
1123
1124 static int
1125 TypeInOK (int n)
1126 {
1127     TypeInDoneEvent(icsText);
1128     return TRUE;
1129 }
1130
1131 void
1132 PopUpMoveDialog (char firstchar)
1133 {
1134     static char buf[2];
1135     buf[0] = firstchar; ASSIGN(icsText, buf);
1136     if(GenericPopUp(typeOptions, _("Type a move"), TransientDlg, BoardWindow, MODAL, 0))
1137         AddHandler(&typeOptions[0], 2);
1138 }
1139
1140 void
1141 BoxAutoPopUp (char *buf)
1142 {
1143         if(appData.icsActive) { // text typed to board in ICS mode: divert to ICS input box
1144             if(DialogExists(InputBoxDlg)) { // box already exists: append to current contents
1145                 char *p, newText[MSG_SIZ];
1146                 GetWidgetText(&boxOptions[0], &p);
1147                 snprintf(newText, MSG_SIZ, "%s%c", p, *buf);
1148                 SetWidgetText(&boxOptions[0], newText, InputBoxDlg);
1149                 if(shellUp[InputBoxDlg]) HardSetFocus (&boxOptions[0]); //why???
1150             } else icsText = buf; // box did not exist: make sure it pops up with char in it
1151             ICSInputBoxPopUp();
1152         } else PopUpMoveDialog(*buf);
1153 }
1154
1155 //------------------------------------------ Engine Settings ------------------------------------
1156
1157 void
1158 SettingsPopUp (ChessProgramState *cps)
1159 {
1160    currentCps = cps;
1161    GenericPopUp(cps->option, _("Engine Settings"), TransientDlg, BoardWindow, MODAL, 0);
1162 }
1163
1164 void
1165 FirstSettingsProc ()
1166 {
1167     SettingsPopUp(&first);
1168 }
1169
1170 void
1171 SecondSettingsProc ()
1172 {
1173    if(WaitForEngine(&second, SettingsMenuIfReady)) return;
1174    SettingsPopUp(&second);
1175 }
1176
1177 //----------------------------------------------- Load Engine --------------------------------------
1178
1179 char *engineDir, *engineLine, *nickName, *params;
1180 Boolean isUCI, hasBook, storeVariant, v1, addToList, useNick, secondEng;
1181
1182 static void EngSel P((int n, int sel));
1183 static int InstallOK P((int n));
1184
1185 static Option installOptions[] = {
1186 {   0,LR|T2T, 0, NULL, NULL, NULL, NULL, Label, N_("Select engine from list:") },
1187 { 300,LR|TB,200, NULL, (void*) engineMnemonic, (char*) &EngSel, NULL, ListBox, "" },
1188 { 0,SAME_ROW, 0, NULL, NULL, NULL, NULL, Break, NULL },
1189 {   0,  LR,   0, NULL, NULL, NULL, NULL, Label, N_("or specify one below:") },
1190 {   0,  0,    0, NULL, (void*) &nickName, NULL, NULL, TextBox, N_("Nickname (optional):") },
1191 {   0,  0,    0, NULL, (void*) &useNick, NULL, NULL, CheckBox, N_("Use nickname in PGN player tags of engine-engine games") },
1192 {   0,  0,    0, NULL, (void*) &engineDir, NULL, NULL, PathName, N_("Engine Directory:") },
1193 {   0,  0,    0, NULL, (void*) &engineName, NULL, NULL, FileName, N_("Engine Command:") },
1194 {   0,  LR,   0, NULL, NULL, NULL, NULL, Label, N_("(Directory will be derived from engine path when empty)") },
1195 {   0,  0,    0, NULL, (void*) &isUCI, NULL, NULL, CheckBox, N_("UCI") },
1196 {   0,  0,    0, NULL, (void*) &v1, NULL, NULL, CheckBox, N_("WB protocol v1 (do not wait for engine features)") },
1197 {   0,  0,    0, NULL, (void*) &hasBook, NULL, NULL, CheckBox, N_("Must not use GUI book") },
1198 {   0,  0,    0, NULL, (void*) &addToList, NULL, NULL, CheckBox, N_("Add this engine to the list") },
1199 {   0,  0,    0, NULL, (void*) &storeVariant, NULL, NULL, CheckBox, N_("Force current variant with this engine") },
1200 {   0,  0,    0, NULL, (void*) &InstallOK, "", NULL, EndMark , "" }
1201 };
1202
1203 static int
1204 InstallOK (int n)
1205 {
1206     if(n && (n = SelectedListBoxItem(&installOptions[1])) > 0) { // called by pressing OK, and engine selected
1207         ASSIGN(engineLine, engineList[n]);
1208     }
1209     PopDown(TransientDlg); // early popdown, to allow FreezeUI to instate grab
1210     if(!secondEng) Load(&first, 0); else Load(&second, 1);
1211     return FALSE; // no double PopDown!
1212 }
1213
1214 static void
1215 EngSel (int n, int sel)
1216 {
1217     if(sel < 1) return;
1218     ASSIGN(engineLine, engineList[sel]);
1219     InstallOK(0);
1220 }
1221
1222 static void
1223 LoadEngineProc (int engineNr, char *title)
1224 {
1225    isUCI = storeVariant = v1 = useNick = False; addToList = hasBook = True; // defaults
1226    secondEng = engineNr;
1227    if(engineLine)   free(engineLine);   engineLine = strdup("");
1228    if(engineDir)    free(engineDir);    engineDir = strdup("");
1229    if(nickName)     free(nickName);     nickName = strdup("");
1230    if(params)       free(params);       params = strdup("");
1231    NamesToList(firstChessProgramNames, engineList, engineMnemonic, "all");
1232    GenericPopUp(installOptions, title, TransientDlg, BoardWindow, MODAL, 0);
1233 }
1234
1235 void
1236 LoadEngine1Proc ()
1237 {
1238     LoadEngineProc (0, _("Load first engine"));
1239 }
1240
1241 void
1242 LoadEngine2Proc ()
1243 {
1244     LoadEngineProc (1, _("Load second engine"));
1245 }
1246
1247 //----------------------------------------------------- Edit Book -----------------------------------------
1248
1249 void
1250 EditBookProc ()
1251 {
1252     EditBookEvent();
1253 }
1254
1255 //--------------------------------------------------- New Shuffle Game ------------------------------
1256
1257 static void SetRandom P((int n));
1258
1259 static int
1260 ShuffleOK (int n)
1261 {
1262     ResetGameEvent();
1263     return 1;
1264 }
1265
1266 static Option shuffleOptions[] = {
1267   {   0,  0,   50, NULL, (void*) &shuffleOpenings, NULL, NULL, CheckBox, N_("shuffle") },
1268   { 0,-1,2000000000, NULL, (void*) &appData.defaultFrcPosition, "", NULL, Spin, N_("Start-position number:") },
1269   {   0,  0,    0, NULL, (void*) &SetRandom, NULL, NULL, Button, N_("randomize") },
1270   {   0,  SAME_ROW,    0, NULL, (void*) &SetRandom, NULL, NULL, Button, N_("pick fixed") },
1271   { 0,SAME_ROW, 0, NULL, (void*) &ShuffleOK, "", NULL, EndMark , "" }
1272 };
1273
1274 static void
1275 SetRandom (int n)
1276 {
1277     int r = n==2 ? -1 : random() & (1<<30)-1;
1278     char buf[MSG_SIZ];
1279     snprintf(buf, MSG_SIZ,  "%d", r);
1280     SetWidgetText(&shuffleOptions[1], buf, TransientDlg);
1281     SetWidgetState(&shuffleOptions[0], True);
1282 }
1283
1284 void
1285 ShuffleMenuProc ()
1286 {
1287     GenericPopUp(shuffleOptions, _("New Shuffle Game"), TransientDlg, BoardWindow, MODAL, 0);
1288 }
1289
1290 //------------------------------------------------------ Time Control -----------------------------------
1291
1292 static int TcOK P((int n));
1293 int tmpMoves, tmpTc, tmpInc, tmpOdds1, tmpOdds2, tcType;
1294
1295 static void
1296 ShowTC (int n)
1297 {
1298 }
1299
1300 static void SetTcType P((int n));
1301
1302 static char *
1303 Value (int n)
1304 {
1305         static char buf[MSG_SIZ];
1306         snprintf(buf, MSG_SIZ, "%d", n);
1307         return buf;
1308 }
1309
1310 static Option tcOptions[] = {
1311 {   0,  0,    0, NULL, (void*) &SetTcType, NULL, NULL, Button, N_("classical") },
1312 {   0,SAME_ROW,0,NULL, (void*) &SetTcType, NULL, NULL, Button, N_("incremental") },
1313 {   0,SAME_ROW,0,NULL, (void*) &SetTcType, NULL, NULL, Button, N_("fixed max") },
1314 {   0,  0,  200, NULL, (void*) &tmpMoves, NULL, NULL, Spin, N_("Moves per session:") },
1315 {   0,  0,10000, NULL, (void*) &tmpTc,    NULL, NULL, Spin, N_("Initial time (min):") },
1316 {   0, 0, 10000, NULL, (void*) &tmpInc,   NULL, NULL, Spin, N_("Increment or max (sec/move):") },
1317 {   0,  0,    0, NULL, NULL, NULL, NULL, Label, N_("Time-Odds factors:") },
1318 {   0,  1, 1000, NULL, (void*) &tmpOdds1, NULL, NULL, Spin, N_("Engine #1") },
1319 {   0,  1, 1000, NULL, (void*) &tmpOdds2, NULL, NULL, Spin, N_("Engine #2 / Human") },
1320 {   0,  0,    0, NULL, (void*) &TcOK, "", NULL, EndMark , "" }
1321 };
1322
1323 static int
1324 TcOK (int n)
1325 {
1326     char *tc;
1327     if(tcType == 0 && tmpMoves <= 0) return 0;
1328     if(tcType == 2 && tmpInc <= 0) return 0;
1329     GetWidgetText(&tcOptions[4], &tc); // get original text, in case it is min:sec
1330     searchTime = 0;
1331     switch(tcType) {
1332       case 0:
1333         if(!ParseTimeControl(tc, -1, tmpMoves)) return 0;
1334         appData.movesPerSession = tmpMoves;
1335         ASSIGN(appData.timeControl, tc);
1336         appData.timeIncrement = -1;
1337         break;
1338       case 1:
1339         if(!ParseTimeControl(tc, tmpInc, 0)) return 0;
1340         ASSIGN(appData.timeControl, tc);
1341         appData.timeIncrement = tmpInc;
1342         break;
1343       case 2:
1344         searchTime = tmpInc;
1345     }
1346     appData.firstTimeOdds = first.timeOdds = tmpOdds1;
1347     appData.secondTimeOdds = second.timeOdds = tmpOdds2;
1348     Reset(True, True);
1349     return 1;
1350 }
1351
1352 static void
1353 SetTcType (int n)
1354 {
1355     switch(tcType = n) {
1356       case 0:
1357         SetWidgetText(&tcOptions[3], Value(tmpMoves), TransientDlg);
1358         SetWidgetText(&tcOptions[4], Value(tmpTc), TransientDlg);
1359         SetWidgetText(&tcOptions[5], _("Unused"), TransientDlg);
1360         break;
1361       case 1:
1362         SetWidgetText(&tcOptions[3], _("Unused"), TransientDlg);
1363         SetWidgetText(&tcOptions[4], Value(tmpTc), TransientDlg);
1364         SetWidgetText(&tcOptions[5], Value(tmpInc), TransientDlg);
1365         break;
1366       case 2:
1367         SetWidgetText(&tcOptions[3], _("Unused"), TransientDlg);
1368         SetWidgetText(&tcOptions[4], _("Unused"), TransientDlg);
1369         SetWidgetText(&tcOptions[5], Value(tmpInc), TransientDlg);
1370     }
1371 }
1372
1373 void
1374 TimeControlProc ()
1375 {
1376    tmpMoves = appData.movesPerSession;
1377    tmpInc = appData.timeIncrement; if(tmpInc < 0) tmpInc = 0;
1378    tmpOdds1 = tmpOdds2 = 1; tcType = 0;
1379    tmpTc = atoi(appData.timeControl);
1380    GenericPopUp(tcOptions, _("Time Control"), TransientDlg, BoardWindow, MODAL, 0);
1381 }
1382
1383 //------------------------------- Ask Question -----------------------------------------
1384
1385 int SendReply P((int n));
1386 char pendingReplyPrefix[MSG_SIZ];
1387 ProcRef pendingReplyPR;
1388 char *answer;
1389
1390 Option askOptions[] = {
1391 { 0, 0, 0, NULL, NULL, NULL, NULL, Label,  NULL },
1392 { 0, 0, 0, NULL, (void*) &answer, "", NULL, TextBox, "" },
1393 { 0, 0, 0, NULL, (void*) &SendReply, "", NULL, EndMark , "" }
1394 };
1395
1396 int
1397 SendReply (int n)
1398 {
1399     char buf[MSG_SIZ];
1400     int err;
1401     char *reply=answer;
1402 //    GetWidgetText(&askOptions[1], &reply);
1403     safeStrCpy(buf, pendingReplyPrefix, sizeof(buf)/sizeof(buf[0]) );
1404     if (*buf) strncat(buf, " ", MSG_SIZ - strlen(buf) - 1);
1405     strncat(buf, reply, MSG_SIZ - strlen(buf) - 1);
1406     strncat(buf, "\n",  MSG_SIZ - strlen(buf) - 1);
1407     OutputToProcess(pendingReplyPR, buf, strlen(buf), &err); // does not go into debug file??? => bug
1408     if (err) DisplayFatalError(_("Error writing to chess program"), err, 0);
1409     return TRUE;
1410 }
1411
1412 void
1413 AskQuestion (char *title, char *question, char *replyPrefix, ProcRef pr)
1414 {
1415     safeStrCpy(pendingReplyPrefix, replyPrefix, sizeof(pendingReplyPrefix)/sizeof(pendingReplyPrefix[0]) );
1416     pendingReplyPR = pr;
1417     ASSIGN(answer, "");
1418     askOptions[0].name = question;
1419     if(GenericPopUp(askOptions, title, AskDlg, BoardWindow, MODAL, 0))
1420         AddHandler(&askOptions[1], 2);
1421 }
1422
1423 //---------------------------- Promotion Popup --------------------------------------
1424
1425 static int count;
1426
1427 static void PromoPick P((int n));
1428
1429 static Option promoOptions[] = {
1430 {   0,         0,    0, NULL, (void*) &PromoPick, NULL, NULL, Button, "" },
1431 {   0,  SAME_ROW,    0, NULL, (void*) &PromoPick, NULL, NULL, Button, "" },
1432 {   0,  SAME_ROW,    0, NULL, (void*) &PromoPick, NULL, NULL, Button, "" },
1433 {   0,  SAME_ROW,    0, NULL, (void*) &PromoPick, NULL, NULL, Button, "" },
1434 {   0,  SAME_ROW,    0, NULL, (void*) &PromoPick, NULL, NULL, Button, "" },
1435 {   0,  SAME_ROW,    0, NULL, (void*) &PromoPick, NULL, NULL, Button, "" },
1436 {   0,  SAME_ROW,    0, NULL, (void*) &PromoPick, NULL, NULL, Button, "" },
1437 {   0, SAME_ROW | NO_OK, 0, NULL, NULL, "", NULL, EndMark , "" }
1438 };
1439
1440 static void
1441 PromoPick (int n)
1442 {
1443     int promoChar = promoOptions[n+count].value;
1444
1445     PopDown(PromoDlg);
1446
1447     if (promoChar == 0) fromX = -1;
1448     if (fromX == -1) return;
1449
1450     if (! promoChar) {
1451         fromX = fromY = -1;
1452         ClearHighlights();
1453         return;
1454     }
1455     UserMoveEvent(fromX, fromY, toX, toY, promoChar);
1456
1457     if (!appData.highlightLastMove || gotPremove) ClearHighlights();
1458     if (gotPremove) SetPremoveHighlights(fromX, fromY, toX, toY);
1459     fromX = fromY = -1;
1460 }
1461
1462 static void
1463 SetPromo (char *name, int nr, char promoChar)
1464 {
1465     safeStrCpy(promoOptions[nr].name, name, MSG_SIZ);
1466     promoOptions[nr].value = promoChar;
1467 }
1468
1469 void
1470 PromotionPopUp ()
1471 { // choice depends on variant: prepare dialog acordingly
1472   count = 7;
1473   SetPromo(_("Cancel"), --count, 0); // Beware: GenericPopUp cannot handle user buttons named "cancel" (lowe case)!
1474   if(gameInfo.variant != VariantShogi) {
1475     if (!appData.testLegality || gameInfo.variant == VariantSuicide ||
1476         gameInfo.variant == VariantSpartan && !WhiteOnMove(currentMove) ||
1477         gameInfo.variant == VariantGiveaway) {
1478       SetPromo(_("King"), --count, 'k');
1479     }
1480     if(gameInfo.variant == VariantSpartan && !WhiteOnMove(currentMove)) {
1481       SetPromo(_("Captain"), --count, 'c');
1482       SetPromo(_("Lieutenant"), --count, 'l');
1483       SetPromo(_("General"), --count, 'g');
1484       SetPromo(_("Warlord"), --count, 'w');
1485     } else {
1486       SetPromo(_("Knight"), --count, 'n');
1487       SetPromo(_("Bishop"), --count, 'b');
1488       SetPromo(_("Rook"), --count, 'r');
1489       if(gameInfo.variant == VariantCapablanca ||
1490          gameInfo.variant == VariantGothic ||
1491          gameInfo.variant == VariantCapaRandom) {
1492         SetPromo(_("Archbishop"), --count, 'a');
1493         SetPromo(_("Chancellor"), --count, 'c');
1494       }
1495       SetPromo(_("Queen"), --count, 'q');
1496     }
1497   } else // [HGM] shogi
1498   {
1499       SetPromo(_("Defer"), --count, '=');
1500       SetPromo(_("Promote"), --count, '+');
1501   }
1502   GenericPopUp(promoOptions + count, "Promotion", PromoDlg, BoardWindow, NONMODAL, 0);
1503 }
1504
1505 //---------------------------- Chat Windows ----------------------------------------------
1506
1507 void
1508 OutputChatMessage (int partner, char *mess)
1509 {
1510     return; // dummy
1511 }
1512
1513 //--------------------------------- Game-List options dialog ------------------------------------------
1514
1515 char *strings[LPUSERGLT_SIZE];
1516 int stringPtr;
1517
1518 void
1519 GLT_ClearList ()
1520 {
1521     strings[0] = NULL;
1522     stringPtr = 0;
1523 }
1524
1525 void
1526 GLT_AddToList (char *name)
1527 {
1528     strings[stringPtr++] = name;
1529     strings[stringPtr] = NULL;
1530 }
1531
1532 Boolean
1533 GLT_GetFromList (int index, char *name)
1534 {
1535   safeStrCpy(name, strings[index], MSG_SIZ);
1536   return TRUE;
1537 }
1538
1539 void
1540 GLT_DeSelectList ()
1541 {
1542 }
1543
1544 static void GLT_Button P((int n));
1545 static int GLT_OK P((int n));
1546
1547 static Option listOptions[] = {
1548 { 0, LR|TB,  200, NULL, (void*) strings, "", NULL, ListBox, "" },
1549 { 0,    0,     0, NULL, (void*) &GLT_Button, NULL, NULL, Button, N_("factory") },
1550 { 0, SAME_ROW, 0, NULL, (void*) &GLT_Button, NULL, NULL, Button, N_("up") },
1551 { 0, SAME_ROW, 0, NULL, (void*) &GLT_Button, NULL, NULL, Button, N_("down") },
1552 { 0, SAME_ROW, 0, NULL, (void*) &GLT_OK, "", NULL, EndMark , "" }
1553 };
1554
1555 static int
1556 GLT_OK (int n)
1557 {
1558     GLT_ParseList();
1559     appData.gameListTags = strdup(lpUserGLT);
1560     return 1;
1561 }
1562
1563 static void
1564 GLT_Button (int n)
1565 {
1566     int index = SelectedListBoxItem (&listOptions[0]);
1567     char *p;
1568     if (index < 0) {
1569         DisplayError(_("No tag selected"), 0);
1570         return;
1571     }
1572     p = strings[index];
1573     if (n == 3) {
1574         if(index >= strlen(GLT_ALL_TAGS)) return;
1575         strings[index] = strings[index+1];
1576         strings[++index] = p;
1577     } else
1578     if (n == 2) {
1579         if(index == 0) return;
1580         strings[index] = strings[index-1];
1581         strings[--index] = p;
1582     } else
1583     if (n == 1) {
1584       safeStrCpy(lpUserGLT, GLT_DEFAULT_TAGS, LPUSERGLT_SIZE);
1585       GLT_TagsToList(lpUserGLT);
1586       index = 0;
1587       LoadListBox(&listOptions[0], "?"); // Note: the others don't need this, as the highlight switching redraws the change items
1588     }
1589     HighlightListBoxItem(&listOptions[0], index);
1590 }
1591
1592 void
1593 GameListOptionsPopUp (DialogClass parent)
1594 {
1595     safeStrCpy(lpUserGLT, appData.gameListTags, LPUSERGLT_SIZE);
1596     GLT_TagsToList(lpUserGLT);
1597
1598     GenericPopUp(listOptions, _("Game-list options"), TransientDlg, parent, MODAL, 0);
1599 }
1600
1601 void
1602 GameListOptionsProc ()
1603 {
1604     GameListOptionsPopUp(BoardWindow);
1605 }
1606
1607 //----------------------------- Error popup in various uses -----------------------------
1608
1609 /*
1610  * [HGM] Note:
1611  * XBoard has always had some pathologic behavior with multiple simultaneous error popups,
1612  * (which can occur even for modal popups when asynchrounous events, e.g. caused by engine, request a popup),
1613  * and this new implementation reproduces that as well:
1614  * Only the shell of the last instance is remembered in shells[ErrorDlg] (which replaces errorShell),
1615  * so that PopDowns ordered from the code always refer to that instance, and once that is down,
1616  * have no clue as to how to reach the others. For the Delete Window button calling PopDown this
1617  * has now been repaired, as the action routine assigned to it gets the shell passed as argument.
1618  */
1619
1620 int errorUp = False;
1621
1622 void
1623 ErrorPopDown ()
1624 {
1625     if (!errorUp) return;
1626     dialogError = errorUp = False;
1627     PopDown(ErrorDlg); PopDown(FatalDlg); // on explicit request we pop down any error dialog
1628     if (errorExitStatus != -1) ExitEvent(errorExitStatus);
1629 }
1630
1631 static int
1632 ErrorOK (int n)
1633 {
1634     dialogError = errorUp = False;
1635     PopDown(n == 1 ? FatalDlg : ErrorDlg); // kludge: non-modal dialogs have one less (dummy) option
1636     if (errorExitStatus != -1) ExitEvent(errorExitStatus);
1637     return FALSE; // prevent second Popdown !
1638 }
1639
1640 static Option errorOptions[] = {
1641 {   0,  0,    0, NULL, NULL, NULL, NULL, Label,  NULL }, // dummy option: will never be displayed
1642 {   0,  0,    0, NULL, NULL, NULL, NULL, Label,  NULL }, // textValue field will be set before popup
1643 { 0,NO_CANCEL,0, NULL, (void*) &ErrorOK, "", NULL, EndMark , "" }
1644 };
1645
1646 void
1647 ErrorPopUp (char *title, char *label, int modal)
1648 {
1649     errorUp = True;
1650     errorOptions[1].name = label;
1651     if(dialogError = shellUp[TransientDlg]) 
1652         GenericPopUp(errorOptions+1, title, FatalDlg, TransientDlg, MODAL, 0); // pop up as daughter of the transient dialog
1653     else
1654         GenericPopUp(errorOptions+modal, title, modal ? FatalDlg: ErrorDlg, BoardWindow, modal, 0); // kludge: option start address indicates modality
1655 }
1656
1657 void
1658 DisplayError (String message, int error)
1659 {
1660     char buf[MSG_SIZ];
1661
1662     if (error == 0) {
1663         if (appData.debugMode || appData.matchMode) {
1664             fprintf(stderr, "%s: %s\n", programName, message);
1665         }
1666     } else {
1667         if (appData.debugMode || appData.matchMode) {
1668             fprintf(stderr, "%s: %s: %s\n",
1669                     programName, message, strerror(error));
1670         }
1671         snprintf(buf, sizeof(buf), "%s: %s", message, strerror(error));
1672         message = buf;
1673     }
1674     ErrorPopUp(_("Error"), message, FALSE);
1675 }
1676
1677
1678 void
1679 DisplayMoveError (String message)
1680 {
1681     fromX = fromY = -1;
1682     ClearHighlights();
1683     DrawPosition(FALSE, NULL);
1684     if (appData.debugMode || appData.matchMode) {
1685         fprintf(stderr, "%s: %s\n", programName, message);
1686     }
1687     if (appData.popupMoveErrors) {
1688         ErrorPopUp(_("Error"), message, FALSE);
1689     } else {
1690         DisplayMessage(message, "");
1691     }
1692 }
1693
1694
1695 void
1696 DisplayFatalError (String message, int error, int status)
1697 {
1698     char buf[MSG_SIZ];
1699
1700     errorExitStatus = status;
1701     if (error == 0) {
1702         fprintf(stderr, "%s: %s\n", programName, message);
1703     } else {
1704         fprintf(stderr, "%s: %s: %s\n",
1705                 programName, message, strerror(error));
1706         snprintf(buf, sizeof(buf), "%s: %s", message, strerror(error));
1707         message = buf;
1708     }
1709     if (appData.popupExitMessage && boardWidget && XtIsRealized(boardWidget)) {
1710       ErrorPopUp(status ? _("Fatal Error") : _("Exiting"), message, TRUE);
1711     } else {
1712       ExitEvent(status);
1713     }
1714 }
1715
1716 void
1717 DisplayInformation (String message)
1718 {
1719     ErrorPopDown();
1720     ErrorPopUp(_("Information"), message, TRUE);
1721 }
1722
1723 void
1724 DisplayNote (String message)
1725 {
1726     ErrorPopDown();
1727     ErrorPopUp(_("Note"), message, FALSE);
1728 }
1729
1730 void
1731 DisplayTitle (char *text)
1732 {
1733     char title[MSG_SIZ];
1734     char icon[MSG_SIZ];
1735
1736     if (text == NULL) text = "";
1737
1738     if (*text != NULLCHAR) {
1739       safeStrCpy(icon, text, sizeof(icon)/sizeof(icon[0]) );
1740       safeStrCpy(title, text, sizeof(title)/sizeof(title[0]) );
1741     } else if (appData.icsActive) {
1742         snprintf(icon, sizeof(icon), "%s", appData.icsHost);
1743         snprintf(title, sizeof(title), "%s: %s", programName, appData.icsHost);
1744     } else if (appData.cmailGameName[0] != NULLCHAR) {
1745         snprintf(icon, sizeof(icon), "%s", "CMail");
1746         snprintf(title,sizeof(title), "%s: %s", programName, "CMail");
1747 #ifdef GOTHIC
1748     // [HGM] license: This stuff should really be done in back-end, but WinBoard already had a pop-up for it
1749     } else if (gameInfo.variant == VariantGothic) {
1750       safeStrCpy(icon,  programName, sizeof(icon)/sizeof(icon[0]) );
1751       safeStrCpy(title, GOTHIC,     sizeof(title)/sizeof(title[0]) );
1752 #endif
1753 #ifdef FALCON
1754     } else if (gameInfo.variant == VariantFalcon) {
1755       safeStrCpy(icon, programName, sizeof(icon)/sizeof(icon[0]) );
1756       safeStrCpy(title, FALCON, sizeof(title)/sizeof(title[0]) );
1757 #endif
1758     } else if (appData.noChessProgram) {
1759       safeStrCpy(icon, programName, sizeof(icon)/sizeof(icon[0]) );
1760       safeStrCpy(title, programName, sizeof(title)/sizeof(title[0]) );
1761     } else {
1762       safeStrCpy(icon, first.tidy, sizeof(icon)/sizeof(icon[0]) );
1763         snprintf(title,sizeof(title), "%s: %s", programName, first.tidy);
1764     }
1765     SetWindowTitle(text, title, icon);
1766 }
1767
1768 void
1769 DisplayWhiteClock (long timeRemaining, int highlight)
1770 {
1771     if(appData.noGUI) return;
1772     DisplayTimerLabel(11, _("White"), timeRemaining, highlight);
1773     if(highlight) SetClockIcon(0);
1774 }
1775
1776 void
1777 DisplayBlackClock (long timeRemaining, int highlight)
1778 {
1779     if(appData.noGUI) return;
1780     DisplayTimerLabel(12, _("Black"), timeRemaining, highlight);
1781     if(highlight) SetClockIcon(1);
1782 }
1783
1784 #define PAUSE_BUTTON "P"
1785 #define PIECE_MENU_SIZE 18
1786 static String pieceMenuStrings[2][PIECE_MENU_SIZE+1] = {
1787     { N_("White"), "----", N_("Pawn"), N_("Knight"), N_("Bishop"), N_("Rook"),
1788       N_("Queen"), N_("King"), "----", N_("Elephant"), N_("Cannon"),
1789       N_("Archbishop"), N_("Chancellor"), "----", N_("Promote"), N_("Demote"),
1790       N_("Empty square"), N_("Clear board"), NULL },
1791     { N_("Black"), "----", N_("Pawn"), N_("Knight"), N_("Bishop"), N_("Rook"),
1792       N_("Queen"), N_("King"), "----", N_("Elephant"), N_("Cannon"),
1793       N_("Archbishop"), N_("Chancellor"), "----", N_("Promote"), N_("Demote"),
1794       N_("Empty square"), N_("Clear board"), NULL }
1795 };
1796 /* must be in same order as pieceMenuStrings! */
1797 static ChessSquare pieceMenuTranslation[2][PIECE_MENU_SIZE] = {
1798     { WhitePlay, (ChessSquare) 0, WhitePawn, WhiteKnight, WhiteBishop,
1799         WhiteRook, WhiteQueen, WhiteKing, (ChessSquare) 0, WhiteAlfil,
1800         WhiteCannon, WhiteAngel, WhiteMarshall, (ChessSquare) 0,
1801         PromotePiece, DemotePiece, EmptySquare, ClearBoard },
1802     { BlackPlay, (ChessSquare) 0, BlackPawn, BlackKnight, BlackBishop,
1803         BlackRook, BlackQueen, BlackKing, (ChessSquare) 0, BlackAlfil,
1804         BlackCannon, BlackAngel, BlackMarshall, (ChessSquare) 0,
1805         PromotePiece, DemotePiece, EmptySquare, ClearBoard },
1806 };
1807
1808 #define DROP_MENU_SIZE 6
1809 static String dropMenuStrings[DROP_MENU_SIZE+1] = {
1810     "----", N_("Pawn"), N_("Knight"), N_("Bishop"), N_("Rook"), N_("Queen"), NULL
1811   };
1812 /* must be in same order as dropMenuStrings! */
1813 static ChessSquare dropMenuTranslation[DROP_MENU_SIZE] = {
1814     (ChessSquare) 0, WhitePawn, WhiteKnight, WhiteBishop,
1815     WhiteRook, WhiteQueen
1816 };
1817
1818 // [HGM] experimental code to pop up window just like the main window, using GenercicPopUp
1819
1820 static Option *Exp P((int n, int x, int y));
1821 void MenuCallback P((int n));
1822 void SizeKludge P((int n));
1823
1824 static int pmFromX = -1, pmFromY = -1;
1825
1826 static void
1827 PMSelect (int n)
1828 {   // user callback for board context menus
1829     if (pmFromX < 0 || pmFromY < 0) return;
1830     if(n == 25) DropMenuEvent(dropMenuTranslation[values[n]], pmFromX, pmFromY);
1831     else EditPositionMenuEvent(pieceMenuTranslation[n-23][values[n]], pmFromX, pmFromY);
1832 }
1833
1834 int
1835 CCB (int n)
1836 {
1837     shiftKey = (ShiftKeys() & 3) != 0;
1838     ClockClick(n == 12);
1839 }
1840
1841 Option mainOptions[] = { // description of main window in terms of generic dialog creator
1842 { 0, 0xCA, 0, NULL, NULL, "", NULL, BoxBegin, "" }, // menu bar
1843   { 0, COMBO_CALLBACK, 0, NULL, (void*)&MenuCallback, NULL, NULL, DropDown, N_("File") },
1844   { 0, COMBO_CALLBACK, 0, NULL, (void*)&MenuCallback, NULL, NULL, DropDown, N_("Edit") },
1845   { 0, COMBO_CALLBACK, 0, NULL, (void*)&MenuCallback, NULL, NULL, DropDown, N_("View") },
1846   { 0, COMBO_CALLBACK, 0, NULL, (void*)&MenuCallback, NULL, NULL, DropDown, N_("Mode") },
1847   { 0, COMBO_CALLBACK, 0, NULL, (void*)&MenuCallback, NULL, NULL, DropDown, N_("Action") },
1848   { 0, COMBO_CALLBACK, 0, NULL, (void*)&MenuCallback, NULL, NULL, DropDown, N_("Engine") },
1849   { 0, COMBO_CALLBACK, 0, NULL, (void*)&MenuCallback, NULL, NULL, DropDown, N_("Options") },
1850   { 0, COMBO_CALLBACK, 0, NULL, (void*)&MenuCallback, NULL, NULL, DropDown, N_("Help") },
1851 { 0, 0, 0, NULL, (void*)&SizeKludge, "", NULL, BoxEnd, "" },
1852 { 0, LR|T2T|BORDER|SAME_ROW, 0, NULL, NULL, "", NULL, Label, "1" }, // optional title in window
1853 { 0, L2L|T2T,              200, NULL, (void*) &CCB, NULL, NULL, Label, "White" }, // white clock
1854 { 0, R2R|T2T|SAME_ROW,     200, NULL, (void*) &CCB, NULL, NULL, Label, "Black" }, // black clock
1855 { 0, LR|T2T|BORDER,        401, NULL, NULL, "", NULL, -1, "2" }, // backup for title in window (if no room for other)
1856 { 0, LR|T2T|BORDER,        270, NULL, NULL, "", NULL, Label, "message" }, // message field
1857 { 0, RR|TT|SAME_ROW,       125, NULL, NULL, "", NULL, BoxBegin, "" }, // (optional) button bar
1858   { 0,    0,     0, NULL, (void*) &ToStartEvent, NULL, NULL, Button, N_("<<") },
1859   { 0, SAME_ROW, 0, NULL, (void*) &BackwardEvent, NULL, NULL, Button, N_("<") },
1860   { 0, SAME_ROW, 0, NULL, (void*) &PauseEvent, NULL, NULL, Button, N_(PAUSE_BUTTON) },
1861   { 0, SAME_ROW, 0, NULL, (void*) &ForwardEvent, NULL, NULL, Button, N_(">") },
1862   { 0, SAME_ROW, 0, NULL, (void*) &ToEndEvent, NULL, NULL, Button, N_(">>") },
1863 { 0, 0, 0, NULL, NULL, "", NULL, BoxEnd, "" },
1864 { 401, LR|TT, 401, NULL, (char*) &Exp, NULL, NULL, Graph, "shadow board" }, // board
1865   { 2, COMBO_CALLBACK, 0, NULL, (void*) &PMSelect, NULL, pieceMenuStrings[0], PopUp, "menuW" },
1866   { 2, COMBO_CALLBACK, 0, NULL, (void*) &PMSelect, NULL, pieceMenuStrings[1], PopUp, "menuB" },
1867   { -1, COMBO_CALLBACK, 0, NULL, (void*) &PMSelect, NULL, dropMenuStrings, PopUp, "menuD" },
1868 { 0,  NO_OK, 0, NULL, NULL, "", NULL, EndMark , "" }
1869 };
1870
1871 void
1872 SizeKludge (int n)
1873 {   // callback called by GenericPopUp immediately after sizing the menu bar
1874     int width = BOARD_WIDTH*(squareSize + lineGap) + lineGap;
1875     int w = width - 44 - mainOptions[n].min;
1876     mainOptions[10].max = w; // width left behind menu bar
1877     if(w < 0.4*width) // if no reasonable amount of space for title, force small layout
1878         mainOptions[13].type = mainOptions[10].type, mainOptions[10].type = -1; 
1879 }
1880
1881 void
1882 MenuCallback (int n)
1883 {
1884     MenuProc *proc = (MenuProc *) (((MenuItem*)(mainOptions[n].choice))[values[n]].proc);
1885
1886     (proc)();
1887 }
1888
1889 static Option *
1890 Exp (int n, int x, int y)
1891 {
1892     static int but1, but3;
1893     int menuNr = -3;
1894
1895     if(n == 0) { // motion
1896         if(SeekGraphClick(Press, x, y, 1)) return NULL;
1897         if(but1 && !PromoScroll(x, y)) DragPieceMove(x, y);
1898         if(but3) MovePV(x, y, lineGap + BOARD_HEIGHT * (squareSize + lineGap));
1899         return NULL;
1900     }
1901     shiftKey = (ShiftKeys() & 3) != 0;
1902     switch(n) {
1903         case  1: LeftClick(Press,   x, y), but1 = 1; break;
1904         case -1: LeftClick(Release, x, y), but1 = 0; break;
1905         case  2: shiftKey = !shiftKey;
1906         case  3: menuNr = RightClick(Press,   x, y, &pmFromX, &pmFromY), but3 = 1; break;
1907         case -2: shiftKey = !shiftKey;
1908         case -3: menuNr = RightClick(Release, x, y, &pmFromX, &pmFromY), but3 = 0; break;
1909         case 10:
1910             DrawPosition(True, NULL);
1911             if(twoBoards) { // [HGM] dual: draw other board in other orientation
1912                 flipView = !flipView; partnerUp = !partnerUp;
1913                 DrawPosition(True, NULL);
1914                 flipView = !flipView; partnerUp = !partnerUp;
1915             }
1916         default:
1917             return NULL;
1918     }
1919
1920     switch(menuNr) {
1921       case 0: return &mainOptions[shiftKey ? 23: 24];
1922       case 1: SetupDropMenu(); return &mainOptions[25];
1923       case 2:
1924       case -1: ErrorPopDown();
1925       case -2:
1926       default: break; // -3, so no clicks caught
1927     }
1928     return NULL;
1929 }
1930
1931 Option *
1932 BoardPopUp (int squareSize, int lineGap, void *clockFontThingy)
1933 {
1934     extern Option *dialogOptions[];
1935     int i, size = BOARD_WIDTH*(squareSize + lineGap) + lineGap;
1936     mainOptions[11].choice = (char**) clockFontThingy;
1937     mainOptions[12].choice = (char**) clockFontThingy;
1938     mainOptions[22].value = BOARD_HEIGHT*(squareSize + lineGap) + lineGap;
1939     mainOptions[22].max = mainOptions[13].max = size; // board size
1940     mainOptions[13].max = size - 2; // board title (subtract border!)
1941     mainOptions[12].max = mainOptions[11].max = size/2-3; // clock width
1942     mainOptions[14].max = appData.showButtonBar ? size-130 : size-2; // message
1943     mainOptions[0].max = size-40; // menu bar
1944     mainOptions[10].type = appData.titleInWindow ? Label : -1 ;
1945     if(!appData.showButtonBar) for(i=15; i<22; i++) mainOptions[i].type = -1;
1946     for(i=0; i<8; i++) mainOptions[i+1].choice = (char**) menuBar[i].mi;
1947     GenericPopUp(mainOptions, "XBoard", BoardWindow, BoardWindow, NONMODAL, 1);
1948     return mainOptions;
1949 }
1950
1951 void
1952 DisplayMessage (char *message, char *extMessage)
1953 {
1954   /* display a message in the message widget */
1955
1956   char buf[MSG_SIZ];
1957
1958   if (extMessage)
1959     {
1960       if (*message)
1961         {
1962           snprintf(buf, sizeof(buf), "%s  %s", message, extMessage);
1963           message = buf;
1964         }
1965       else
1966         {
1967           message = extMessage;
1968         };
1969     };
1970
1971     safeStrCpy(lastMsg, message, MSG_SIZ); // [HGM] make available
1972
1973   /* need to test if messageWidget already exists, since this function
1974      can also be called during the startup, if for example a Xresource
1975      is not set up correctly */
1976   if(mainOptions[14].handle)
1977     SetWidgetLabel(&mainOptions[14], message);
1978
1979   return;
1980 }
1981
1982