Redo Game List with generic popup
[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    (for concurrent playing of a single") },
258 { 0,  0,          0, NULL, (void*) &appData.cycleSync, "", NULL, CheckBox, N_("Sync after cycle      tourney with multiple XBoards)") },
259 { 150, T_VSCRL | T_FILL | T_WRAP,
260                   0, NULL, (void*) &engineName, "", NULL, TextBox, N_("Tourney participants:") },
261 { 0,  COMBO_CALLBACK | NO_GETTEXT,
262                   0, NULL, (void*) &AddToTourney, (char*) (engineMnemonic+1), (engineMnemonic+1), ComboBox, N_("Select Engine:") },
263 { 0,  0,         10, NULL, (void*) &appData.tourneyType, "", NULL, Spin, N_("Tourney type (0 = round-robin, 1 = gauntlet):") },
264 { 0,  1, 1000000000, NULL, (void*) &appData.tourneyCycles, "", NULL, Spin, N_("Number of tourney cycles (or Swiss rounds):") },
265 { 0,  1, 1000000000, NULL, (void*) &appData.defaultMatchGames, "", NULL, Spin, N_("Default Number of Games in Match (or Pairing):") },
266 { 0,  0, 1000000000, NULL, (void*) &appData.matchPause, "", NULL, Spin, N_("Pause between Match Games (msec):") },
267 { 0,  0,          0, NULL, (void*) &appData.saveGameFile, ".pgn", NULL, FileName, N_("Save Tourney Games on:") },
268 { 0,  0,          0, NULL, (void*) &appData.loadGameFile, ".pgn", NULL, FileName, N_("Game File with Opening Lines:") },
269 { 0, -2, 1000000000, NULL, (void*) &appData.loadGameIndex, "", NULL, Spin, N_("Game Number (-1 or -2 = Auto-Increment):") },
270 { 0,  0,          0, NULL, (void*) &appData.loadPositionFile, ".fen", NULL, FileName, N_("File with Start Positions:") },
271 { 0, -2, 1000000000, NULL, (void*) &appData.loadPositionIndex, "", NULL, Spin, N_("Position Number (-1 or -2 = Auto-Increment):") },
272 { 0,  0, 1000000000, NULL, (void*) &appData.rewindIndex, "", NULL, Spin, N_("Rewind Index after this many Games (0 = never):") },
273 { 0,  0,          0, NULL, (void*) &appData.defNoBook, "", NULL, CheckBox, N_("Disable own engine books by default") },
274 { 0,  0,          0, NULL, (void*) &ReplaceParticipant, NULL, NULL, Button, N_("Replace Engine") },
275 { 0, SAME_ROW,    0, NULL, (void*) &UpgradeParticipant, NULL, NULL, Button, N_("Upgrade Engine") },
276 { 0, SAME_ROW,    0, NULL, (void*) &CloneTourney, NULL, NULL, Button, N_("Clone Tourney") },
277 { 0, SAME_ROW,    0, NULL, (void*) &MatchOK, "", NULL, EndMark , "" }
278 };
279
280 static void
281 ReplaceParticipant ()
282 {
283     GenericReadout(matchOptions, 3);
284     Substitute(strdup(engineName), True);
285 }
286
287 static void
288 UpgradeParticipant ()
289 {
290     GenericReadout(matchOptions, 3);
291     Substitute(strdup(engineName), False);
292 }
293
294 static void
295 CloneTourney ()
296 {
297     FILE *f;
298     char *name;
299     GetWidgetText(matchOptions, &name);
300     if(name && name[0] && (f = fopen(name, "r")) ) {
301         char *saveSaveFile;
302         saveSaveFile = appData.saveGameFile; appData.saveGameFile = NULL; // this is a persistent option, protect from change
303         ParseArgsFromFile(f);
304         engineName = appData.participants; GenericUpdate(matchOptions, -1);
305         FREE(appData.saveGameFile); appData.saveGameFile = saveSaveFile;
306     } else DisplayError(_("First you must specify an existing tourney file to clone"), 0);
307 }
308
309 static void
310 AddToTourney (int n)
311 {
312     AddLine(&matchOptions[3], engineMnemonic[values[4]+1]);
313 }
314
315 void
316 MatchOptionsProc ()
317 {
318    NamesToList(firstChessProgramNames, engineList, engineMnemonic, "all");
319    matchOptions[5].min = -(appData.pairingEngine[0] != NULLCHAR); // with pairing engine, allow Swiss
320    ASSIGN(tfName, appData.tourneyFile[0] ? appData.tourneyFile : MakeName(appData.defName));
321    ASSIGN(engineName, appData.participants);
322    GenericPopUp(matchOptions, _("Match Options"), TransientDlg, BoardWindow, MODAL, 0);
323 }
324
325 // ------------------------------------------- General Options --------------------------------------------------
326
327 static int oldShow, oldBlind, oldPonder;
328
329 static int
330 GeneralOptionsOK (int n)
331 {
332         int newPonder = appData.ponderNextMove;
333         appData.ponderNextMove = oldPonder;
334         PonderNextMoveEvent(newPonder);
335         if(!appData.highlightLastMove) ClearHighlights(), ClearPremoveHighlights();
336         if(oldShow != appData.showCoords || oldBlind != appData.blindfold) DrawPosition(TRUE, NULL);
337         return 1;
338 }
339
340 static Option generalOptions[] = {
341 { 0,  0, 0, NULL, (void*) &appData.whitePOV, "", NULL, CheckBox, N_("Absolute Analysis Scores") },
342 { 0,  0, 0, NULL, (void*) &appData.sweepSelect, "", NULL, CheckBox, N_("Almost Always Queen (Detour Under-Promote)") },
343 { 0,  0, 0, NULL, (void*) &appData.animateDragging, "", NULL, CheckBox, N_("Animate Dragging") },
344 { 0,  0, 0, NULL, (void*) &appData.animate, "", NULL, CheckBox, N_("Animate Moving") },
345 { 0,  0, 0, NULL, (void*) &appData.autoCallFlag, "", NULL, CheckBox, N_("Auto Flag") },
346 { 0,  0, 0, NULL, (void*) &appData.autoFlipView, "", NULL, CheckBox, N_("Auto Flip View") },
347 { 0,  0, 0, NULL, (void*) &appData.blindfold, "", NULL, CheckBox, N_("Blindfold") },
348 { 0,  0, 0, NULL, (void*) &appData.dropMenu, "", NULL, CheckBox, N_("Drop Menu") },
349 { 0,  0, 0, NULL, (void*) &appData.hideThinkingFromHuman, "", NULL, CheckBox, N_("Hide Thinking from Human") },
350 { 0,  0, 0, NULL, (void*) &appData.highlightLastMove, "", NULL, CheckBox, N_("Highlight Last Move") },
351 { 0,  0, 0, NULL, (void*) &appData.highlightMoveWithArrow, "", NULL, CheckBox, N_("Highlight with Arrow") },
352 { 0,  0, 0, NULL, (void*) &appData.ringBellAfterMoves, "", NULL, CheckBox, N_("Move Sound") },
353 { 0,  0, 0, NULL, (void*) &appData.oneClick, "", NULL, CheckBox, N_("One-Click Moving") },
354 { 0,  0, 0, NULL, (void*) &appData.periodicUpdates, "", NULL, CheckBox, N_("Periodic Updates (in Analysis Mode)") },
355 { 0,  0, 0, NULL, (void*) &appData.ponderNextMove, "", NULL, CheckBox, N_("Ponder Next Move") },
356 { 0,  0, 0, NULL, (void*) &appData.popupExitMessage, "", NULL, CheckBox, N_("Popup Exit Messages") },
357 { 0,  0, 0, NULL, (void*) &appData.popupMoveErrors, "", NULL, CheckBox, N_("Popup Move Errors") },
358 { 0,  0, 0, NULL, (void*) &appData.showEvalInMoveHistory, "", NULL, CheckBox, N_("Scores in Move List") },
359 { 0,  0, 0, NULL, (void*) &appData.showCoords, "", NULL, CheckBox, N_("Show Coordinates") },
360 { 0,  0, 0, NULL, (void*) &appData.markers, "", NULL, CheckBox, N_("Show Target Squares") },
361 { 0,  0, 0, NULL, (void*) &appData.useStickyWindows, "", NULL, CheckBox, N_("Sticky Windows") },
362 { 0,  0, 0, NULL, (void*) &appData.testLegality, "", NULL, CheckBox, N_("Test Legality") },
363 { 0,  0, 0, NULL, (void*) &appData.topLevel, "", NULL, CheckBox, N_("Top-Level Dialogs") },
364 { 0, 0,10,  NULL, (void*) &appData.flashCount, "", NULL, Spin, N_("Flash Moves (0 = no flashing):") },
365 { 0, 1,10,  NULL, (void*) &appData.flashRate, "", NULL, Spin, N_("Flash Rate (high = fast):") },
366 { 0, 5,100, NULL, (void*) &appData.animSpeed, "", NULL, Spin, N_("Animation Speed (high = slow):") },
367 { 0, 1,5,   NULL, (void*) &appData.zoom, "", NULL, Spin, N_("Zoom factor in Evaluation Graph:") },
368 { 0,  0, 0, NULL, (void*) &GeneralOptionsOK, "", NULL, EndMark , "" }
369 };
370
371 void
372 OptionsProc ()
373 {
374    oldPonder = appData.ponderNextMove;
375    oldShow = appData.showCoords; oldBlind = appData.blindfold;
376    GenericPopUp(generalOptions, _("General Options"), TransientDlg, BoardWindow, MODAL, 0);
377 }
378
379 //---------------------------------------------- New Variant ------------------------------------------------
380
381 static void Pick P((int n));
382
383 static Option variantDescriptors[] = {
384 { VariantNormal,        0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("normal")},
385 { VariantFairy,  SAME_ROW, 135, NULL, (void*) &Pick, "#BFBFBF", NULL, Button, N_("fairy")},
386 { VariantFischeRandom,  0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("FRC")},
387 { VariantSChess, SAME_ROW, 135, NULL, (void*) &Pick, "#FFBFBF", NULL, Button, N_("Seirawan")},
388 { VariantWildCastle,    0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("wild castle")},
389 { VariantSuper,  SAME_ROW, 135, NULL, (void*) &Pick, "#FFBFBF", NULL, Button, N_("Superchess")},
390 { VariantNoCastle,      0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("no castle")},
391 { VariantCrazyhouse,SAME_ROW,135,NULL,(void*) &Pick, "#FFBFBF", NULL, Button, N_("crazyhouse")},
392 { VariantKnightmate,    0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("knightmate")},
393 { VariantBughouse,SAME_ROW,135, NULL, (void*) &Pick, "#FFBFBF", NULL, Button, N_("bughouse")},
394 { VariantBerolina,      0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("berolina")},
395 { VariantShogi,  SAME_ROW, 135, NULL, (void*) &Pick, "#BFFFFF", NULL, Button, N_("shogi (9x9)")},
396 { VariantCylinder,      0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("cylinder")},
397 { VariantXiangqi, SAME_ROW,135, NULL, (void*) &Pick, "#BFFFFF", NULL, Button, N_("xiangqi (9x10)")},
398 { VariantShatranj,      0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("shatranj")},
399 { VariantCourier, SAME_ROW,135, NULL, (void*) &Pick, "#BFFFBF", NULL, Button, N_("courier (12x8)")},
400 { VariantMakruk,        0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("makruk")},
401 { VariantGreat,  SAME_ROW, 135, NULL, (void*) &Pick, "#BFBFFF", NULL, Button, N_("Great Shatranj (10x8)")},
402 { VariantAtomic,        0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("atomic")},
403 { VariantFalcon, SAME_ROW, 135, NULL, (void*) &Pick, "#BFBFFF", NULL, Button, N_("falcon (10x8)")},
404 { VariantTwoKings,      0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("two kings")},
405 { VariantCapablanca,SAME_ROW,135,NULL,(void*) &Pick, "#BFBFFF", NULL, Button, N_("Capablanca (10x8)")},
406 { Variant3Check,        0, 135, NULL, (void*) &Pick, "#FFFFFF", NULL, Button, N_("3-checks")},
407 { VariantGothic, SAME_ROW, 135, NULL, (void*) &Pick, "#BFBFFF", NULL, Button, N_("Gothic (10x8)")},
408 { VariantSuicide,       0, 135, NULL, (void*) &Pick, "#FFFFBF", NULL, Button, N_("suicide")},
409 { VariantJanus,  SAME_ROW, 135, NULL, (void*) &Pick, "#BFBFFF", NULL, Button, N_("janus (10x8)")},
410 { VariantGiveaway,      0, 135, NULL, (void*) &Pick, "#FFFFBF", NULL, Button, N_("give-away")},
411 { VariantCapaRandom,SAME_ROW,135,NULL,(void*) &Pick, "#BFBFFF", NULL, Button, N_("CRC (10x8)")},
412 { VariantLosers,        0, 135, NULL, (void*) &Pick, "#FFFFBF", NULL, Button, N_("losers")},
413 { VariantGrand,  SAME_ROW, 135, NULL, (void*) &Pick, "#5070FF", NULL, Button, N_("grand (10x10)")},
414 { VariantSpartan,       0, 135, NULL, (void*) &Pick, "#FF0000", NULL, Button, N_("Spartan")},
415 { 0, 0, 0, NULL, NULL, NULL, NULL, Label, N_("Board size ( -1 = default for selected variant):")},
416 { 0, -1, BOARD_RANKS-1, NULL, (void*) &appData.NrRanks, "", NULL, Spin, N_("Number of Board Ranks:") },
417 { 0, -1, BOARD_FILES, NULL, (void*) &appData.NrFiles, "", NULL, Spin, N_("Number of Board Files:") },
418 { 0, -1, BOARD_RANKS-1, NULL, (void*) &appData.holdingsSize, "", NULL, Spin, N_("Holdings Size:") },
419 { 0, 0, 0, NULL, NULL, NULL, NULL, Label,
420                                 N_("WARNING: variants with un-orthodox\n"
421                                   "pieces only have built-in bitmaps\n"
422                                   "for -boardSize middling, bulky and\n"
423                                   "petite, and substitute king or amazon\n"
424                                   "for missing bitmaps. (See manual.)")},
425 { 0, NO_OK, 0, NULL, NULL, "", NULL, EndMark , "" }
426 };
427
428 static void
429 Pick (int n)
430 {
431         VariantClass v = variantDescriptors[n].value;
432         if(!appData.noChessProgram) {
433             char *name = VariantName(v), buf[MSG_SIZ];
434             if (first.protocolVersion > 1 && StrStr(first.variants, name) == NULL) {
435                 /* [HGM] in protocol 2 we check if variant is suported by engine */
436               snprintf(buf, MSG_SIZ,  _("Variant %s not supported by %s"), name, first.tidy);
437                 DisplayError(buf, 0);
438                 return; /* ignore OK if first engine does not support it */
439             } else
440             if (second.initDone && second.protocolVersion > 1 && StrStr(second.variants, name) == NULL) {
441               snprintf(buf, MSG_SIZ,  _("Warning: second engine (%s) does not support this!"), second.tidy);
442                 DisplayError(buf, 0);   /* use of second engine is optional; only warn user */
443             }
444         }
445
446         GenericReadout(variantDescriptors, -1); // make sure ranks and file settings are read
447
448         gameInfo.variant = v;
449         appData.variant = VariantName(v);
450
451         shuffleOpenings = FALSE; /* [HGM] shuffle: possible shuffle reset when we switch */
452         startedFromPositionFile = FALSE; /* [HGM] loadPos: no longer valid in new variant */
453         appData.pieceToCharTable = NULL;
454         appData.pieceNickNames = "";
455         appData.colorNickNames = "";
456         Reset(True, True);
457         PopDown(TransientDlg);
458         return;
459 }
460
461 void
462 NewVariantProc ()
463 {
464    GenericPopUp(variantDescriptors, _("New Variant"), TransientDlg, BoardWindow, MODAL, 0);
465 }
466
467 //------------------------------------------- Common Engine Options -------------------------------------
468
469 static int oldCores;
470
471 static int
472 CommonOptionsOK (int n)
473 {
474         int newPonder = appData.ponderNextMove;
475         // make sure changes are sent to first engine by re-initializing it
476         // if it was already started pre-emptively at end of previous game
477         if(gameMode == BeginningOfGame) Reset(True, True); else {
478             // Some changed setting need immediate sending always.
479             if(oldCores != appData.smpCores)
480                 NewSettingEvent(False, &(first.maxCores), "cores", appData.smpCores);
481             appData.ponderNextMove = oldPonder;
482             PonderNextMoveEvent(newPonder);
483         }
484         return 1;
485 }
486
487 static Option commonEngineOptions[] = {
488 { 0,  0,    0, NULL, (void*) &appData.ponderNextMove, "", NULL, CheckBox, N_("Ponder Next Move") },
489 { 0,  0, 1000, NULL, (void*) &appData.smpCores, "", NULL, Spin, N_("Maximum Number of CPUs per Engine:") },
490 { 0,  0,    0, NULL, (void*) &appData.polyglotDir, "", NULL, PathName, N_("Polygot Directory:") },
491 { 0,  0,16000, NULL, (void*) &appData.defaultHashSize, "", NULL, Spin, N_("Hash-Table Size (MB):") },
492 { 0,  0,    0, NULL, (void*) &appData.defaultPathEGTB, "", NULL, PathName, N_("Nalimov EGTB Path:") },
493 { 0,  0, 1000, NULL, (void*) &appData.defaultCacheSizeEGTB, "", NULL, Spin, N_("EGTB Cache Size (MB):") },
494 { 0,  0,    0, NULL, (void*) &appData.usePolyglotBook, "", NULL, CheckBox, N_("Use GUI Book") },
495 { 0,  0,    0, NULL, (void*) &appData.polyglotBook, ".bin", NULL, FileName, N_("Opening-Book Filename:") },
496 { 0,  0,  100, NULL, (void*) &appData.bookDepth, "", NULL, Spin, N_("Book Depth (moves):") },
497 { 0,  0,  100, NULL, (void*) &appData.bookStrength, "", NULL, Spin, N_("Book Variety (0) vs. Strength (100):") },
498 { 0,  0,    0, NULL, (void*) &appData.firstHasOwnBookUCI, "", NULL, CheckBox, N_("Engine #1 Has Own Book") },
499 { 0,  0,    0, NULL, (void*) &appData.secondHasOwnBookUCI, "", NULL, CheckBox, N_("Engine #2 Has Own Book          ") },
500 { 0,SAME_ROW,0,NULL, (void*) &CommonOptionsOK, "", NULL, EndMark , "" }
501 };
502
503 void
504 UciMenuProc ()
505 {
506    oldCores = appData.smpCores;
507    oldPonder = appData.ponderNextMove;
508    GenericPopUp(commonEngineOptions, _("Common Engine Settings"), TransientDlg, BoardWindow, MODAL, 0);
509 }
510
511 //------------------------------------------ Adjudication Options --------------------------------------
512
513 static Option adjudicationOptions[] = {
514 { 0, 0,    0, NULL, (void*) &appData.checkMates, "", NULL, CheckBox, N_("Detect all Mates") },
515 { 0, 0,    0, NULL, (void*) &appData.testClaims, "", NULL, CheckBox, N_("Verify Engine Result Claims") },
516 { 0, 0,    0, NULL, (void*) &appData.materialDraws, "", NULL, CheckBox, N_("Draw if Insufficient Mating Material") },
517 { 0, 0,    0, NULL, (void*) &appData.trivialDraws, "", NULL, CheckBox, N_("Adjudicate Trivial Draws (3-Move Delay)") },
518 { 0, 0,100,   NULL, (void*) &appData.ruleMoves, "", NULL, Spin, N_("N-Move Rule:") },
519 { 0, 0,    6, NULL, (void*) &appData.drawRepeats, "", NULL, Spin, N_("N-fold Repeats:") },
520 { 0, 0,1000,  NULL, (void*) &appData.adjudicateDrawMoves, "", NULL, Spin, N_("Draw after N Moves Total:") },
521 { 0, -5000,0, NULL, (void*) &appData.adjudicateLossThreshold, "", NULL, Spin, N_("Win / Loss Threshold:") },
522 { 0, 0,    0, NULL, (void*) &first.scoreIsAbsolute, "", NULL, CheckBox, N_("Negate Score of Engine #1") },
523 { 0, 0,    0, NULL, (void*) &second.scoreIsAbsolute, "", NULL, CheckBox, N_("Negate Score of Engine #2") },
524 { 0,SAME_ROW, 0, NULL, NULL, "", NULL, EndMark , "" }
525 };
526
527 void
528 EngineMenuProc ()
529 {
530    GenericPopUp(adjudicationOptions, _("Adjudicate non-ICS Games"), TransientDlg, BoardWindow, MODAL, 0);
531 }
532
533 //--------------------------------------------- ICS Options ---------------------------------------------
534
535 static int
536 IcsOptionsOK (int n)
537 {
538     ParseIcsTextColors();
539     return 1;
540 }
541
542 Option icsOptions[] = {
543 { 0, 0, 0, NULL, (void*) &appData.autoKibitz, "",  NULL, CheckBox, N_("Auto-Kibitz") },
544 { 0, 0, 0, NULL, (void*) &appData.autoComment, "", NULL, CheckBox, N_("Auto-Comment") },
545 { 0, 0, 0, NULL, (void*) &appData.autoObserve, "", NULL, CheckBox, N_("Auto-Observe") },
546 { 0, 0, 0, NULL, (void*) &appData.autoRaiseBoard, "", NULL, CheckBox, N_("Auto-Raise Board") },
547 { 0, 0, 0, NULL, (void*) &appData.bgObserve, "",   NULL, CheckBox, N_("Background Observe while Playing") },
548 { 0, 0, 0, NULL, (void*) &appData.dualBoard, "",   NULL, CheckBox, N_("Dual Board for Background-Observed Game") },
549 { 0, 0, 0, NULL, (void*) &appData.getMoveList, "", NULL, CheckBox, N_("Get Move List") },
550 { 0, 0, 0, NULL, (void*) &appData.quietPlay, "",   NULL, CheckBox, N_("Quiet Play") },
551 { 0, 0, 0, NULL, (void*) &appData.seekGraph, "",   NULL, CheckBox, N_("Seek Graph") },
552 { 0, 0, 0, NULL, (void*) &appData.autoRefresh, "", NULL, CheckBox, N_("Auto-Refresh Seek Graph") },
553 { 0, 0, 0, NULL, (void*) &appData.premove, "",     NULL, CheckBox, N_("Premove") },
554 { 0, 0, 0, NULL, (void*) &appData.premoveWhite, "", NULL, CheckBox, N_("Premove for White") },
555 { 0, 0, 0, NULL, (void*) &appData.premoveWhiteText, "", NULL, TextBox, N_("First White Move:") },
556 { 0, 0, 0, NULL, (void*) &appData.premoveBlack, "", NULL, CheckBox, N_("Premove for Black") },
557 { 0, 0, 0, NULL, (void*) &appData.premoveBlackText, "", NULL, TextBox, N_("First Black Move:") },
558 { 0, SAME_ROW, 0, NULL, NULL, NULL, NULL, Break, "" },
559 { 0, 0, 0, NULL, (void*) &appData.icsAlarm, "", NULL, CheckBox, N_("Alarm") },
560 { 0, 0, 100000000, NULL, (void*) &appData.icsAlarmTime, "", NULL, Spin, N_("Alarm Time (msec):") },
561 //{ 0, 0, 0, NULL, (void*) &appData.chatBoxes, "", NULL, TextBox, N_("Startup Chat Boxes:") },
562 { 0, 0, 0, NULL, (void*) &appData.colorize, "", NULL, CheckBox, N_("Colorize Messages") },
563 { 0, 0, 0, NULL, (void*) &appData.colorShout, "", NULL, TextBox, N_("Shout Text Colors:") },
564 { 0, 0, 0, NULL, (void*) &appData.colorSShout, "", NULL, TextBox, N_("S-Shout Text Colors:") },
565 { 0, 0, 0, NULL, (void*) &appData.colorChannel1, "", NULL, TextBox, N_("Channel #1 Text Colors:") },
566 { 0, 0, 0, NULL, (void*) &appData.colorChannel, "", NULL, TextBox, N_("Other Channel Text Colors:") },
567 { 0, 0, 0, NULL, (void*) &appData.colorKibitz, "", NULL, TextBox, N_("Kibitz Text Colors:") },
568 { 0, 0, 0, NULL, (void*) &appData.colorTell, "", NULL, TextBox, N_("Tell Text Colors:") },
569 { 0, 0, 0, NULL, (void*) &appData.colorChallenge, "", NULL, TextBox, N_("Challenge Text Colors:") },
570 { 0, 0, 0, NULL, (void*) &appData.colorRequest, "", NULL, TextBox, N_("Request Text Colors:") },
571 { 0, 0, 0, NULL, (void*) &appData.colorSeek, "", NULL, TextBox, N_("Seek Text Colors:") },
572 { 0, 0, 0, NULL, (void*) &IcsOptionsOK, "", NULL, EndMark , "" }
573 };
574
575 void
576 IcsOptionsProc ()
577 {
578    GenericPopUp(icsOptions, _("ICS Options"), TransientDlg, BoardWindow, MODAL, 0);
579 }
580
581 //-------------------------------------------- Load Game Options ---------------------------------
582
583 static char *modeNames[] = { N_("Exact position match"), N_("Shown position is subset"), N_("Same material with exactly same Pawn chain"), 
584                       N_("Same material"), N_("Material range (top board half optional)"), N_("Material difference (optional stuff balanced)"), NULL };
585 static char *modeValues[] = { "1", "2", "3", "4", "5", "6" };
586 static char *searchMode;
587
588 static int
589 LoadOptionsOK ()
590 {
591     appData.searchMode = atoi(searchMode);
592     return 1;
593 }
594
595 static Option loadOptions[] = {
596 { 0,  0, 0,     NULL, (void*) &appData.autoDisplayTags, "", NULL, CheckBox, N_("Auto-Display Tags") },
597 { 0,  0, 0,     NULL, (void*) &appData.autoDisplayComment, "", NULL, CheckBox, N_("Auto-Display Comment") },
598 { 0, LR, 0,     NULL, NULL, NULL, NULL, Label, N_("Auto-Play speed of loaded games\n(0 = instant, -1 = off):") },
599 { 0, -1,10000000, NULL, (void*) &appData.timeDelay, "", NULL, Fractional, N_("Seconds per Move:") },
600 { 0, LR, 0,     NULL, NULL, NULL, NULL, Label,  N_("\noptions to use in game-viewer mode:") },
601 { 0, 0,300,     NULL, (void*) &appData.viewerOptions, "", NULL, TextBox,  "" },
602 { 0, LR,  0,    NULL, NULL, NULL, NULL, Label,  N_("\nThresholds for position filtering in game list:") },
603 { 0, 0,5000,    NULL, (void*) &appData.eloThreshold1, "", NULL, Spin, N_("Elo of strongest player at least:") },
604 { 0, 0,5000,    NULL, (void*) &appData.eloThreshold2, "", NULL, Spin, N_("Elo of weakest player at least:") },
605 { 0, 0,5000,    NULL, (void*) &appData.dateThreshold, "", NULL, Spin, N_("No games before year:") },
606 { 0, 1,50,      NULL, (void*) &appData.stretch, "", NULL, Spin, N_("Minimum nr consecutive positions:") },
607 { 0, 0,205,     NULL, (void*) &searchMode, (char*) modeValues, modeNames, ComboBox, N_("Search mode:") },
608 { 0, 0, 0,      NULL, (void*) &appData.ignoreColors, "", NULL, CheckBox, N_("Also match reversed colors") },
609 { 0, 0, 0,      NULL, (void*) &appData.findMirror, "", NULL, CheckBox, N_("Also match left-right flipped position") },
610 { 0,  0, 0,     NULL, (void*) &LoadOptionsOK, "", NULL, EndMark , "" }
611 };
612
613 void
614 LoadOptionsPopUp (DialogClass parent)
615 {
616    ASSIGN(searchMode, modeValues[appData.searchMode-1]);
617    GenericPopUp(loadOptions, _("Load Game Options"), TransientDlg, parent, MODAL, 0);
618 }
619
620 void
621 LoadOptionsProc ()
622 {   // called from menu
623     LoadOptionsPopUp(BoardWindow);
624 }
625
626 //------------------------------------------- Save Game Options --------------------------------------------
627
628 static Option saveOptions[] = {
629 { 0, 0, 0, NULL, (void*) &appData.autoSaveGames, "", NULL, CheckBox, N_("Auto-Save Games") },
630 { 0, 0, 0, NULL, (void*) &appData.saveGameFile, ".pgn", NULL, FileName,  N_("Save Games on File:") },
631 { 0, 0, 0, NULL, (void*) &appData.savePositionFile, ".fen", NULL, FileName,  N_("Save Final Positions on File:") },
632 { 0, 0, 0, NULL, (void*) &appData.pgnEventHeader, "", NULL, TextBox,  N_("PGN Event Header:") },
633 { 0, 0, 0, NULL, (void*) &appData.oldSaveStyle, "", NULL, CheckBox, N_("Old Save Style (as opposed to PGN)") },
634 { 0, 0, 0, NULL, (void*) &appData.numberTag, "", NULL, CheckBox, N_("Include Number Tag in tourney PGN") },
635 { 0, 0, 0, NULL, (void*) &appData.saveExtendedInfoInPGN, "", NULL, CheckBox, N_("Save Score/Depth Info in PGN") },
636 { 0, 0, 0, NULL, (void*) &appData.saveOutOfBookInfo, "", NULL, CheckBox, N_("Save Out-of-Book Info in PGN           ") },
637 { 0, SAME_ROW, 0, NULL, NULL, "", NULL, EndMark , "" }
638 };
639
640 void
641 SaveOptionsProc ()
642 {
643    GenericPopUp(saveOptions, _("Save Game Options"), TransientDlg, BoardWindow, MODAL, 0);
644 }
645
646 //----------------------------------------------- Sound Options ---------------------------------------------
647
648 static void Test P((int n));
649 static char *trialSound;
650
651 static char *soundNames[] = {
652         N_("No Sound"),
653         N_("Default Beep"),
654         N_("Above WAV File"),
655         N_("Car Horn"),
656         N_("Cymbal"),
657         N_("Ding"),
658         N_("Gong"),
659         N_("Laser"),
660         N_("Penalty"),
661         N_("Phone"),
662         N_("Pop"),
663         N_("Slap"),
664         N_("Wood Thunk"),
665         NULL,
666         N_("User File")
667 };
668
669 static char *soundFiles[] = { // sound files corresponding to above names
670         "",
671         "$",
672         NULL, // kludge alert: as first thing in the dialog readout this is replaced with the user-given .WAV filename
673         "honkhonk.wav",
674         "cymbal.wav",
675         "ding1.wav",
676         "gong.wav",
677         "laser.wav",
678         "penalty.wav",
679         "phone.wav",
680         "pop2.wav",
681         "slap.wav",
682         "woodthunk.wav",
683         NULL,
684         NULL
685 };
686
687 static Option soundOptions[] = {
688 { 0, 0, 0, NULL, (void*) &appData.soundProgram, "", NULL, TextBox, N_("Sound Program:") },
689 { 0, 0, 0, NULL, (void*) &appData.soundDirectory, "", NULL, PathName, N_("Sounds Directory:") },
690 { 0, 0, 0, NULL, (void*) (soundFiles+2) /* kludge! */, ".wav", NULL, FileName, N_("User WAV File:") },
691 { 0, 0, 0, NULL, (void*) &trialSound, (char*) soundFiles, soundNames, ComboBox, N_("Try-Out Sound:") },
692 { 0, SAME_ROW, 0, NULL, (void*) &Test, NULL, NULL, Button, N_("Play") },
693 { 0, 0, 0, NULL, (void*) &appData.soundMove, (char*) soundFiles, soundNames, ComboBox, N_("Move:") },
694 { 0, 0, 0, NULL, (void*) &appData.soundIcsWin, (char*) soundFiles, soundNames, ComboBox, N_("Win:") },
695 { 0, 0, 0, NULL, (void*) &appData.soundIcsLoss, (char*) soundFiles, soundNames, ComboBox, N_("Lose:") },
696 { 0, 0, 0, NULL, (void*) &appData.soundIcsDraw, (char*) soundFiles, soundNames, ComboBox, N_("Draw:") },
697 { 0, 0, 0, NULL, (void*) &appData.soundIcsUnfinished, (char*) soundFiles, soundNames, ComboBox, N_("Unfinished:") },
698 { 0, 0, 0, NULL, (void*) &appData.soundIcsAlarm, (char*) soundFiles, soundNames, ComboBox, N_("Alarm:") },
699 { 0, 0, 0, NULL, (void*) &appData.soundShout, (char*) soundFiles, soundNames, ComboBox, N_("Shout:") },
700 { 0, 0, 0, NULL, (void*) &appData.soundSShout, (char*) soundFiles, soundNames, ComboBox, N_("S-Shout:") },
701 { 0, 0, 0, NULL, (void*) &appData.soundChannel, (char*) soundFiles, soundNames, ComboBox, N_("Channel:") },
702 { 0, 0, 0, NULL, (void*) &appData.soundChannel1, (char*) soundFiles, soundNames, ComboBox, N_("Channel 1:") },
703 { 0, 0, 0, NULL, (void*) &appData.soundTell, (char*) soundFiles, soundNames, ComboBox, N_("Tell:") },
704 { 0, 0, 0, NULL, (void*) &appData.soundKibitz, (char*) soundFiles, soundNames, ComboBox, N_("Kibitz:") },
705 { 0, 0, 0, NULL, (void*) &appData.soundChallenge, (char*) soundFiles, soundNames, ComboBox, N_("Challenge:") },
706 { 0, 0, 0, NULL, (void*) &appData.soundRequest, (char*) soundFiles, soundNames, ComboBox, N_("Request:") },
707 { 0, 0, 0, NULL, (void*) &appData.soundSeek, (char*) soundFiles, soundNames, ComboBox, N_("Seek:") },
708 { 0, SAME_ROW, 0, NULL, NULL, "", NULL, EndMark , "" }
709 };
710
711 static void
712 Test (int n)
713 {
714     GenericReadout(soundOptions, 2);
715     if(soundFiles[values[3]]) PlaySound(soundFiles[values[3]]);
716 }
717
718 void
719 SoundOptionsProc ()
720 {
721    free(soundFiles[2]);
722    soundFiles[2] = strdup("*");
723    GenericPopUp(soundOptions, _("Sound Options"), TransientDlg, BoardWindow, MODAL, 0);
724 }
725
726 //--------------------------------------------- Board Options --------------------------------------
727
728 static void DefColor P((int n));
729 static void AdjustColor P((int i));
730
731 static int
732 BoardOptionsOK (int n)
733 {
734     if(appData.overrideLineGap >= 0) lineGap = appData.overrideLineGap; else lineGap = defaultLineGap;
735     useImages = useImageSqs = 0;
736     InitDrawingParams();
737     InitDrawingSizes(-1, 0);
738     DrawPosition(True, NULL);
739     return 1;
740 }
741
742 static Option boardOptions[] = {
743 { 0,          0, 70, NULL, (void*) &appData.whitePieceColor, "", NULL, TextBox, N_("White Piece Color:") },
744 { 1000, SAME_ROW, 0, NULL, (void*) &DefColor, NULL, (char**) "#FFFFCC", Button, "      " },
745 /* TRANSLATORS: R = single letter for the color red */
746 {    1, SAME_ROW, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, N_("R") },
747 /* TRANSLATORS: G = single letter for the color green */
748 {    2, SAME_ROW, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, N_("G") },
749 /* TRANSLATORS: B = single letter for the color blue */
750 {    3, SAME_ROW, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, N_("B") },
751 /* TRANSLATORS: D = single letter to make a color darker */
752 {    4, SAME_ROW, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, N_("D") },
753 { 0,          0, 70, NULL, (void*) &appData.blackPieceColor, "", NULL, TextBox, N_("Black Piece Color:") },
754 { 1000, SAME_ROW, 0, NULL, (void*) &DefColor, NULL, (char**) "#202020", Button, "      " },
755 {    1, SAME_ROW, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, N_("R") },
756 {    2, SAME_ROW, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, N_("G") },
757 {    3, SAME_ROW, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, N_("B") },
758 {    4, SAME_ROW, 0, NULL, (void*) &AdjustColor, NULL, NULL, Button, N_("D") },
759 { 0,          0, 70, NULL, (void*) &appData.lightSquareColor, "", NULL, TextBox, N_("Light Square Color:") },
760 { 1000, SAME_ROW, 0, NULL, (void*) &DefColor, NULL, (char**) "#C8C365", 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.darkSquareColor, "", NULL, TextBox, N_("Dark Square Color:") },
766 { 1000, SAME_ROW, 0, NULL, (void*) &DefColor, NULL, (char**) "#77A26D", 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.highlightSquareColor, "", NULL, TextBox, N_("Highlight Color:") },
772 { 1000, SAME_ROW, 0, NULL, (void*) &DefColor, NULL, (char**) "#FFFF00", 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.premoveHighlightColor, "", NULL, TextBox, N_("Premove Highlight Color:") },
778 { 1000, SAME_ROW, 0, NULL, (void*) &DefColor, NULL, (char**) "#FF0000", 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, 0, NULL, (void*) &appData.upsideDown, "", NULL, CheckBox, N_("Flip Pieces Shogi Style        (Colored buttons restore default)") },
784 //{ 0, 0, 0, NULL, (void*) &appData.allWhite, "", NULL, CheckBox, N_("Use Outline Pieces for Black") },
785 { 0, 0, 0, NULL, (void*) &appData.monoMode, "", NULL, CheckBox, N_("Mono Mode") },
786 { 0,-1, 5, NULL, (void*) &appData.overrideLineGap, "", NULL, Spin, N_("Line Gap ( -1 = default for board size):") },
787 { 0, 0, 0, NULL, (void*) &appData.useBitmaps, "", NULL, CheckBox, N_("Use Board Textures") },
788 { 0, 0, 0, NULL, (void*) &appData.liteBackTextureFile, ".xpm", NULL, FileName, N_("Light-Squares Texture File:") },
789 { 0, 0, 0, NULL, (void*) &appData.darkBackTextureFile, ".xpm", NULL, FileName, N_("Dark-Squares Texture File:") },
790 { 0, 0, 0, NULL, (void*) &appData.bitmapDirectory, "", NULL, PathName, N_("Directory with Bitmap Pieces:") },
791 { 0, 0, 0, NULL, (void*) &appData.pixmapDirectory, "", NULL, PathName, N_("Directory with Pixmap Pieces:") },
792 { 0, 0, 0, NULL, (void*) &BoardOptionsOK, "", NULL, EndMark , "" }
793 };
794
795 static void
796 SetColorText (int n, char *buf)
797 {
798     SetWidgetText(&boardOptions[n-1], buf, TransientDlg);
799     SetColor(buf, &boardOptions[n]);
800 }
801
802 static void
803 DefColor (int n)
804 {
805     SetColorText(n, (char*) boardOptions[n].choice);
806 }
807
808 void
809 RefreshColor (int source, int n)
810 {
811     int col, j, r, g, b, step = 10;
812     char *s, buf[MSG_SIZ]; // color string
813     GetWidgetText(&boardOptions[source], &s);
814     if(sscanf(s, "#%x", &col) != 1) return;   // malformed
815     b = col & 0xFF; g = col & 0xFF00; r = col & 0xFF0000;
816     switch(n) {
817         case 1: r += 0x10000*step;break;
818         case 2: g += 0x100*step;  break;
819         case 3: b += step;        break;
820         case 4: r -= 0x10000*step; g -= 0x100*step; b -= step; break;
821     }
822     if(r < 0) r = 0; if(g < 0) g = 0; if(b < 0) b = 0;
823     if(r > 0xFF0000) r = 0xFF0000; if(g > 0xFF00) g = 0xFF00; if(b > 0xFF) b = 0xFF;
824     col = r | g | b;
825     snprintf(buf, MSG_SIZ, "#%06x", col);
826     for(j=1; j<7; j++) if(buf[j] >= 'a') buf[j] -= 32; // capitalize
827     SetColorText(source+1, buf);
828 }
829
830 static void
831 AdjustColor (int i)
832 {
833     int n = boardOptions[i].value;
834     RefreshColor(i-n-1, n);
835 }
836
837 void
838 BoardOptionsProc ()
839 {
840    GenericPopUp(boardOptions, _("Board Options"), TransientDlg, BoardWindow, MODAL, 0);
841 }
842
843 //-------------------------------------------- ICS Text Menu Options ------------------------------
844
845 Option textOptions[100];
846 static void PutText P((char *text, int pos));
847
848 void
849 SendString (char *p)
850 {
851     char buf[MSG_SIZ], *q;
852     if(q = strstr(p, "$input")) {
853         if(!shellUp[TextMenuDlg]) return;
854         strncpy(buf, p, MSG_SIZ);
855         strncpy(buf + (q-p), q+6, MSG_SIZ-(q-p));
856         PutText(buf, q-p);
857         return;
858     }
859     snprintf(buf, MSG_SIZ, "%s\n", p);
860     SendToICS(buf);
861 }
862
863 void
864 IcsTextProc ()
865 {
866    int i=0, j;
867    char *p, *q, *r;
868    if((p = icsTextMenuString) == NULL) return;
869    do {
870         q = r = p; while(*p && *p != ';') p++;
871         for(j=0; j<p-q; j++) textOptions[i].name[j] = *r++;
872         textOptions[i].name[j++] = 0;
873         if(!*p) break;
874         if(*++p == '\n') p++; // optional linefeed after button-text terminating semicolon
875         q = p;
876         textOptions[i].choice = (char**) (r = textOptions[i].name + j);
877         while(*p && (*p != ';' || p[1] != '\n')) textOptions[i].name[j++] = *p++;
878         textOptions[i].name[j++] = 0;
879         if(*p) p += 2;
880         textOptions[i].max = 135;
881         textOptions[i].min = i&1;
882         textOptions[i].handle = NULL;
883         textOptions[i].target = &SendText;
884         textOptions[i].textValue = strstr(r, "$input") ? "#80FF80" : strstr(r, "$name") ? "#FF8080" : "#FFFFFF";
885         textOptions[i].type = Button;
886    } while(++i < 99 && *p);
887    if(i == 0) return;
888    textOptions[i].type = EndMark;
889    textOptions[i].target = NULL;
890    textOptions[i].min = 2;
891    MarkMenu("ICStex", TextMenuDlg);
892    GenericPopUp(textOptions, _("ICS text menu"), TextMenuDlg, BoardWindow, NONMODAL, 1);
893 }
894
895 //---------------------------------------------------- Edit Comment -----------------------------------
896
897 static char *commentText;
898 static int commentIndex;
899 static void ClearComment P((int n));
900 static void SaveChanges P((int n));
901
902 static int
903 NewComCallback (int n)
904 {
905     ReplaceComment(commentIndex, commentText);
906     return 1;
907 }
908
909 Option commentOptions[] = {
910 { 200, T_VSCRL | T_FILL | T_WRAP | T_TOP, 250, NULL, (void*) &commentText, "", NULL, TextBox, "" },
911 { 0,     0,     50, NULL, (void*) &ClearComment, NULL, NULL, Button, N_("clear") },
912 { 0, SAME_ROW, 100, NULL, (void*) &SaveChanges, NULL, NULL, Button, N_("save changes") },
913 { 0, SAME_ROW,  0,  NULL, (void*) &NewComCallback, "", NULL, EndMark , "" }
914 };
915
916 static void
917 SaveChanges (int n)
918 {
919     GenericReadout(commentOptions, 0);
920     ReplaceComment(commentIndex, commentText);
921 }
922
923 static void
924 ClearComment (int n)
925 {
926     SetWidgetText(&commentOptions[0], "", CommentDlg);
927 }
928
929 void
930 NewCommentPopup (char *title, char *text, int index)
931 {
932     if(DialogExists(CommentDlg)) { // if already exists, alter title and content
933         SetDialogTitle(CommentDlg, title);
934         SetWidgetText(&commentOptions[0], text, CommentDlg);
935     }
936     if(commentText) free(commentText); commentText = strdup(text);
937     commentIndex = index;
938     MarkMenu("Show Comments", CommentDlg);
939     if(GenericPopUp(commentOptions, title, CommentDlg, BoardWindow, NONMODAL, 1))
940         AddHandler(&commentOptions[0], 1);
941 }
942
943 void
944 EditCommentProc ()
945 {
946     int j;
947     if (PopDown(CommentDlg)) { // popdown succesful
948         MarkMenuItem("Edit Comment", False);
949         MarkMenuItem("Show Comments", False);
950     } else // was not up
951         EditCommentEvent();
952 }
953
954 //------------------------------------------------------ Edit Tags ----------------------------------
955
956 static void changeTags P((int n));
957 static char *tagsText;
958
959 static int
960 NewTagsCallback (int n)
961 {
962     ReplaceTags(tagsText, &gameInfo);
963     return 1;
964 }
965
966 static Option tagsOptions[] = {
967 {   0,   0,   0, NULL, NULL, NULL, NULL, Label,  NULL },
968 { 200, T_VSCRL | T_FILL | T_WRAP | T_TOP, 200, NULL, (void*) &tagsText, "", NULL, TextBox, "" },
969 {   0,   0, 100, NULL, (void*) &changeTags, NULL, NULL, Button, N_("save changes") },
970 { 0,SAME_ROW, 0, NULL, (void*) &NewTagsCallback, "", NULL, EndMark , "" }
971 };
972
973 static void
974 changeTags (int n)
975 {
976     GenericReadout(tagsOptions, 1);
977     if(bookUp) SaveToBook(tagsText); else
978     ReplaceTags(tagsText, &gameInfo);
979 }
980
981 void
982 NewTagsPopup (char *text, char *msg)
983 {
984     char *title = bookUp ? _("Edit book") : _("Tags");
985
986     if(DialogExists(TagsDlg)) { // if already exists, alter title and content
987         SetWidgetText(&tagsOptions[1], text, TagsDlg);
988         SetDialogTitle(TagsDlg, title);
989     }
990     if(tagsText) free(tagsText); tagsText = strdup(text);
991     tagsOptions[0].name = msg;
992     MarkMenu("Show Tags", TagsDlg);
993     GenericPopUp(tagsOptions, title, TagsDlg, BoardWindow, NONMODAL, 1);
994 }
995
996 //---------------------------------------------- ICS Input Box ----------------------------------
997
998 char *icsText;
999
1000 // [HGM] code borrowed from winboard.c (which should thus go to backend.c!)
1001 #define HISTORY_SIZE 64
1002 static char *history[HISTORY_SIZE];
1003 static int histIn = 0, histP = 0;
1004
1005 static void
1006 SaveInHistory (char *cmd)
1007 {
1008   if (history[histIn] != NULL) {
1009     free(history[histIn]);
1010     history[histIn] = NULL;
1011   }
1012   if (*cmd == NULLCHAR) return;
1013   history[histIn] = StrSave(cmd);
1014   histIn = (histIn + 1) % HISTORY_SIZE;
1015   if (history[histIn] != NULL) {
1016     free(history[histIn]);
1017     history[histIn] = NULL;
1018   }
1019   histP = histIn;
1020 }
1021
1022 static char *
1023 PrevInHistory (char *cmd)
1024 {
1025   int newhp;
1026   if (histP == histIn) {
1027     if (history[histIn] != NULL) free(history[histIn]);
1028     history[histIn] = StrSave(cmd);
1029   }
1030   newhp = (histP - 1 + HISTORY_SIZE) % HISTORY_SIZE;
1031   if (newhp == histIn || history[newhp] == NULL) return NULL;
1032   histP = newhp;
1033   return history[histP];
1034 }
1035
1036 static char *
1037 NextInHistory ()
1038 {
1039   if (histP == histIn) return NULL;
1040   histP = (histP + 1) % HISTORY_SIZE;
1041   return history[histP];   
1042 }
1043 // end of borrowed code
1044
1045 Option boxOptions[] = {
1046 {  30,  0,  400, NULL, (void*) &icsText, "", NULL, TextBox, "" },
1047 {  0,SAME_ROW | NO_OK, 0, NULL, NULL, "", NULL, EndMark , "" }
1048 };
1049
1050 void
1051 ICSInputSendText ()
1052 {
1053     char *val;
1054
1055     GetWidgetText(&boxOptions[0], &val);
1056     SaveInHistory(val);
1057     SendMultiLineToICS(val);
1058     SetWidgetText(&boxOptions[0], val, InputBoxDlg);
1059 }
1060
1061 void
1062 IcsKey (int n)
1063 {   // [HGM] input: let up-arrow recall previous line from history
1064     char *val;
1065
1066     if (!shellUp[InputBoxDlg]) return;
1067     switch(n) {
1068       case 0:
1069         ICSInputSendText();
1070         return;
1071       case 1:
1072         GetWidgetText(&boxOptions[0], &val);
1073         val = PrevInHistory(val);
1074         break;
1075       case -1:
1076         val = NextInHistory();
1077     }
1078     SetWidgetText(&boxOptions[0], val ? val : "", InputBoxDlg);
1079 }
1080
1081 static void
1082 PutText (char *text, int pos)
1083 {
1084     char buf[MSG_SIZ], *p;
1085
1086     if(strstr(text, "$add ") == text) {
1087         GetWidgetText(&boxOptions[0], &p);
1088         snprintf(buf, MSG_SIZ, "%s%s", p, text+5); text = buf;
1089         pos += strlen(p) - 5;
1090     }
1091     SetWidgetText(&boxOptions[0], text, TextMenuDlg);
1092     SetInsertPos(&boxOptions[0], pos);
1093 }
1094
1095 void
1096 ICSInputBoxPopUp ()
1097 {
1098     MarkMenu("ICS Input Box", InputBoxDlg);
1099     if(GenericPopUp(boxOptions, _("ICS input box"), InputBoxDlg, BoardWindow, NONMODAL, 0))
1100         AddHandler(&boxOptions[0], 3);
1101 }
1102
1103 void
1104 IcsInputBoxProc ()
1105 {
1106     if (!PopDown(InputBoxDlg)) ICSInputBoxPopUp();
1107 }
1108
1109 //--------------------------------------------- Move Type In ------------------------------------------
1110
1111 static int TypeInOK P((int n));
1112
1113 Option typeOptions[] = {
1114 { 30,  0,            400, NULL, (void*) &icsText, "", NULL, TextBox, "" },
1115 { 0, SAME_ROW | NO_OK, 0, NULL, (void*) &TypeInOK, "", NULL, EndMark , "" }
1116 };
1117
1118 static int
1119 TypeInOK (int n)
1120 {
1121     TypeInDoneEvent(icsText);
1122     return TRUE;
1123 }
1124
1125 void
1126 PopUpMoveDialog (char firstchar)
1127 {
1128     static char buf[2];
1129     buf[0] = firstchar; ASSIGN(icsText, buf);
1130     if(GenericPopUp(typeOptions, _("Type a move"), TransientDlg, BoardWindow, MODAL, 0))
1131         AddHandler(&typeOptions[0], 2);
1132 }
1133
1134 void
1135 BoxAutoPopUp (char *buf)
1136 {
1137         if(appData.icsActive) { // text typed to board in ICS mode: divert to ICS input box
1138             if(DialogExists(InputBoxDlg)) { // box already exists: append to current contents
1139                 char *p, newText[MSG_SIZ];
1140                 GetWidgetText(&boxOptions[0], &p);
1141                 snprintf(newText, MSG_SIZ, "%s%c", p, *buf);
1142                 SetWidgetText(&boxOptions[0], newText, InputBoxDlg);
1143                 if(shellUp[InputBoxDlg]) HardSetFocus (&boxOptions[0]); //why???
1144             } else icsText = buf; // box did not exist: make sure it pops up with char in it
1145             ICSInputBoxPopUp();
1146         } else PopUpMoveDialog(*buf);
1147 }
1148
1149 //------------------------------------------ Engine Settings ------------------------------------
1150
1151 void
1152 SettingsPopUp (ChessProgramState *cps)
1153 {
1154    currentCps = cps;
1155    GenericPopUp(cps->option, _("Engine Settings"), TransientDlg, BoardWindow, MODAL, 0);
1156 }
1157
1158 void
1159 FirstSettingsProc ()
1160 {
1161     SettingsPopUp(&first);
1162 }
1163
1164 void
1165 SecondSettingsProc ()
1166 {
1167    if(WaitForEngine(&second, SettingsMenuIfReady)) return;
1168    SettingsPopUp(&second);
1169 }
1170
1171 //----------------------------------------------- Load Engine --------------------------------------
1172
1173 char *engineDir, *engineLine, *nickName, *params;
1174 Boolean isUCI, hasBook, storeVariant, v1, addToList, useNick;
1175 static char *engineNr[] = { N_("First Engine"), N_("Second Engine"), NULL };
1176
1177 static int
1178 InstallOK (int n)
1179 {
1180     PopDown(TransientDlg); // early popdown, to allow FreezeUI to instate grab
1181     if(engineChoice[0] == engineNr[0][0])  Load(&first, 0); else Load(&second, 1);
1182     return FALSE; // no double PopDown!
1183 }
1184
1185 static Option installOptions[] = {
1186 {   0,  NO_GETTEXT, 0, NULL, (void*) &engineLine, (char*) engineList, engineMnemonic, ComboBox, N_("Select engine from list:") },
1187 {   0,  LR,   0, NULL, NULL, NULL, NULL, Label, N_("or specify one below:") },
1188 {   0,  0,    0, NULL, (void*) &nickName, NULL, NULL, TextBox, N_("Nickname (optional):") },
1189 {   0,  0,    0, NULL, (void*) &useNick, NULL, NULL, CheckBox, N_("Use nickname in PGN player tags of engine-engine games") },
1190 {   0,  0,    0, NULL, (void*) &engineDir, NULL, NULL, PathName, N_("Engine Directory:") },
1191 {   0,  0,    0, NULL, (void*) &engineName, NULL, NULL, FileName, N_("Engine Command:") },
1192 {   0,  LR,   0, NULL, NULL, NULL, NULL, Label, N_("(Directory will be derived from engine path when empty)") },
1193 {   0,  0,    0, NULL, (void*) &isUCI, NULL, NULL, CheckBox, N_("UCI") },
1194 {   0,  0,    0, NULL, (void*) &v1, NULL, NULL, CheckBox, N_("WB protocol v1 (do not wait for engine features)") },
1195 {   0,  0,    0, NULL, (void*) &hasBook, NULL, NULL, CheckBox, N_("Must not use GUI book") },
1196 {   0,  0,    0, NULL, (void*) &addToList, NULL, NULL, CheckBox, N_("Add this engine to the list") },
1197 {   0,  0,    0, NULL, (void*) &storeVariant, NULL, NULL, CheckBox, N_("Force current variant with this engine") },
1198 {   0,  0,    0, NULL, (void*) &engineChoice, (char*) engineNr, engineNr, ComboBox, N_("Load mentioned engine as") },
1199 { 0,SAME_ROW, 0, NULL, (void*) &InstallOK, "", NULL, EndMark , "" }
1200 };
1201
1202 void
1203 LoadEngineProc ()
1204 {
1205    isUCI = storeVariant = v1 = useNick = False; addToList = hasBook = True; // defaults
1206    if(engineChoice) free(engineChoice); engineChoice = strdup(engineNr[0]);
1207    if(engineLine)   free(engineLine);   engineLine = strdup("");
1208    if(engineDir)    free(engineDir);    engineDir = strdup("");
1209    if(nickName)     free(nickName);     nickName = strdup("");
1210    if(params)       free(params);       params = strdup("");
1211    NamesToList(firstChessProgramNames, engineList, engineMnemonic, "all");
1212    GenericPopUp(installOptions, _("Load engine"), TransientDlg, BoardWindow, MODAL, 0);
1213 }
1214
1215 //----------------------------------------------------- Edit Book -----------------------------------------
1216
1217 void
1218 EditBookProc ()
1219 {
1220     EditBookEvent();
1221 }
1222
1223 //--------------------------------------------------- New Shuffle Game ------------------------------
1224
1225 static void SetRandom P((int n));
1226
1227 static int
1228 ShuffleOK (int n)
1229 {
1230     ResetGameEvent();
1231     return 1;
1232 }
1233
1234 static Option shuffleOptions[] = {
1235   {   0,  0,   50, NULL, (void*) &shuffleOpenings, NULL, NULL, CheckBox, N_("shuffle") },
1236   { 0,-1,2000000000, NULL, (void*) &appData.defaultFrcPosition, "", NULL, Spin, N_("Start-position number:") },
1237   {   0,  0,    0, NULL, (void*) &SetRandom, NULL, NULL, Button, N_("randomize") },
1238   {   0,  SAME_ROW,    0, NULL, (void*) &SetRandom, NULL, NULL, Button, N_("pick fixed") },
1239   { 0,SAME_ROW, 0, NULL, (void*) &ShuffleOK, "", NULL, EndMark , "" }
1240 };
1241
1242 static void
1243 SetRandom (int n)
1244 {
1245     int r = n==2 ? -1 : random() & (1<<30)-1;
1246     char buf[MSG_SIZ];
1247     snprintf(buf, MSG_SIZ,  "%d", r);
1248     SetWidgetText(&shuffleOptions[1], buf, TransientDlg);
1249     SetWidgetState(&shuffleOptions[0], True);
1250 }
1251
1252 void
1253 ShuffleMenuProc ()
1254 {
1255     GenericPopUp(shuffleOptions, _("New Shuffle Game"), TransientDlg, BoardWindow, MODAL, 0);
1256 }
1257
1258 //------------------------------------------------------ Time Control -----------------------------------
1259
1260 static int TcOK P((int n));
1261 int tmpMoves, tmpTc, tmpInc, tmpOdds1, tmpOdds2, tcType;
1262
1263 static void
1264 ShowTC (int n)
1265 {
1266 }
1267
1268 static void SetTcType P((int n));
1269
1270 static char *
1271 Value (int n)
1272 {
1273         static char buf[MSG_SIZ];
1274         snprintf(buf, MSG_SIZ, "%d", n);
1275         return buf;
1276 }
1277
1278 static Option tcOptions[] = {
1279 {   0,  0,    0, NULL, (void*) &SetTcType, NULL, NULL, Button, N_("classical") },
1280 {   0,SAME_ROW,0,NULL, (void*) &SetTcType, NULL, NULL, Button, N_("incremental") },
1281 {   0,SAME_ROW,0,NULL, (void*) &SetTcType, NULL, NULL, Button, N_("fixed max") },
1282 {   0,  0,  200, NULL, (void*) &tmpMoves, NULL, NULL, Spin, N_("Moves per session:") },
1283 {   0,  0,10000, NULL, (void*) &tmpTc,    NULL, NULL, Spin, N_("Initial time (min):") },
1284 {   0, 0, 10000, NULL, (void*) &tmpInc,   NULL, NULL, Spin, N_("Increment or max (sec/move):") },
1285 {   0,  0,    0, NULL, NULL, NULL, NULL, Label, N_("Time-Odds factors:") },
1286 {   0,  1, 1000, NULL, (void*) &tmpOdds1, NULL, NULL, Spin, N_("Engine #1") },
1287 {   0,  1, 1000, NULL, (void*) &tmpOdds2, NULL, NULL, Spin, N_("Engine #2 / Human") },
1288 {   0,  0,    0, NULL, (void*) &TcOK, "", NULL, EndMark , "" }
1289 };
1290
1291 static int
1292 TcOK (int n)
1293 {
1294     char *tc;
1295     if(tcType == 0 && tmpMoves <= 0) return 0;
1296     if(tcType == 2 && tmpInc <= 0) return 0;
1297     GetWidgetText(&tcOptions[4], &tc); // get original text, in case it is min:sec
1298     searchTime = 0;
1299     switch(tcType) {
1300       case 0:
1301         if(!ParseTimeControl(tc, -1, tmpMoves)) return 0;
1302         appData.movesPerSession = tmpMoves;
1303         ASSIGN(appData.timeControl, tc);
1304         appData.timeIncrement = -1;
1305         break;
1306       case 1:
1307         if(!ParseTimeControl(tc, tmpInc, 0)) return 0;
1308         ASSIGN(appData.timeControl, tc);
1309         appData.timeIncrement = tmpInc;
1310         break;
1311       case 2:
1312         searchTime = tmpInc;
1313     }
1314     appData.firstTimeOdds = first.timeOdds = tmpOdds1;
1315     appData.secondTimeOdds = second.timeOdds = tmpOdds2;
1316     Reset(True, True);
1317     return 1;
1318 }
1319
1320 static void
1321 SetTcType (int n)
1322 {
1323     switch(tcType = n) {
1324       case 0:
1325         SetWidgetText(&tcOptions[3], Value(tmpMoves), TransientDlg);
1326         SetWidgetText(&tcOptions[4], Value(tmpTc), TransientDlg);
1327         SetWidgetText(&tcOptions[5], _("Unused"), TransientDlg);
1328         break;
1329       case 1:
1330         SetWidgetText(&tcOptions[3], _("Unused"), TransientDlg);
1331         SetWidgetText(&tcOptions[4], Value(tmpTc), TransientDlg);
1332         SetWidgetText(&tcOptions[5], Value(tmpInc), TransientDlg);
1333         break;
1334       case 2:
1335         SetWidgetText(&tcOptions[3], _("Unused"), TransientDlg);
1336         SetWidgetText(&tcOptions[4], _("Unused"), TransientDlg);
1337         SetWidgetText(&tcOptions[5], Value(tmpInc), TransientDlg);
1338     }
1339 }
1340
1341 void
1342 TimeControlProc ()
1343 {
1344    tmpMoves = appData.movesPerSession;
1345    tmpInc = appData.timeIncrement; if(tmpInc < 0) tmpInc = 0;
1346    tmpOdds1 = tmpOdds2 = 1; tcType = 0;
1347    tmpTc = atoi(appData.timeControl);
1348    GenericPopUp(tcOptions, _("Time Control"), TransientDlg, BoardWindow, MODAL, 0);
1349 }
1350
1351 //------------------------------- Ask Question -----------------------------------------
1352
1353 int SendReply P((int n));
1354 char pendingReplyPrefix[MSG_SIZ];
1355 ProcRef pendingReplyPR;
1356 char *answer;
1357
1358 Option askOptions[] = {
1359 { 0, 0, 0, NULL, NULL, NULL, NULL, Label,  NULL },
1360 { 0, 0, 0, NULL, (void*) &answer, "", NULL, TextBox, "" },
1361 { 0, 0, 0, NULL, (void*) &SendReply, "", NULL, EndMark , "" }
1362 };
1363
1364 int
1365 SendReply (int n)
1366 {
1367     char buf[MSG_SIZ];
1368     int err;
1369     char *reply=answer;
1370 //    GetWidgetText(&askOptions[1], &reply);
1371     safeStrCpy(buf, pendingReplyPrefix, sizeof(buf)/sizeof(buf[0]) );
1372     if (*buf) strncat(buf, " ", MSG_SIZ - strlen(buf) - 1);
1373     strncat(buf, reply, MSG_SIZ - strlen(buf) - 1);
1374     strncat(buf, "\n",  MSG_SIZ - strlen(buf) - 1);
1375     OutputToProcess(pendingReplyPR, buf, strlen(buf), &err); // does not go into debug file??? => bug
1376     if (err) DisplayFatalError(_("Error writing to chess program"), err, 0);
1377     return TRUE;
1378 }
1379
1380 void
1381 AskQuestion (char *title, char *question, char *replyPrefix, ProcRef pr)
1382 {
1383     safeStrCpy(pendingReplyPrefix, replyPrefix, sizeof(pendingReplyPrefix)/sizeof(pendingReplyPrefix[0]) );
1384     pendingReplyPR = pr;
1385     ASSIGN(answer, "");
1386     askOptions[0].name = question;
1387     if(GenericPopUp(askOptions, title, AskDlg, BoardWindow, MODAL, 0))
1388         AddHandler(&askOptions[1], 2);
1389 }
1390
1391 //---------------------------- Promotion Popup --------------------------------------
1392
1393 static int count;
1394
1395 static void PromoPick P((int n));
1396
1397 static Option promoOptions[] = {
1398 {   0,         0,    0, NULL, (void*) &PromoPick, NULL, NULL, Button, "" },
1399 {   0,  SAME_ROW,    0, NULL, (void*) &PromoPick, NULL, NULL, Button, "" },
1400 {   0,  SAME_ROW,    0, NULL, (void*) &PromoPick, NULL, NULL, Button, "" },
1401 {   0,  SAME_ROW,    0, NULL, (void*) &PromoPick, NULL, NULL, Button, "" },
1402 {   0,  SAME_ROW,    0, NULL, (void*) &PromoPick, NULL, NULL, Button, "" },
1403 {   0,  SAME_ROW,    0, NULL, (void*) &PromoPick, NULL, NULL, Button, "" },
1404 {   0,  SAME_ROW,    0, NULL, (void*) &PromoPick, NULL, NULL, Button, "" },
1405 {   0, SAME_ROW | NO_OK, 0, NULL, NULL, "", NULL, EndMark , "" }
1406 };
1407
1408 static void
1409 PromoPick (int n)
1410 {
1411     int promoChar = promoOptions[n+count].value;
1412
1413     PopDown(PromoDlg);
1414
1415     if (promoChar == 0) fromX = -1;
1416     if (fromX == -1) return;
1417
1418     if (! promoChar) {
1419         fromX = fromY = -1;
1420         ClearHighlights();
1421         return;
1422     }
1423     UserMoveEvent(fromX, fromY, toX, toY, promoChar);
1424
1425     if (!appData.highlightLastMove || gotPremove) ClearHighlights();
1426     if (gotPremove) SetPremoveHighlights(fromX, fromY, toX, toY);
1427     fromX = fromY = -1;
1428 }
1429
1430 static void
1431 SetPromo (char *name, int nr, char promoChar)
1432 {
1433     safeStrCpy(promoOptions[nr].name, name, MSG_SIZ);
1434     promoOptions[nr].value = promoChar;
1435 }
1436
1437 void
1438 PromotionPopUp ()
1439 { // choice depends on variant: prepare dialog acordingly
1440   count = 7;
1441   SetPromo(_("Cancel"), --count, 0); // Beware: GenericPopUp cannot handle user buttons named "cancel" (lowe case)!
1442   if(gameInfo.variant != VariantShogi) {
1443     if (!appData.testLegality || gameInfo.variant == VariantSuicide ||
1444         gameInfo.variant == VariantSpartan && !WhiteOnMove(currentMove) ||
1445         gameInfo.variant == VariantGiveaway) {
1446       SetPromo(_("King"), --count, 'k');
1447     }
1448     if(gameInfo.variant == VariantSpartan && !WhiteOnMove(currentMove)) {
1449       SetPromo(_("Captain"), --count, 'c');
1450       SetPromo(_("Lieutenant"), --count, 'l');
1451       SetPromo(_("General"), --count, 'g');
1452       SetPromo(_("Warlord"), --count, 'w');
1453     } else {
1454       SetPromo(_("Knight"), --count, 'n');
1455       SetPromo(_("Bishop"), --count, 'b');
1456       SetPromo(_("Rook"), --count, 'r');
1457       if(gameInfo.variant == VariantCapablanca ||
1458          gameInfo.variant == VariantGothic ||
1459          gameInfo.variant == VariantCapaRandom) {
1460         SetPromo(_("Archbishop"), --count, 'a');
1461         SetPromo(_("Chancellor"), --count, 'c');
1462       }
1463       SetPromo(_("Queen"), --count, 'q');
1464     }
1465   } else // [HGM] shogi
1466   {
1467       SetPromo(_("Defer"), --count, '=');
1468       SetPromo(_("Promote"), --count, '+');
1469   }
1470   GenericPopUp(promoOptions + count, "Promotion", PromoDlg, BoardWindow, NONMODAL, 0);
1471 }
1472
1473 //---------------------------- Chat Windows ----------------------------------------------
1474
1475 void
1476 OutputChatMessage (int partner, char *mess)
1477 {
1478     return; // dummy
1479 }
1480
1481 //--------------------------------- Game-List options dialog ------------------------------------------
1482
1483 char *strings[LPUSERGLT_SIZE];
1484 int stringPtr;
1485
1486 void
1487 GLT_ClearList ()
1488 {
1489     strings[0] = NULL;
1490     stringPtr = 0;
1491 }
1492
1493 void
1494 GLT_AddToList (char *name)
1495 {
1496     strings[stringPtr++] = name;
1497     strings[stringPtr] = NULL;
1498 }
1499
1500 Boolean
1501 GLT_GetFromList (int index, char *name)
1502 {
1503   safeStrCpy(name, strings[index], MSG_SIZ);
1504   return TRUE;
1505 }
1506
1507 void
1508 GLT_DeSelectList ()
1509 {
1510 }
1511
1512 static void GLT_Button P((int n));
1513 static int GLT_OK P((int n));
1514
1515 static Option listOptions[] = {
1516 { 0, LR|TB,  200, NULL, (void*) strings, "", NULL, ListBox, "" },
1517 { 0,    0,     0, NULL, (void*) &GLT_Button, NULL, NULL, Button, N_("factory") },
1518 { 0, SAME_ROW, 0, NULL, (void*) &GLT_Button, NULL, NULL, Button, N_("up") },
1519 { 0, SAME_ROW, 0, NULL, (void*) &GLT_Button, NULL, NULL, Button, N_("down") },
1520 { 0, SAME_ROW, 0, NULL, (void*) &GLT_OK, "", NULL, EndMark , "" }
1521 };
1522
1523 static int
1524 GLT_OK (int n)
1525 {
1526     GLT_ParseList();
1527     appData.gameListTags = strdup(lpUserGLT);
1528     return 1;
1529 }
1530
1531 static void
1532 GLT_Button (int n)
1533 {
1534     int index = SelectedListBoxItem (&listOptions[0]);
1535     char *p;
1536     if (index < 0) {
1537         DisplayError(_("No tag selected"), 0);
1538         return;
1539     }
1540     p = strings[index];
1541     if (n == 3) {
1542         if(index >= strlen(GLT_ALL_TAGS)) return;
1543         strings[index] = strings[index+1];
1544         strings[++index] = p;
1545     } else
1546     if (n == 2) {
1547         if(index == 0) return;
1548         strings[index] = strings[index-1];
1549         strings[--index] = p;
1550     } else
1551     if (n == 1) {
1552       safeStrCpy(lpUserGLT, GLT_DEFAULT_TAGS, LPUSERGLT_SIZE);
1553       GLT_TagsToList(lpUserGLT);
1554       index = 0;
1555       LoadListBox(&listOptions[0], "?"); // Note: the others don't need this, as the highlight switching redraws the change items
1556     }
1557     HighlightListBoxItem(&listOptions[0], index);
1558 }
1559
1560 void
1561 GameListOptionsPopUp (DialogClass parent)
1562 {
1563     safeStrCpy(lpUserGLT, appData.gameListTags, LPUSERGLT_SIZE);
1564     GLT_TagsToList(lpUserGLT);
1565
1566     GenericPopUp(listOptions, _("Game-list options"), TransientDlg, parent, MODAL, 0);
1567 }
1568
1569 void
1570 GameListOptionsProc ()
1571 {
1572     GameListOptionsPopUp(BoardWindow);
1573 }
1574
1575 //----------------------------- Error popup in various uses -----------------------------
1576
1577 /*
1578  * [HGM] Note:
1579  * XBoard has always had some pathologic behavior with multiple simultaneous error popups,
1580  * (which can occur even for modal popups when asynchrounous events, e.g. caused by engine, request a popup),
1581  * and this new implementation reproduces that as well:
1582  * Only the shell of the last instance is remembered in shells[ErrorDlg] (which replaces errorShell),
1583  * so that PopDowns ordered from the code always refer to that instance, and once that is down,
1584  * have no clue as to how to reach the others. For the Delete Window button calling PopDown this
1585  * has now been repaired, as the action routine assigned to it gets the shell passed as argument.
1586  */
1587
1588 int errorUp = False;
1589
1590 void
1591 ErrorPopDown ()
1592 {
1593     if (!errorUp) return;
1594     dialogError = errorUp = False;
1595     PopDown(ErrorDlg); PopDown(FatalDlg); // on explicit request we pop down any error dialog
1596     if (errorExitStatus != -1) ExitEvent(errorExitStatus);
1597 }
1598
1599 static int
1600 ErrorOK (int n)
1601 {
1602     dialogError = errorUp = False;
1603     PopDown(n == 1 ? FatalDlg : ErrorDlg); // kludge: non-modal dialogs have one less (dummy) option
1604     if (errorExitStatus != -1) ExitEvent(errorExitStatus);
1605     return FALSE; // prevent second Popdown !
1606 }
1607
1608 static Option errorOptions[] = {
1609 {   0,  0,    0, NULL, NULL, NULL, NULL, Label,  NULL }, // dummy option: will never be displayed
1610 {   0,  0,    0, NULL, NULL, NULL, NULL, Label,  NULL }, // textValue field will be set before popup
1611 { 0,NO_CANCEL,0, NULL, (void*) &ErrorOK, "", NULL, EndMark , "" }
1612 };
1613
1614 void
1615 ErrorPopUp (char *title, char *label, int modal)
1616 {
1617     errorUp = True;
1618     errorOptions[1].name = label;
1619     if(dialogError = shellUp[TransientDlg]) 
1620         GenericPopUp(errorOptions+1, title, FatalDlg, TransientDlg, MODAL, 0); // pop up as daughter of the transient dialog
1621     else
1622         GenericPopUp(errorOptions+modal, title, modal ? FatalDlg: ErrorDlg, BoardWindow, modal, 0); // kludge: option start address indicates modality
1623 }
1624
1625 void
1626 DisplayError (String message, int error)
1627 {
1628     char buf[MSG_SIZ];
1629
1630     if (error == 0) {
1631         if (appData.debugMode || appData.matchMode) {
1632             fprintf(stderr, "%s: %s\n", programName, message);
1633         }
1634     } else {
1635         if (appData.debugMode || appData.matchMode) {
1636             fprintf(stderr, "%s: %s: %s\n",
1637                     programName, message, strerror(error));
1638         }
1639         snprintf(buf, sizeof(buf), "%s: %s", message, strerror(error));
1640         message = buf;
1641     }
1642     ErrorPopUp(_("Error"), message, FALSE);
1643 }
1644
1645
1646 void
1647 DisplayMoveError (String message)
1648 {
1649     fromX = fromY = -1;
1650     ClearHighlights();
1651     DrawPosition(FALSE, NULL);
1652     if (appData.debugMode || appData.matchMode) {
1653         fprintf(stderr, "%s: %s\n", programName, message);
1654     }
1655     if (appData.popupMoveErrors) {
1656         ErrorPopUp(_("Error"), message, FALSE);
1657     } else {
1658         DisplayMessage(message, "");
1659     }
1660 }
1661
1662
1663 void
1664 DisplayFatalError (String message, int error, int status)
1665 {
1666     char buf[MSG_SIZ];
1667
1668     errorExitStatus = status;
1669     if (error == 0) {
1670         fprintf(stderr, "%s: %s\n", programName, message);
1671     } else {
1672         fprintf(stderr, "%s: %s: %s\n",
1673                 programName, message, strerror(error));
1674         snprintf(buf, sizeof(buf), "%s: %s", message, strerror(error));
1675         message = buf;
1676     }
1677     if (appData.popupExitMessage && boardWidget && XtIsRealized(boardWidget)) {
1678       ErrorPopUp(status ? _("Fatal Error") : _("Exiting"), message, TRUE);
1679     } else {
1680       ExitEvent(status);
1681     }
1682 }
1683
1684 void
1685 DisplayInformation (String message)
1686 {
1687     ErrorPopDown();
1688     ErrorPopUp(_("Information"), message, TRUE);
1689 }
1690
1691 void
1692 DisplayNote (String message)
1693 {
1694     ErrorPopDown();
1695     ErrorPopUp(_("Note"), message, FALSE);
1696 }
1697
1698 void
1699 DisplayTitle (char *text)
1700 {
1701     char title[MSG_SIZ];
1702     char icon[MSG_SIZ];
1703
1704     if (text == NULL) text = "";
1705
1706     if (*text != NULLCHAR) {
1707       safeStrCpy(icon, text, sizeof(icon)/sizeof(icon[0]) );
1708       safeStrCpy(title, text, sizeof(title)/sizeof(title[0]) );
1709     } else if (appData.icsActive) {
1710         snprintf(icon, sizeof(icon), "%s", appData.icsHost);
1711         snprintf(title, sizeof(title), "%s: %s", programName, appData.icsHost);
1712     } else if (appData.cmailGameName[0] != NULLCHAR) {
1713         snprintf(icon, sizeof(icon), "%s", "CMail");
1714         snprintf(title,sizeof(title), "%s: %s", programName, "CMail");
1715 #ifdef GOTHIC
1716     // [HGM] license: This stuff should really be done in back-end, but WinBoard already had a pop-up for it
1717     } else if (gameInfo.variant == VariantGothic) {
1718       safeStrCpy(icon,  programName, sizeof(icon)/sizeof(icon[0]) );
1719       safeStrCpy(title, GOTHIC,     sizeof(title)/sizeof(title[0]) );
1720 #endif
1721 #ifdef FALCON
1722     } else if (gameInfo.variant == VariantFalcon) {
1723       safeStrCpy(icon, programName, sizeof(icon)/sizeof(icon[0]) );
1724       safeStrCpy(title, FALCON, sizeof(title)/sizeof(title[0]) );
1725 #endif
1726     } else if (appData.noChessProgram) {
1727       safeStrCpy(icon, programName, sizeof(icon)/sizeof(icon[0]) );
1728       safeStrCpy(title, programName, sizeof(title)/sizeof(title[0]) );
1729     } else {
1730       safeStrCpy(icon, first.tidy, sizeof(icon)/sizeof(icon[0]) );
1731         snprintf(title,sizeof(title), "%s: %s", programName, first.tidy);
1732     }
1733     SetWindowTitle(text, title, icon);
1734 }
1735
1736