2 * backend.c -- Common back end for X and Windows NT versions of
5 * Copyright 1991 by Digital Equipment Corporation, Maynard, Massachusetts.
6 * Enhancements Copyright 1992-2001 Free Software Foundation, Inc.
8 * The following terms apply to Digital Equipment Corporation's copyright
10 * ------------------------------------------------------------------------
13 * Permission to use, copy, modify, and distribute this software and its
14 * documentation for any purpose and without fee is hereby granted,
15 * provided that the above copyright notice appear in all copies and that
16 * both that copyright notice and this permission notice appear in
17 * supporting documentation, and that the name of Digital not be
18 * used in advertising or publicity pertaining to distribution of the
19 * software without specific, written prior permission.
21 * DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
22 * ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
23 * DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
24 * ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
25 * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
26 * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
28 * ------------------------------------------------------------------------
30 * The following terms apply to the enhanced version of XBoard distributed
31 * by the Free Software Foundation:
32 * ------------------------------------------------------------------------
33 * This program is free software; you can redistribute it and/or modify
34 * it under the terms of the GNU General Public License as published by
35 * the Free Software Foundation; either version 2 of the License, or
36 * (at your option) any later version.
38 * This program is distributed in the hope that it will be useful,
39 * but WITHOUT ANY WARRANTY; without even the implied warranty of
40 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
41 * GNU General Public License for more details.
43 * You should have received a copy of the GNU General Public License
44 * along with this program; if not, write to the Free Software
45 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
46 * ------------------------------------------------------------------------
48 * See the file ChangeLog for a revision history. */
55 #include <sys/types.h>
62 #else /* not STDC_HEADERS */
65 # else /* not HAVE_STRING_H */
67 # endif /* not HAVE_STRING_H */
68 #endif /* not STDC_HEADERS */
71 # include <sys/fcntl.h>
72 #else /* not HAVE_SYS_FCNTL_H */
75 # endif /* HAVE_FCNTL_H */
76 #endif /* not HAVE_SYS_FCNTL_H */
78 #if TIME_WITH_SYS_TIME
79 # include <sys/time.h>
83 # include <sys/time.h>
89 #if defined(_amigados) && !defined(__GNUC__)
94 extern int gettimeofday(struct timeval *, struct timezone *);
102 #include "frontend.h"
109 #include "backendz.h"
113 # define _(s) gettext (s)
114 # define N_(s) gettext_noop (s)
121 /* A point in time */
123 long sec; /* Assuming this is >= 32 bits */
124 int ms; /* Assuming this is >= 16 bits */
127 /* Search stats from chessprogram */
129 char movelist[2*MSG_SIZ]; /* Last PV we were sent */
130 int depth; /* Current search depth */
131 int nr_moves; /* Total nr of root moves */
132 int moves_left; /* Moves remaining to be searched */
133 char move_name[MOVE_LEN]; /* Current move being searched, if provided */
134 u64 nodes; /* # of nodes searched */
135 int time; /* Search time (centiseconds) */
136 int score; /* Score (centipawns) */
137 int got_only_move; /* If last msg was "(only move)" */
138 int got_fail; /* 0 - nothing, 1 - got "--", 2 - got "++" */
139 int ok_to_send; /* handshaking between send & recv */
140 int line_is_book; /* 1 if movelist is book moves */
141 int seen_stat; /* 1 if we've seen the stat01: line */
144 int establish P((void));
145 void read_from_player P((InputSourceRef isr, VOIDSTAR closure,
146 char *buf, int count, int error));
147 void read_from_ics P((InputSourceRef isr, VOIDSTAR closure,
148 char *buf, int count, int error));
149 void SendToICS P((char *s));
150 void SendToICSDelayed P((char *s, long msdelay));
151 void SendMoveToICS P((ChessMove moveType, int fromX, int fromY,
153 void InitPosition P((int redraw));
154 void HandleMachineMove P((char *message, ChessProgramState *cps));
155 int AutoPlayOneMove P((void));
156 int LoadGameOneMove P((ChessMove readAhead));
157 int LoadGameFromFile P((char *filename, int n, char *title, int useList));
158 int LoadPositionFromFile P((char *filename, int n, char *title));
159 int SavePositionToFile P((char *filename));
160 void ApplyMove P((int fromX, int fromY, int toX, int toY, int promoChar,
162 void MakeMove P((int fromX, int fromY, int toX, int toY, int promoChar));
163 void ShowMove P((int fromX, int fromY, int toX, int toY));
164 void FinishMove P((ChessMove moveType, int fromX, int fromY, int toX, int toY,
165 /*char*/int promoChar));
166 void BackwardInner P((int target));
167 void ForwardInner P((int target));
168 void GameEnds P((ChessMove result, char *resultDetails, int whosays));
169 void EditPositionDone P((void));
170 void PrintOpponents P((FILE *fp));
171 void PrintPosition P((FILE *fp, int move));
172 void StartChessProgram P((ChessProgramState *cps));
173 void SendToProgram P((char *message, ChessProgramState *cps));
174 void SendMoveToProgram P((int moveNum, ChessProgramState *cps));
175 void ReceiveFromProgram P((InputSourceRef isr, VOIDSTAR closure,
176 char *buf, int count, int error));
177 void SendTimeControl P((ChessProgramState *cps,
178 int mps, long tc, int inc, int sd, int st));
179 char *TimeControlTagValue P((void));
180 void Attention P((ChessProgramState *cps));
181 void FeedMovesToProgram P((ChessProgramState *cps, int upto));
182 void ResurrectChessProgram P((void));
183 void DisplayComment P((int moveNumber, char *text));
184 void DisplayMove P((int moveNumber));
185 void DisplayAnalysis P((void));
187 void ParseGameHistory P((char *game));
188 void ParseBoard12 P((char *string));
189 void StartClocks P((void));
190 void SwitchClocks P((void));
191 void StopClocks P((void));
192 void ResetClocks P((void));
193 char *PGNDate P((void));
194 void SetGameInfo P((void));
195 Boolean ParseFEN P((Board board, int *blackPlaysFirst, char *fen));
196 int RegisterMove P((void));
197 void MakeRegisteredMove P((void));
198 void TruncateGame P((void));
199 int looking_at P((char *, int *, char *));
200 void CopyPlayerNameIntoFileName P((char **, char *));
201 char *SavePart P((char *));
202 int SaveGameOldStyle P((FILE *));
203 int SaveGamePGN P((FILE *));
204 void GetTimeMark P((TimeMark *));
205 long SubtractTimeMarks P((TimeMark *, TimeMark *));
206 int CheckFlags P((void));
207 long NextTickLength P((long));
208 void CheckTimeControl P((void));
209 void show_bytes P((FILE *, char *, int));
210 int string_to_rating P((char *str));
211 void ParseFeatures P((char* args, ChessProgramState *cps));
212 void InitBackEnd3 P((void));
213 void FeatureDone P((ChessProgramState* cps, int val));
214 void InitChessProgram P((ChessProgramState *cps));
215 double u64ToDouble P((u64 value));
218 extern void ConsoleCreate();
221 extern int tinyLayout, smallLayout;
222 static ChessProgramStats programStats;
224 /* States for ics_getting_history */
226 #define H_REQUESTED 1
227 #define H_GOT_REQ_HEADER 2
228 #define H_GOT_UNREQ_HEADER 3
229 #define H_GETTING_MOVES 4
230 #define H_GOT_UNWANTED_HEADER 5
232 /* whosays values for GameEnds */
239 /* Maximum number of games in a cmail message */
240 #define CMAIL_MAX_GAMES 20
242 /* Different types of move when calling RegisterMove */
244 #define CMAIL_RESIGN 1
246 #define CMAIL_ACCEPT 3
248 /* Different types of result to remember for each game */
249 #define CMAIL_NOT_RESULT 0
250 #define CMAIL_OLD_RESULT 1
251 #define CMAIL_NEW_RESULT 2
253 /* Telnet protocol constants */
263 /* Some compiler can't cast u64 to double
264 * This function do the job for us:
266 * We use the highest bit for cast, this only
267 * works if the highest bit is not
268 * in use (This should not happen)
270 * We used this for all compiler
273 u64ToDouble(u64 value)
276 u64 tmp = value & 0x7fffffffffffffff;
277 r = (double)(s64)tmp;
278 if (value & 0x8000000000000000)
279 r += 9.2233720368547758080e18; /* 2^63 */
283 /* Fake up flags for now, as we aren't keeping track of castling
288 int flags = F_ALL_CASTLE_OK;
289 if ((index % 2) == 0) flags |= F_WHITE_ON_MOVE;
290 switch (gameInfo.variant) {
292 case VariantGiveaway:
293 flags |= F_IGNORE_CHECK;
294 flags &= ~F_ALL_CASTLE_OK;
297 flags |= F_IGNORE_CHECK | F_ATOMIC_CAPTURE;
299 case VariantKriegspiel:
300 flags |= F_KRIEGSPIEL_CAPTURE;
302 case VariantNoCastle:
303 flags &= ~F_ALL_CASTLE_OK;
311 FILE *gameFileFP, *debugFP;
313 char cmailMove[CMAIL_MAX_GAMES][MOVE_LEN], cmailMsg[MSG_SIZ];
314 char bookOutput[MSG_SIZ*10], thinkOutput[MSG_SIZ*10], lastHint[MSG_SIZ];
315 char thinkOutput1[MSG_SIZ*10];
317 ChessProgramState first, second;
319 /* premove variables */
322 int premoveFromX = 0;
323 int premoveFromY = 0;
324 int premovePromoChar = 0;
326 Boolean alarmSounded;
327 /* end premove variables */
329 char *ics_prefix = "$";
330 int ics_type = ICS_GENERIC;
332 int currentMove = 0, forwardMostMove = 0, backwardMostMove = 0;
333 int pauseExamForwardMostMove = 0;
334 int nCmailGames = 0, nCmailResults = 0, nCmailMovesRegistered = 0;
335 int cmailMoveRegistered[CMAIL_MAX_GAMES], cmailResult[CMAIL_MAX_GAMES];
336 int cmailMsgLoaded = FALSE, cmailMailedMove = FALSE;
337 int cmailOldMove = -1, firstMove = TRUE, flipView = FALSE;
338 int blackPlaysFirst = FALSE, startedFromSetupPosition = FALSE;
339 int searchTime = 0, pausing = FALSE, pauseExamInvalid = FALSE;
340 int whiteFlag = FALSE, blackFlag = FALSE;
341 int userOfferedDraw = FALSE;
342 int ics_user_moved = 0, ics_gamenum = -1, ics_getting_history = H_FALSE;
343 int matchMode = FALSE, hintRequested = FALSE, bookRequested = FALSE;
344 int cmailMoveType[CMAIL_MAX_GAMES];
345 long ics_clock_paused = 0;
346 ProcRef icsPR = NoProc, cmailPR = NoProc;
347 InputSourceRef telnetISR = NULL, fromUserISR = NULL, cmailISR = NULL;
348 GameMode gameMode = BeginningOfGame;
349 char moveList[MAX_MOVES][MOVE_LEN], parseList[MAX_MOVES][MOVE_LEN * 2];
350 char *commentList[MAX_MOVES], *cmailCommentList[CMAIL_MAX_GAMES];
351 char white_holding[64], black_holding[64];
352 TimeMark lastNodeCountTime;
353 long lastNodeCount=0;
354 int have_sent_ICS_logon = 0;
356 long whiteTimeRemaining, blackTimeRemaining, timeControl, timeIncrement;
357 long timeRemaining[2][MAX_MOVES];
359 TimeMark programStartTime;
360 char ics_handle[MSG_SIZ];
361 int have_set_title = 0;
363 /* animateTraining preserves the state of appData.animate
364 * when Training mode is activated. This allows the
365 * response to be animated when appData.animate == TRUE and
366 * appData.animateDragging == TRUE.
368 Boolean animateTraining;
374 Board boards[MAX_MOVES];
375 Board initialPosition = {
376 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
377 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
378 { WhitePawn, WhitePawn, WhitePawn, WhitePawn,
379 WhitePawn, WhitePawn, WhitePawn, WhitePawn },
380 { EmptySquare, EmptySquare, EmptySquare, EmptySquare,
381 EmptySquare, EmptySquare, EmptySquare, EmptySquare },
382 { EmptySquare, EmptySquare, EmptySquare, EmptySquare,
383 EmptySquare, EmptySquare, EmptySquare, EmptySquare },
384 { EmptySquare, EmptySquare, EmptySquare, EmptySquare,
385 EmptySquare, EmptySquare, EmptySquare, EmptySquare },
386 { EmptySquare, EmptySquare, EmptySquare, EmptySquare,
387 EmptySquare, EmptySquare, EmptySquare, EmptySquare },
388 { BlackPawn, BlackPawn, BlackPawn, BlackPawn,
389 BlackPawn, BlackPawn, BlackPawn, BlackPawn },
390 { BlackRook, BlackKnight, BlackBishop, BlackQueen,
391 BlackKing, BlackBishop, BlackKnight, BlackRook }
393 Board twoKingsPosition = {
394 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
395 WhiteKing, WhiteKing, WhiteKnight, WhiteRook },
396 { WhitePawn, WhitePawn, WhitePawn, WhitePawn,
397 WhitePawn, WhitePawn, WhitePawn, WhitePawn },
398 { EmptySquare, EmptySquare, EmptySquare, EmptySquare,
399 EmptySquare, EmptySquare, EmptySquare, EmptySquare },
400 { EmptySquare, EmptySquare, EmptySquare, EmptySquare,
401 EmptySquare, EmptySquare, EmptySquare, EmptySquare },
402 { EmptySquare, EmptySquare, EmptySquare, EmptySquare,
403 EmptySquare, EmptySquare, EmptySquare, EmptySquare },
404 { EmptySquare, EmptySquare, EmptySquare, EmptySquare,
405 EmptySquare, EmptySquare, EmptySquare, EmptySquare },
406 { BlackPawn, BlackPawn, BlackPawn, BlackPawn,
407 BlackPawn, BlackPawn, BlackPawn, BlackPawn },
408 { BlackRook, BlackKnight, BlackBishop, BlackQueen,
409 BlackKing, BlackKing, BlackKnight, BlackRook }
413 /* Convert str to a rating. Checks for special cases of "----",
414 "++++", etc. Also strips ()'s */
416 string_to_rating(str)
419 while(*str && !isdigit(*str)) ++str;
421 return 0; /* One of the special "no rating" cases */
429 /* Init programStats */
430 programStats.movelist[0] = 0;
431 programStats.depth = 0;
432 programStats.nr_moves = 0;
433 programStats.moves_left = 0;
434 programStats.nodes = 0;
435 programStats.time = 100;
436 programStats.score = 0;
437 programStats.got_only_move = 0;
438 programStats.got_fail = 0;
439 programStats.line_is_book = 0;
445 int matched, min, sec;
447 GetTimeMark(&programStartTime);
450 programStats.ok_to_send = 1;
451 programStats.seen_stat = 0;
454 * Initialize game list
460 * Internet chess server status
462 if (appData.icsActive) {
463 appData.matchMode = FALSE;
464 appData.matchGames = 0;
466 appData.noChessProgram = !appData.zippyPlay;
468 appData.zippyPlay = FALSE;
469 appData.zippyTalk = FALSE;
470 appData.noChessProgram = TRUE;
472 if (*appData.icsHelper != NULLCHAR) {
473 appData.useTelnet = TRUE;
474 appData.telnetProgram = appData.icsHelper;
477 appData.zippyTalk = appData.zippyPlay = FALSE;
481 * Parse timeControl resource
483 if (!ParseTimeControl(appData.timeControl, appData.timeIncrement,
484 appData.movesPerSession)) {
486 sprintf(buf, _("bad timeControl option %s"), appData.timeControl);
487 DisplayFatalError(buf, 0, 2);
491 * Parse searchTime resource
493 if (*appData.searchTime != NULLCHAR) {
494 matched = sscanf(appData.searchTime, "%d:%d", &min, &sec);
496 searchTime = min * 60;
497 } else if (matched == 2) {
498 searchTime = min * 60 + sec;
501 sprintf(buf, _("bad searchTime option %s"), appData.searchTime);
502 DisplayFatalError(buf, 0, 2);
506 first.which = "first";
507 second.which = "second";
508 first.maybeThinking = second.maybeThinking = FALSE;
509 first.pr = second.pr = NoProc;
510 first.isr = second.isr = NULL;
511 first.sendTime = second.sendTime = 2;
512 first.sendDrawOffers = 1;
513 if (appData.firstPlaysBlack) {
514 first.twoMachinesColor = "black\n";
515 second.twoMachinesColor = "white\n";
517 first.twoMachinesColor = "white\n";
518 second.twoMachinesColor = "black\n";
520 first.program = appData.firstChessProgram;
521 second.program = appData.secondChessProgram;
522 first.host = appData.firstHost;
523 second.host = appData.secondHost;
524 first.dir = appData.firstDirectory;
525 second.dir = appData.secondDirectory;
526 first.other = &second;
527 second.other = &first;
528 first.initString = appData.initString;
529 second.initString = appData.secondInitString;
530 first.computerString = appData.firstComputerString;
531 second.computerString = appData.secondComputerString;
532 first.useSigint = second.useSigint = TRUE;
533 first.useSigterm = second.useSigterm = TRUE;
534 first.reuse = appData.reuseFirst;
535 second.reuse = appData.reuseSecond;
536 first.useSetboard = second.useSetboard = FALSE;
537 first.useSAN = second.useSAN = FALSE;
538 first.usePing = second.usePing = FALSE;
539 first.lastPing = second.lastPing = 0;
540 first.lastPong = second.lastPong = 0;
541 first.usePlayother = second.usePlayother = FALSE;
542 first.useColors = second.useColors = TRUE;
543 first.useUsermove = second.useUsermove = FALSE;
544 first.sendICS = second.sendICS = FALSE;
545 first.sendName = second.sendName = appData.icsActive;
546 first.sdKludge = second.sdKludge = FALSE;
547 first.stKludge = second.stKludge = FALSE;
548 TidyProgramName(first.program, first.host, first.tidy);
549 TidyProgramName(second.program, second.host, second.tidy);
550 first.matchWins = second.matchWins = 0;
551 strcpy(first.variants, appData.variant);
552 strcpy(second.variants, appData.variant);
553 first.analysisSupport = second.analysisSupport = 2; /* detect */
554 first.analyzing = second.analyzing = FALSE;
555 first.initDone = second.initDone = FALSE;
557 if (appData.firstProtocolVersion > PROTOVER ||
558 appData.firstProtocolVersion < 1) {
560 sprintf(buf, _("protocol version %d not supported"),
561 appData.firstProtocolVersion);
562 DisplayFatalError(buf, 0, 2);
564 first.protocolVersion = appData.firstProtocolVersion;
567 if (appData.secondProtocolVersion > PROTOVER ||
568 appData.secondProtocolVersion < 1) {
570 sprintf(buf, _("protocol version %d not supported"),
571 appData.secondProtocolVersion);
572 DisplayFatalError(buf, 0, 2);
574 second.protocolVersion = appData.secondProtocolVersion;
577 if (appData.icsActive) {
578 appData.clockMode = TRUE; /* changes dynamically in ICS mode */
579 } else if (*appData.searchTime != NULLCHAR || appData.noChessProgram) {
580 appData.clockMode = FALSE;
581 first.sendTime = second.sendTime = 0;
585 /* Override some settings from environment variables, for backward
586 compatibility. Unfortunately it's not feasible to have the env
587 vars just set defaults, at least in xboard. Ugh.
589 if (appData.icsActive && (appData.zippyPlay || appData.zippyTalk)) {
594 if (appData.noChessProgram) {
595 programVersion = (char*) malloc(5 + strlen(PRODUCT) + strlen(VERSION)
596 + strlen(PATCHLEVEL));
597 sprintf(programVersion, "%s %s.%s", PRODUCT, VERSION, PATCHLEVEL);
601 while (*q != ' ' && *q != NULLCHAR) q++;
603 while (p > first.program && *(p-1) != '/') p--;
604 programVersion = (char*) malloc(8 + strlen(PRODUCT) + strlen(VERSION)
605 + strlen(PATCHLEVEL) + (q - p));
606 sprintf(programVersion, "%s %s.%s + ", PRODUCT, VERSION, PATCHLEVEL);
607 strncat(programVersion, p, q - p);
610 if (!appData.icsActive) {
612 /* Check for variants that are supported only in ICS mode,
613 or not at all. Some that are accepted here nevertheless
614 have bugs; see comments below.
616 VariantClass variant = StringToVariant(appData.variant);
618 case VariantBughouse: /* need four players and two boards */
619 case VariantKriegspiel: /* need to hide pieces and move details */
620 case VariantFischeRandom: /* castling doesn't work, shuffle not done */
621 sprintf(buf, _("Variant %s supported only in ICS mode"), appData.variant);
622 DisplayFatalError(buf, 0, 2);
626 case VariantLoadable:
636 sprintf(buf, _("Unknown variant name %s"), appData.variant);
637 DisplayFatalError(buf, 0, 2);
640 case VariantNormal: /* definitely works! */
641 case VariantWildCastle: /* pieces not automatically shuffled */
642 case VariantNoCastle: /* pieces not automatically shuffled */
643 case VariantCrazyhouse: /* holdings not shown,
644 offboard interposition not understood */
645 case VariantLosers: /* should work except for win condition,
646 and doesn't know captures are mandatory */
647 case VariantSuicide: /* should work except for win condition,
648 and doesn't know captures are mandatory */
649 case VariantGiveaway: /* should work except for win condition,
650 and doesn't know captures are mandatory */
651 case VariantTwoKings: /* should work */
652 case VariantAtomic: /* should work except for win condition */
653 case Variant3Check: /* should work except for win condition */
654 case VariantShatranj: /* might work if TestLegality is off */
661 ParseTimeControl(tc, ti, mps)
666 int matched, min, sec;
668 matched = sscanf(tc, "%d:%d", &min, &sec);
670 timeControl = min * 60 * 1000;
671 } else if (matched == 2) {
672 timeControl = (min * 60 + sec) * 1000;
678 timeIncrement = ti * 1000; /* convert to ms */
682 movesPerSession = mps;
690 if (appData.debugMode) {
691 fprintf(debugFP, "%s\n", programVersion);
694 if (appData.matchGames > 0) {
695 appData.matchMode = TRUE;
696 } else if (appData.matchMode) {
697 appData.matchGames = 1;
700 if (appData.noChessProgram || first.protocolVersion == 1) {
703 /* kludge: allow timeout for initial "feature" commands */
705 DisplayMessage("", "Starting chess program");
706 ScheduleDelayedEvent(InitBackEnd3, FEATURE_TIMEOUT);
711 InitBackEnd3 P((void))
713 GameMode initialMode;
717 InitChessProgram(&first);
720 /* Make a console window if needed */
721 if (appData.icsActive) ConsoleCreate();
724 if (appData.icsActive) {
727 if (*appData.icsCommPort != NULLCHAR) {
728 sprintf(buf, _("Could not open comm port %s"),
729 appData.icsCommPort);
731 sprintf(buf, _("Could not connect to host %s, port %s"),
732 appData.icsHost, appData.icsPort);
734 DisplayFatalError(buf, err, 1);
739 AddInputSource(icsPR, FALSE, read_from_ics, &telnetISR);
741 AddInputSource(NoProc, FALSE, read_from_player, &fromUserISR);
742 } else if (appData.noChessProgram) {
748 if (*appData.cmailGameName != NULLCHAR) {
750 OpenLoopback(&cmailPR);
752 AddInputSource(cmailPR, FALSE, CmailSigHandlerCallBack, &cmailISR);
756 DisplayMessage("", "");
757 if (StrCaseCmp(appData.initialMode, "") == 0) {
758 initialMode = BeginningOfGame;
759 } else if (StrCaseCmp(appData.initialMode, "TwoMachines") == 0) {
760 initialMode = TwoMachinesPlay;
761 } else if (StrCaseCmp(appData.initialMode, "AnalyzeFile") == 0) {
762 initialMode = AnalyzeFile;
763 } else if (StrCaseCmp(appData.initialMode, "Analysis") == 0) {
764 initialMode = AnalyzeMode;
765 } else if (StrCaseCmp(appData.initialMode, "MachineWhite") == 0) {
766 initialMode = MachinePlaysWhite;
767 } else if (StrCaseCmp(appData.initialMode, "MachineBlack") == 0) {
768 initialMode = MachinePlaysBlack;
769 } else if (StrCaseCmp(appData.initialMode, "EditGame") == 0) {
770 initialMode = EditGame;
771 } else if (StrCaseCmp(appData.initialMode, "EditPosition") == 0) {
772 initialMode = EditPosition;
773 } else if (StrCaseCmp(appData.initialMode, "Training") == 0) {
774 initialMode = Training;
776 sprintf(buf, _("Unknown initialMode %s"), appData.initialMode);
777 DisplayFatalError(buf, 0, 2);
781 if (appData.matchMode) {
782 /* Set up machine vs. machine match */
783 if (appData.noChessProgram) {
784 DisplayFatalError(_("Can't have a match with no chess programs"),
790 if (*appData.loadGameFile != NULLCHAR) {
791 if (!LoadGameFromFile(appData.loadGameFile,
792 appData.loadGameIndex,
793 appData.loadGameFile, FALSE)) {
794 DisplayFatalError(_("Bad game file"), 0, 1);
797 } else if (*appData.loadPositionFile != NULLCHAR) {
798 if (!LoadPositionFromFile(appData.loadPositionFile,
799 appData.loadPositionIndex,
800 appData.loadPositionFile)) {
801 DisplayFatalError(_("Bad position file"), 0, 1);
806 } else if (*appData.cmailGameName != NULLCHAR) {
807 /* Set up cmail mode */
808 ReloadCmailMsgEvent(TRUE);
810 /* Set up other modes */
811 if (initialMode == AnalyzeFile) {
812 if (*appData.loadGameFile == NULLCHAR) {
813 DisplayFatalError(_("AnalyzeFile mode requires a game file"), 0, 1);
817 if (*appData.loadGameFile != NULLCHAR) {
818 (void) LoadGameFromFile(appData.loadGameFile,
819 appData.loadGameIndex,
820 appData.loadGameFile, TRUE);
821 } else if (*appData.loadPositionFile != NULLCHAR) {
822 (void) LoadPositionFromFile(appData.loadPositionFile,
823 appData.loadPositionIndex,
824 appData.loadPositionFile);
826 if (initialMode == AnalyzeMode) {
827 if (appData.noChessProgram) {
828 DisplayFatalError(_("Analysis mode requires a chess engine"), 0, 2);
831 if (appData.icsActive) {
832 DisplayFatalError(_("Analysis mode does not work with ICS mode"),0,2);
836 } else if (initialMode == AnalyzeFile) {
837 ShowThinkingEvent(TRUE);
839 AnalysisPeriodicEvent(1);
840 } else if (initialMode == MachinePlaysWhite) {
841 if (appData.noChessProgram) {
842 DisplayFatalError(_("MachineWhite mode requires a chess engine"),
846 if (appData.icsActive) {
847 DisplayFatalError(_("MachineWhite mode does not work with ICS mode"),
852 } else if (initialMode == MachinePlaysBlack) {
853 if (appData.noChessProgram) {
854 DisplayFatalError(_("MachineBlack mode requires a chess engine"),
858 if (appData.icsActive) {
859 DisplayFatalError(_("MachineBlack mode does not work with ICS mode"),
864 } else if (initialMode == TwoMachinesPlay) {
865 if (appData.noChessProgram) {
866 DisplayFatalError(_("TwoMachines mode requires a chess engine"),
870 if (appData.icsActive) {
871 DisplayFatalError(_("TwoMachines mode does not work with ICS mode"),
876 } else if (initialMode == EditGame) {
878 } else if (initialMode == EditPosition) {
880 } else if (initialMode == Training) {
881 if (*appData.loadGameFile == NULLCHAR) {
882 DisplayFatalError(_("Training mode requires a game file"), 0, 2);
891 * Establish will establish a contact to a remote host.port.
892 * Sets icsPR to a ProcRef for a process (or pseudo-process)
893 * used to talk to the host.
894 * Returns 0 if okay, error code if not.
901 if (*appData.icsCommPort != NULLCHAR) {
902 /* Talk to the host through a serial comm port */
903 return OpenCommPort(appData.icsCommPort, &icsPR);
905 } else if (*appData.gateway != NULLCHAR) {
906 if (*appData.remoteShell == NULLCHAR) {
907 /* Use the rcmd protocol to run telnet program on a gateway host */
908 sprintf(buf, "%s %s %s",
909 appData.telnetProgram, appData.icsHost, appData.icsPort);
910 return OpenRcmd(appData.gateway, appData.remoteUser, buf, &icsPR);
913 /* Use the rsh program to run telnet program on a gateway host */
914 if (*appData.remoteUser == NULLCHAR) {
915 sprintf(buf, "%s %s %s %s %s", appData.remoteShell,
916 appData.gateway, appData.telnetProgram,
917 appData.icsHost, appData.icsPort);
919 sprintf(buf, "%s %s -l %s %s %s %s",
920 appData.remoteShell, appData.gateway,
921 appData.remoteUser, appData.telnetProgram,
922 appData.icsHost, appData.icsPort);
924 return StartChildProcess(buf, "", &icsPR);
927 } else if (appData.useTelnet) {
928 return OpenTelnet(appData.icsHost, appData.icsPort, &icsPR);
931 /* TCP socket interface differs somewhat between
932 Unix and NT; handle details in the front end.
934 return OpenTCP(appData.icsHost, appData.icsPort, &icsPR);
939 show_bytes(fp, buf, count)
945 if (*buf < 040 || *(unsigned char *) buf > 0177) {
946 fprintf(fp, "\\%03o", *buf & 0xff);
955 /* Returns an errno value */
957 OutputMaybeTelnet(pr, message, count, outError)
963 char buf[8192], *p, *q, *buflim;
964 int left, newcount, outcount;
966 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet ||
967 *appData.gateway != NULLCHAR) {
968 if (appData.debugMode) {
969 fprintf(debugFP, ">ICS: ");
970 show_bytes(debugFP, message, count);
971 fprintf(debugFP, "\n");
973 return OutputToProcess(pr, message, count, outError);
976 buflim = &buf[sizeof(buf)-1]; /* allow 1 byte for expanding last char */
983 if (appData.debugMode) {
984 fprintf(debugFP, ">ICS: ");
985 show_bytes(debugFP, buf, newcount);
986 fprintf(debugFP, "\n");
988 outcount = OutputToProcess(pr, buf, newcount, outError);
989 if (outcount < newcount) return -1; /* to be sure */
996 } else if (((unsigned char) *p) == TN_IAC) {
997 *q++ = (char) TN_IAC;
1004 if (appData.debugMode) {
1005 fprintf(debugFP, ">ICS: ");
1006 show_bytes(debugFP, buf, newcount);
1007 fprintf(debugFP, "\n");
1009 outcount = OutputToProcess(pr, buf, newcount, outError);
1010 if (outcount < newcount) return -1; /* to be sure */
1015 read_from_player(isr, closure, message, count, error)
1022 int outError, outCount;
1023 static int gotEof = 0;
1025 /* Pass data read from player on to ICS */
1028 outCount = OutputMaybeTelnet(icsPR, message, count, &outError);
1029 if (outCount < count) {
1030 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1032 } else if (count < 0) {
1033 RemoveInputSource(isr);
1034 DisplayFatalError(_("Error reading from keyboard"), error, 1);
1035 } else if (gotEof++ > 0) {
1036 RemoveInputSource(isr);
1037 DisplayFatalError(_("Got end of file from keyboard"), 0, 0);
1045 int count, outCount, outError;
1047 if (icsPR == NULL) return;
1050 outCount = OutputMaybeTelnet(icsPR, s, count, &outError);
1051 if (outCount < count) {
1052 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1056 /* This is used for sending logon scripts to the ICS. Sending
1057 without a delay causes problems when using timestamp on ICC
1058 (at least on my machine). */
1060 SendToICSDelayed(s,msdelay)
1064 int count, outCount, outError;
1066 if (icsPR == NULL) return;
1069 if (appData.debugMode) {
1070 fprintf(debugFP, ">ICS: ");
1071 show_bytes(debugFP, s, count);
1072 fprintf(debugFP, "\n");
1074 outCount = OutputToProcessDelayed(icsPR, s, count, &outError,
1076 if (outCount < count) {
1077 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1082 /* Remove all highlighting escape sequences in s
1083 Also deletes any suffix starting with '('
1086 StripHighlightAndTitle(s)
1089 static char retbuf[MSG_SIZ];
1092 while (*s != NULLCHAR) {
1093 while (*s == '\033') {
1094 while (*s != NULLCHAR && !isalpha(*s)) s++;
1095 if (*s != NULLCHAR) s++;
1097 while (*s != NULLCHAR && *s != '\033') {
1098 if (*s == '(' || *s == '[') {
1109 /* Remove all highlighting escape sequences in s */
1114 static char retbuf[MSG_SIZ];
1117 while (*s != NULLCHAR) {
1118 while (*s == '\033') {
1119 while (*s != NULLCHAR && !isalpha(*s)) s++;
1120 if (*s != NULLCHAR) s++;
1122 while (*s != NULLCHAR && *s != '\033') {
1130 char *variantNames[] = VARIANT_NAMES;
1135 return variantNames[v];
1139 /* Identify a variant from the strings the chess servers use or the
1140 PGN Variant tag names we use. */
1147 VariantClass v = VariantNormal;
1148 int i, found = FALSE;
1153 for (i=0; i<sizeof(variantNames)/sizeof(char*); i++) {
1154 if (StrCaseStr(e, variantNames[i])) {
1155 v = (VariantClass) i;
1162 if ((StrCaseStr(e, "fischer") && StrCaseStr(e, "random"))
1163 || StrCaseStr(e, "wild/fr")) {
1164 v = VariantFischeRandom;
1165 } else if ((i = 4, p = StrCaseStr(e, "wild")) ||
1166 (i = 1, p = StrCaseStr(e, "w"))) {
1168 while (*p && (isspace(*p) || *p == '(' || *p == '/')) p++;
1175 case 0: /* FICS only, actually */
1177 /* Castling legal even if K starts on d-file */
1178 v = VariantWildCastle;
1183 /* Castling illegal even if K & R happen to start in
1184 normal positions. */
1185 v = VariantNoCastle;
1198 /* Castling legal iff K & R start in normal positions */
1204 /* Special wilds for position setup; unclear what to do here */
1205 v = VariantLoadable;
1208 /* Bizarre ICC game */
1209 v = VariantTwoKings;
1212 v = VariantKriegspiel;
1218 v = VariantFischeRandom;
1221 v = VariantCrazyhouse;
1224 v = VariantBughouse;
1230 /* Not quite the same as FICS suicide! */
1231 v = VariantGiveaway;
1237 v = VariantShatranj;
1240 /* Temporary names for future ICC types. The name *will* change in
1241 the next xboard/WinBoard release after ICC defines it. */
1268 /* Found "wild" or "w" in the string but no number;
1269 must assume it's normal chess. */
1273 sprintf(buf, "Unknown wild type %d", wnum);
1274 DisplayError(buf, 0);
1280 if (appData.debugMode) {
1281 fprintf(debugFP, _("recognized '%s' (%d) as variant %s\n"),
1282 e, wnum, VariantName(v));
1287 static int leftover_start = 0, leftover_len = 0;
1288 char star_match[STAR_MATCH_N][MSG_SIZ];
1290 /* Test whether pattern is present at &buf[*index]; if so, return TRUE,
1291 advance *index beyond it, and set leftover_start to the new value of
1292 *index; else return FALSE. If pattern contains the character '*', it
1293 matches any sequence of characters not containing '\r', '\n', or the
1294 character following the '*' (if any), and the matched sequence(s) are
1295 copied into star_match.
1298 looking_at(buf, index, pattern)
1303 char *bufp = &buf[*index], *patternp = pattern;
1305 char *matchp = star_match[0];
1308 if (*patternp == NULLCHAR) {
1309 *index = leftover_start = bufp - buf;
1313 if (*bufp == NULLCHAR) return FALSE;
1314 if (*patternp == '*') {
1315 if (*bufp == *(patternp + 1)) {
1317 matchp = star_match[++star_count];
1321 } else if (*bufp == '\n' || *bufp == '\r') {
1323 if (*patternp == NULLCHAR)
1328 *matchp++ = *bufp++;
1332 if (*patternp != *bufp) return FALSE;
1339 SendToPlayer(data, length)
1343 int error, outCount;
1344 outCount = OutputToProcess(NoProc, data, length, &error);
1345 if (outCount < length) {
1346 DisplayFatalError(_("Error writing to display"), error, 1);
1351 PackHolding(packed, holding)
1363 switch (runlength) {
1374 sprintf(q, "%d", runlength);
1386 /* Telnet protocol requests from the front end */
1388 TelnetRequest(ddww, option)
1389 unsigned char ddww, option;
1391 unsigned char msg[3];
1392 int outCount, outError;
1394 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet) return;
1396 if (appData.debugMode) {
1397 char buf1[8], buf2[8], *ddwwStr, *optionStr;
1413 sprintf(buf1, "%d", ddww);
1422 sprintf(buf2, "%d", option);
1425 fprintf(debugFP, ">%s %s ", ddwwStr, optionStr);
1430 outCount = OutputToProcess(icsPR, (char *)msg, 3, &outError);
1432 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1439 if (!appData.icsActive) return;
1440 TelnetRequest(TN_DO, TN_ECHO);
1446 if (!appData.icsActive) return;
1447 TelnetRequest(TN_DONT, TN_ECHO);
1450 static int loggedOn = FALSE;
1452 /*-- Game start info cache: --*/
1454 char gs_kind[MSG_SIZ];
1455 static char player1Name[128] = "";
1456 static char player2Name[128] = "";
1457 static int player1Rating = -1;
1458 static int player2Rating = -1;
1459 /*----------------------------*/
1462 read_from_ics(isr, closure, data, count, error)
1469 #define BUF_SIZE 8192
1470 #define STARTED_NONE 0
1471 #define STARTED_MOVES 1
1472 #define STARTED_BOARD 2
1473 #define STARTED_OBSERVE 3
1474 #define STARTED_HOLDINGS 4
1475 #define STARTED_CHATTER 5
1476 #define STARTED_COMMENT 6
1477 #define STARTED_MOVES_NOHIDE 7
1479 static int started = STARTED_NONE;
1480 static char parse[20000];
1481 static int parse_pos = 0;
1482 static char buf[BUF_SIZE + 1];
1483 static int firstTime = TRUE, intfSet = FALSE;
1484 static ColorClass curColor = ColorNormal;
1485 static ColorClass prevColor = ColorNormal;
1486 static int savingComment = FALSE;
1493 /* For zippy color lines of winboard
1494 * cleanup for gcc compiler */
1500 if (appData.debugMode) {
1502 fprintf(debugFP, "<ICS: ");
1503 show_bytes(debugFP, data, count);
1504 fprintf(debugFP, "\n");
1510 /* If last read ended with a partial line that we couldn't parse,
1511 prepend it to the new read and try again. */
1512 if (leftover_len > 0) {
1513 for (i=0; i<leftover_len; i++)
1514 buf[i] = buf[leftover_start + i];
1517 /* Copy in new characters, removing nulls and \r's */
1518 buf_len = leftover_len;
1519 for (i = 0; i < count; i++) {
1520 if (data[i] != NULLCHAR && data[i] != '\r')
1521 buf[buf_len++] = data[i];
1524 buf[buf_len] = NULLCHAR;
1525 next_out = leftover_len;
1529 while (i < buf_len) {
1530 /* Deal with part of the TELNET option negotiation
1531 protocol. We refuse to do anything beyond the
1532 defaults, except that we allow the WILL ECHO option,
1533 which ICS uses to turn off password echoing when we are
1534 directly connected to it. We reject this option
1535 if localLineEditing mode is on (always on in xboard)
1536 and we are talking to port 23, which might be a real
1537 telnet server that will try to keep WILL ECHO on permanently.
1539 if (buf_len - i >= 3 && (unsigned char) buf[i] == TN_IAC) {
1540 static int remoteEchoOption = FALSE; /* telnet ECHO option */
1541 unsigned char option;
1543 switch ((unsigned char) buf[++i]) {
1545 if (appData.debugMode)
1546 fprintf(debugFP, "\n<WILL ");
1547 switch (option = (unsigned char) buf[++i]) {
1549 if (appData.debugMode)
1550 fprintf(debugFP, "ECHO ");
1551 /* Reply only if this is a change, according
1552 to the protocol rules. */
1553 if (remoteEchoOption) break;
1554 if (appData.localLineEditing &&
1555 atoi(appData.icsPort) == TN_PORT) {
1556 TelnetRequest(TN_DONT, TN_ECHO);
1559 TelnetRequest(TN_DO, TN_ECHO);
1560 remoteEchoOption = TRUE;
1564 if (appData.debugMode)
1565 fprintf(debugFP, "%d ", option);
1566 /* Whatever this is, we don't want it. */
1567 TelnetRequest(TN_DONT, option);
1572 if (appData.debugMode)
1573 fprintf(debugFP, "\n<WONT ");
1574 switch (option = (unsigned char) buf[++i]) {
1576 if (appData.debugMode)
1577 fprintf(debugFP, "ECHO ");
1578 /* Reply only if this is a change, according
1579 to the protocol rules. */
1580 if (!remoteEchoOption) break;
1582 TelnetRequest(TN_DONT, TN_ECHO);
1583 remoteEchoOption = FALSE;
1586 if (appData.debugMode)
1587 fprintf(debugFP, "%d ", (unsigned char) option);
1588 /* Whatever this is, it must already be turned
1589 off, because we never agree to turn on
1590 anything non-default, so according to the
1591 protocol rules, we don't reply. */
1596 if (appData.debugMode)
1597 fprintf(debugFP, "\n<DO ");
1598 switch (option = (unsigned char) buf[++i]) {
1600 /* Whatever this is, we refuse to do it. */
1601 if (appData.debugMode)
1602 fprintf(debugFP, "%d ", option);
1603 TelnetRequest(TN_WONT, option);
1608 if (appData.debugMode)
1609 fprintf(debugFP, "\n<DONT ");
1610 switch (option = (unsigned char) buf[++i]) {
1612 if (appData.debugMode)
1613 fprintf(debugFP, "%d ", option);
1614 /* Whatever this is, we are already not doing
1615 it, because we never agree to do anything
1616 non-default, so according to the protocol
1617 rules, we don't reply. */
1622 if (appData.debugMode)
1623 fprintf(debugFP, "\n<IAC ");
1624 /* Doubled IAC; pass it through */
1628 if (appData.debugMode)
1629 fprintf(debugFP, "\n<%d ", (unsigned char) buf[i]);
1630 /* Drop all other telnet commands on the floor */
1633 if (oldi > next_out)
1634 SendToPlayer(&buf[next_out], oldi - next_out);
1640 /* OK, this at least will *usually* work */
1641 if (!loggedOn && looking_at(buf, &i, "ics%")) {
1645 if (loggedOn && !intfSet) {
1646 if (ics_type == ICS_ICC) {
1648 "/set-quietly interface %s\n/set-quietly style 12\n",
1651 } else if (ics_type == ICS_CHESSNET) {
1652 sprintf(str, "/style 12\n");
1654 strcpy(str, "alias $ @\n$set interface ");
1655 strcat(str, programVersion);
1656 strcat(str, "\n$iset startpos 1\n$iset ms 1\n");
1658 strcat(str, "$iset nohighlight 1\n");
1660 strcat(str, "$iset lock 1\n$style 12\n");
1666 if (started == STARTED_COMMENT) {
1667 /* Accumulate characters in comment */
1668 parse[parse_pos++] = buf[i];
1669 if (buf[i] == '\n') {
1670 parse[parse_pos] = NULLCHAR;
1671 AppendComment(forwardMostMove, StripHighlight(parse));
1672 started = STARTED_NONE;
1674 /* Don't match patterns against characters in chatter */
1679 if (started == STARTED_CHATTER) {
1680 if (buf[i] != '\n') {
1681 /* Don't match patterns against characters in chatter */
1685 started = STARTED_NONE;
1688 /* Kludge to deal with rcmd protocol */
1689 if (firstTime && looking_at(buf, &i, "\001*")) {
1690 DisplayFatalError(&buf[1], 0, 1);
1696 if (!loggedOn && looking_at(buf, &i, "chessclub.com")) {
1699 if (appData.debugMode)
1700 fprintf(debugFP, "ics_type %d\n", ics_type);
1703 if (!loggedOn && looking_at(buf, &i, "freechess.org")) {
1704 ics_type = ICS_FICS;
1706 if (appData.debugMode)
1707 fprintf(debugFP, "ics_type %d\n", ics_type);
1710 if (!loggedOn && looking_at(buf, &i, "chess.net")) {
1711 ics_type = ICS_CHESSNET;
1713 if (appData.debugMode)
1714 fprintf(debugFP, "ics_type %d\n", ics_type);
1719 (looking_at(buf, &i, "\"*\" is *a registered name") ||
1720 looking_at(buf, &i, "Logging you in as \"*\"") ||
1721 looking_at(buf, &i, "will be \"*\""))) {
1722 strcpy(ics_handle, star_match[0]);
1726 if (loggedOn && !have_set_title && ics_handle[0] != NULLCHAR) {
1728 sprintf(buf, "%s@%s", ics_handle, appData.icsHost);
1729 DisplayIcsInteractionTitle(buf);
1730 have_set_title = TRUE;
1733 /* skip finger notes */
1734 if (started == STARTED_NONE &&
1735 ((buf[i] == ' ' && isdigit(buf[i+1])) ||
1736 (buf[i] == '1' && buf[i+1] == '0')) &&
1737 buf[i+2] == ':' && buf[i+3] == ' ') {
1738 started = STARTED_CHATTER;
1743 /* skip formula vars */
1744 if (started == STARTED_NONE &&
1745 buf[i] == 'f' && isdigit(buf[i+1]) && buf[i+2] == ':') {
1746 started = STARTED_CHATTER;
1752 if (appData.zippyTalk || appData.zippyPlay) {
1755 /* Backup address for color zippy lines */
1757 if (loggedOn == TRUE)
1758 if (ZippyControl(buf, &backup) || ZippyConverse(buf, &backup) ||
1759 (appData.zippyPlay && ZippyMatch(buf, &backup)));
1761 if (ZippyControl(buf, &i) ||
1762 ZippyConverse(buf, &i) ||
1763 (appData.zippyPlay && ZippyMatch(buf, &i))) {
1770 if (/* Don't color "message" or "messages" output */
1771 (tkind = 5, looking_at(buf, &i, "*. * (*:*): ")) ||
1772 looking_at(buf, &i, "*. * at *:*: ") ||
1773 looking_at(buf, &i, "--* (*:*): ") ||
1774 /* Regular tells and says */
1775 (tkind = 1, looking_at(buf, &i, "* tells you: ")) ||
1776 looking_at(buf, &i, "* (your partner) tells you: ") ||
1777 looking_at(buf, &i, "* says: ") ||
1778 /* Message notifications (same color as tells) */
1779 looking_at(buf, &i, "* has left a message ") ||
1780 looking_at(buf, &i, "* just sent you a message:\n") ||
1781 /* Whispers and kibitzes */
1782 (tkind = 2, looking_at(buf, &i, "* whispers: ")) ||
1783 looking_at(buf, &i, "* kibitzes: ") ||
1785 (tkind = 3, looking_at(buf, &i, "*(*: "))) {
1787 if (tkind == 1 && strchr(star_match[0], ':')) {
1788 /* Avoid "tells you:" spoofs in channels */
1791 if (star_match[0][0] == NULLCHAR ||
1792 strchr(star_match[0], ' ') ||
1793 (tkind == 3 && strchr(star_match[1], ' '))) {
1794 /* Reject bogus matches */
1797 if (appData.colorize) {
1798 if (oldi > next_out) {
1799 SendToPlayer(&buf[next_out], oldi - next_out);
1804 Colorize(ColorTell, FALSE);
1805 curColor = ColorTell;
1808 Colorize(ColorKibitz, FALSE);
1809 curColor = ColorKibitz;
1812 p = strrchr(star_match[1], '(');
1819 Colorize(ColorChannel1, FALSE);
1820 curColor = ColorChannel1;
1822 Colorize(ColorChannel, FALSE);
1823 curColor = ColorChannel;
1827 curColor = ColorNormal;
1831 if (started == STARTED_NONE && appData.autoComment &&
1832 (gameMode == IcsObserving ||
1833 gameMode == IcsPlayingWhite ||
1834 gameMode == IcsPlayingBlack)) {
1835 parse_pos = i - oldi;
1836 memcpy(parse, &buf[oldi], parse_pos);
1837 parse[parse_pos] = NULLCHAR;
1838 started = STARTED_COMMENT;
1839 savingComment = TRUE;
1841 started = STARTED_CHATTER;
1842 savingComment = FALSE;
1849 if (looking_at(buf, &i, "* s-shouts: ") ||
1850 looking_at(buf, &i, "* c-shouts: ")) {
1851 if (appData.colorize) {
1852 if (oldi > next_out) {
1853 SendToPlayer(&buf[next_out], oldi - next_out);
1856 Colorize(ColorSShout, FALSE);
1857 curColor = ColorSShout;
1860 started = STARTED_CHATTER;
1864 if (looking_at(buf, &i, "--->")) {
1869 if (looking_at(buf, &i, "* shouts: ") ||
1870 looking_at(buf, &i, "--> ")) {
1871 if (appData.colorize) {
1872 if (oldi > next_out) {
1873 SendToPlayer(&buf[next_out], oldi - next_out);
1876 Colorize(ColorShout, FALSE);
1877 curColor = ColorShout;
1880 started = STARTED_CHATTER;
1884 if (looking_at( buf, &i, "Challenge:")) {
1885 if (appData.colorize) {
1886 if (oldi > next_out) {
1887 SendToPlayer(&buf[next_out], oldi - next_out);
1890 Colorize(ColorChallenge, FALSE);
1891 curColor = ColorChallenge;
1897 if (looking_at(buf, &i, "* offers you") ||
1898 looking_at(buf, &i, "* offers to be") ||
1899 looking_at(buf, &i, "* would like to") ||
1900 looking_at(buf, &i, "* requests to") ||
1901 looking_at(buf, &i, "Your opponent offers") ||
1902 looking_at(buf, &i, "Your opponent requests")) {
1904 if (appData.colorize) {
1905 if (oldi > next_out) {
1906 SendToPlayer(&buf[next_out], oldi - next_out);
1909 Colorize(ColorRequest, FALSE);
1910 curColor = ColorRequest;
1915 if (looking_at(buf, &i, "* (*) seeking")) {
1916 if (appData.colorize) {
1917 if (oldi > next_out) {
1918 SendToPlayer(&buf[next_out], oldi - next_out);
1921 Colorize(ColorSeek, FALSE);
1922 curColor = ColorSeek;
1927 if (looking_at(buf, &i, "\\ ")) {
1928 if (prevColor != ColorNormal) {
1929 if (oldi > next_out) {
1930 SendToPlayer(&buf[next_out], oldi - next_out);
1933 Colorize(prevColor, TRUE);
1934 curColor = prevColor;
1936 if (savingComment) {
1937 parse_pos = i - oldi;
1938 memcpy(parse, &buf[oldi], parse_pos);
1939 parse[parse_pos] = NULLCHAR;
1940 started = STARTED_COMMENT;
1942 started = STARTED_CHATTER;
1947 if (looking_at(buf, &i, "Black Strength :") ||
1948 looking_at(buf, &i, "<<< style 10 board >>>") ||
1949 looking_at(buf, &i, "<10>") ||
1950 looking_at(buf, &i, "#@#")) {
1951 /* Wrong board style */
1953 SendToICS(ics_prefix);
1954 SendToICS("set style 12\n");
1955 SendToICS(ics_prefix);
1956 SendToICS("refresh\n");
1960 if (!have_sent_ICS_logon && looking_at(buf, &i, "login:")) {
1962 have_sent_ICS_logon = 1;
1966 if (ics_getting_history != H_GETTING_MOVES /*smpos kludge*/ &&
1967 (looking_at(buf, &i, "\n<12> ") ||
1968 looking_at(buf, &i, "<12> "))) {
1970 if (oldi > next_out) {
1971 SendToPlayer(&buf[next_out], oldi - next_out);
1974 started = STARTED_BOARD;
1979 if ((started == STARTED_NONE && looking_at(buf, &i, "\n<b1> ")) ||
1980 looking_at(buf, &i, "<b1> ")) {
1981 if (oldi > next_out) {
1982 SendToPlayer(&buf[next_out], oldi - next_out);
1985 started = STARTED_HOLDINGS;
1990 if (looking_at(buf, &i, "* *vs. * *--- *")) {
1992 /* Header for a move list -- first line */
1994 switch (ics_getting_history) {
1998 case BeginningOfGame:
1999 /* User typed "moves" or "oldmoves" while we
2000 were idle. Pretend we asked for these
2001 moves and soak them up so user can step
2002 through them and/or save them.
2005 gameMode = IcsObserving;
2008 ics_getting_history = H_GOT_UNREQ_HEADER;
2010 case EditGame: /*?*/
2011 case EditPosition: /*?*/
2012 /* Should above feature work in these modes too? */
2013 /* For now it doesn't */
2014 ics_getting_history = H_GOT_UNWANTED_HEADER;
2017 ics_getting_history = H_GOT_UNWANTED_HEADER;
2022 /* Is this the right one? */
2023 if (gameInfo.white && gameInfo.black &&
2024 strcmp(gameInfo.white, star_match[0]) == 0 &&
2025 strcmp(gameInfo.black, star_match[2]) == 0) {
2027 ics_getting_history = H_GOT_REQ_HEADER;
2030 case H_GOT_REQ_HEADER:
2031 case H_GOT_UNREQ_HEADER:
2032 case H_GOT_UNWANTED_HEADER:
2033 case H_GETTING_MOVES:
2034 /* Should not happen */
2035 DisplayError(_("Error gathering move list: two headers"), 0);
2036 ics_getting_history = H_FALSE;
2040 /* Save player ratings into gameInfo if needed */
2041 if ((ics_getting_history == H_GOT_REQ_HEADER ||
2042 ics_getting_history == H_GOT_UNREQ_HEADER) &&
2043 (gameInfo.whiteRating == -1 ||
2044 gameInfo.blackRating == -1)) {
2046 gameInfo.whiteRating = string_to_rating(star_match[1]);
2047 gameInfo.blackRating = string_to_rating(star_match[3]);
2048 if (appData.debugMode)
2049 fprintf(debugFP, _("Ratings from header: W %d, B %d\n"),
2050 gameInfo.whiteRating, gameInfo.blackRating);
2055 if (looking_at(buf, &i,
2056 "* * match, initial time: * minute*, increment: * second")) {
2057 /* Header for a move list -- second line */
2058 /* Initial board will follow if this is a wild game */
2060 if (gameInfo.event != NULL) free(gameInfo.event);
2061 sprintf(str, "ICS %s %s match", star_match[0], star_match[1]);
2062 gameInfo.event = StrSave(str);
2063 gameInfo.variant = StringToVariant(gameInfo.event);
2067 if (looking_at(buf, &i, "Move ")) {
2068 /* Beginning of a move list */
2069 switch (ics_getting_history) {
2071 /* Normally should not happen */
2072 /* Maybe user hit reset while we were parsing */
2075 /* Happens if we are ignoring a move list that is not
2076 * the one we just requested. Common if the user
2077 * tries to observe two games without turning off
2080 case H_GETTING_MOVES:
2081 /* Should not happen */
2082 DisplayError(_("Error gathering move list: nested"), 0);
2083 ics_getting_history = H_FALSE;
2085 case H_GOT_REQ_HEADER:
2086 ics_getting_history = H_GETTING_MOVES;
2087 started = STARTED_MOVES;
2089 if (oldi > next_out) {
2090 SendToPlayer(&buf[next_out], oldi - next_out);
2093 case H_GOT_UNREQ_HEADER:
2094 ics_getting_history = H_GETTING_MOVES;
2095 started = STARTED_MOVES_NOHIDE;
2098 case H_GOT_UNWANTED_HEADER:
2099 ics_getting_history = H_FALSE;
2105 if (looking_at(buf, &i, "% ") ||
2106 ((started == STARTED_MOVES || started == STARTED_MOVES_NOHIDE)
2107 && looking_at(buf, &i, "}*"))) {
2108 savingComment = FALSE;
2111 case STARTED_MOVES_NOHIDE:
2112 memcpy(&parse[parse_pos], &buf[oldi], i - oldi);
2113 parse[parse_pos + i - oldi] = NULLCHAR;
2114 ParseGameHistory(parse);
2116 if (appData.zippyPlay && first.initDone) {
2117 FeedMovesToProgram(&first, forwardMostMove);
2118 if (gameMode == IcsPlayingWhite) {
2119 if (WhiteOnMove(forwardMostMove)) {
2120 if (first.sendTime) {
2121 if (first.useColors) {
2122 SendToProgram("black\n", &first);
2124 SendTimeRemaining(&first, TRUE);
2126 if (first.useColors) {
2127 SendToProgram("white\ngo\n", &first);
2129 SendToProgram("go\n", &first);
2131 first.maybeThinking = TRUE;
2133 if (first.usePlayother) {
2134 if (first.sendTime) {
2135 SendTimeRemaining(&first, TRUE);
2137 SendToProgram("playother\n", &first);
2143 } else if (gameMode == IcsPlayingBlack) {
2144 if (!WhiteOnMove(forwardMostMove)) {
2145 if (first.sendTime) {
2146 if (first.useColors) {
2147 SendToProgram("white\n", &first);
2149 SendTimeRemaining(&first, FALSE);
2151 if (first.useColors) {
2152 SendToProgram("black\ngo\n", &first);
2154 SendToProgram("go\n", &first);
2156 first.maybeThinking = TRUE;
2158 if (first.usePlayother) {
2159 if (first.sendTime) {
2160 SendTimeRemaining(&first, FALSE);
2162 SendToProgram("playother\n", &first);
2171 if (gameMode == IcsObserving && ics_gamenum == -1) {
2172 /* Moves came from oldmoves or moves command
2173 while we weren't doing anything else.
2175 currentMove = forwardMostMove;
2176 ClearHighlights();/*!!could figure this out*/
2177 flipView = appData.flipView;
2178 DrawPosition(FALSE, boards[currentMove]);
2179 DisplayBothClocks();
2180 sprintf(str, "%s vs. %s",
2181 gameInfo.white, gameInfo.black);
2185 /* Moves were history of an active game */
2186 if (gameInfo.resultDetails != NULL) {
2187 free(gameInfo.resultDetails);
2188 gameInfo.resultDetails = NULL;
2191 HistorySet(parseList, backwardMostMove,
2192 forwardMostMove, currentMove-1);
2193 DisplayMove(currentMove - 1);
2194 if (started == STARTED_MOVES) next_out = i;
2195 started = STARTED_NONE;
2196 ics_getting_history = H_FALSE;
2199 case STARTED_OBSERVE:
2200 started = STARTED_NONE;
2201 SendToICS(ics_prefix);
2202 SendToICS("refresh\n");
2211 if ((started == STARTED_MOVES || started == STARTED_BOARD ||
2212 started == STARTED_HOLDINGS ||
2213 started == STARTED_MOVES_NOHIDE) && i >= leftover_len) {
2214 /* Accumulate characters in move list or board */
2215 parse[parse_pos++] = buf[i];
2218 /* Start of game messages. Mostly we detect start of game
2219 when the first board image arrives. On some versions
2220 of the ICS, though, we need to do a "refresh" after starting
2221 to observe in order to get the current board right away. */
2222 if (looking_at(buf, &i, "Adding game * to observation list")) {
2223 started = STARTED_OBSERVE;
2227 /* Handle auto-observe */
2228 if (appData.autoObserve &&
2229 (gameMode == IcsIdle || gameMode == BeginningOfGame) &&
2230 looking_at(buf, &i, "Game notification: * (*) vs. * (*)")) {
2232 /* Choose the player that was highlighted, if any. */
2233 if (star_match[0][0] == '\033' ||
2234 star_match[1][0] != '\033') {
2235 player = star_match[0];
2237 player = star_match[2];
2239 sprintf(str, "%sobserve %s\n",
2240 ics_prefix, StripHighlightAndTitle(player));
2243 /* Save ratings from notify string */
2244 strcpy(player1Name, star_match[0]);
2245 player1Rating = string_to_rating(star_match[1]);
2246 strcpy(player2Name, star_match[2]);
2247 player2Rating = string_to_rating(star_match[3]);
2249 if (appData.debugMode)
2251 "Ratings from 'Game notification:' %s %d, %s %d\n",
2252 player1Name, player1Rating,
2253 player2Name, player2Rating);
2258 /* Deal with automatic examine mode after a game,
2259 and with IcsObserving -> IcsExamining transition */
2260 if (looking_at(buf, &i, "Entering examine mode for game *") ||
2261 looking_at(buf, &i, "has made you an examiner of game *")) {
2263 int gamenum = atoi(star_match[0]);
2264 if ((gameMode == IcsIdle || gameMode == IcsObserving) &&
2265 gamenum == ics_gamenum) {
2266 /* We were already playing or observing this game;
2267 no need to refetch history */
2268 gameMode = IcsExamining;
2270 pauseExamForwardMostMove = forwardMostMove;
2271 } else if (currentMove < forwardMostMove) {
2272 ForwardInner(forwardMostMove);
2275 /* I don't think this case really can happen */
2276 SendToICS(ics_prefix);
2277 SendToICS("refresh\n");
2282 /* Error messages */
2283 if (ics_user_moved) {
2284 if (looking_at(buf, &i, "Illegal move") ||
2285 looking_at(buf, &i, "Not a legal move") ||
2286 looking_at(buf, &i, "Your king is in check") ||
2287 looking_at(buf, &i, "It isn't your turn") ||
2288 looking_at(buf, &i, "It is not your move")) {
2291 if (forwardMostMove > backwardMostMove) {
2292 currentMove = --forwardMostMove;
2293 DisplayMove(currentMove - 1); /* before DMError */
2294 DisplayMoveError("Illegal move (rejected by ICS)");
2295 DrawPosition(FALSE, boards[currentMove]);
2297 DisplayBothClocks();
2303 if (looking_at(buf, &i, "still have time") ||
2304 looking_at(buf, &i, "not out of time") ||
2305 looking_at(buf, &i, "either player is out of time") ||
2306 looking_at(buf, &i, "has timeseal; checking")) {
2307 /* We must have called his flag a little too soon */
2308 whiteFlag = blackFlag = FALSE;
2312 if (looking_at(buf, &i, "added * seconds to") ||
2313 looking_at(buf, &i, "seconds were added to")) {
2314 /* Update the clocks */
2315 SendToICS(ics_prefix);
2316 SendToICS("refresh\n");
2320 if (!ics_clock_paused && looking_at(buf, &i, "clock paused")) {
2321 ics_clock_paused = TRUE;
2326 if (ics_clock_paused && looking_at(buf, &i, "clock resumed")) {
2327 ics_clock_paused = FALSE;
2332 /* Grab player ratings from the Creating: message.
2333 Note we have to check for the special case when
2334 the ICS inserts things like [white] or [black]. */
2335 if (looking_at(buf, &i, "Creating: * (*)* * (*)") ||
2336 looking_at(buf, &i, "Creating: * (*) [*] * (*)")) {
2338 0 player 1 name (not necessarily white)
2340 2 empty, white, or black (IGNORED)
2341 3 player 2 name (not necessarily black)
2344 The names/ratings are sorted out when the game
2345 actually starts (below).
2347 strcpy(player1Name, StripHighlightAndTitle(star_match[0]));
2348 player1Rating = string_to_rating(star_match[1]);
2349 strcpy(player2Name, StripHighlightAndTitle(star_match[3]));
2350 player2Rating = string_to_rating(star_match[4]);
2352 if (appData.debugMode)
2354 "Ratings from 'Creating:' %s %d, %s %d\n",
2355 player1Name, player1Rating,
2356 player2Name, player2Rating);
2361 /* Improved generic start/end-of-game messages */
2362 if ((tkind=0, looking_at(buf, &i, "{Game * (* vs. *) *}*")) ||
2363 (tkind=1, looking_at(buf, &i, "{Game * (*(*) vs. *(*)) *}*"))){
2364 /* If tkind == 0: */
2365 /* star_match[0] is the game number */
2366 /* [1] is the white player's name */
2367 /* [2] is the black player's name */
2368 /* For end-of-game: */
2369 /* [3] is the reason for the game end */
2370 /* [4] is a PGN end game-token, preceded by " " */
2371 /* For start-of-game: */
2372 /* [3] begins with "Creating" or "Continuing" */
2373 /* [4] is " *" or empty (don't care). */
2374 int gamenum = atoi(star_match[0]);
2375 char *whitename, *blackname, *why, *endtoken;
2376 ChessMove endtype = (ChessMove) 0;
2379 whitename = star_match[1];
2380 blackname = star_match[2];
2381 why = star_match[3];
2382 endtoken = star_match[4];
2384 whitename = star_match[1];
2385 blackname = star_match[3];
2386 why = star_match[5];
2387 endtoken = star_match[6];
2390 /* Game start messages */
2391 if (strncmp(why, "Creating ", 9) == 0 ||
2392 strncmp(why, "Continuing ", 11) == 0) {
2393 gs_gamenum = gamenum;
2394 strcpy(gs_kind, strchr(why, ' ') + 1);
2396 if (appData.zippyPlay) {
2397 ZippyGameStart(whitename, blackname);
2403 /* Game end messages */
2404 if (gameMode == IcsIdle || gameMode == BeginningOfGame ||
2405 ics_gamenum != gamenum) {
2408 while (endtoken[0] == ' ') endtoken++;
2409 switch (endtoken[0]) {
2412 endtype = GameUnfinished;
2415 endtype = BlackWins;
2418 if (endtoken[1] == '/')
2419 endtype = GameIsDrawn;
2421 endtype = WhiteWins;
2424 GameEnds(endtype, why, GE_ICS);
2426 if (appData.zippyPlay && first.initDone) {
2427 ZippyGameEnd(endtype, why);
2428 if (first.pr == NULL) {
2429 /* Start the next process early so that we'll
2430 be ready for the next challenge */
2431 StartChessProgram(&first);
2433 /* Send "new" early, in case this command takes
2434 a long time to finish, so that we'll be ready
2435 for the next challenge. */
2442 if (looking_at(buf, &i, "Removing game * from observation") ||
2443 looking_at(buf, &i, "no longer observing game *") ||
2444 looking_at(buf, &i, "Game * (*) has no examiners")) {
2445 if (gameMode == IcsObserving &&
2446 atoi(star_match[0]) == ics_gamenum)
2451 ics_user_moved = FALSE;
2456 if (looking_at(buf, &i, "no longer examining game *")) {
2457 if (gameMode == IcsExamining &&
2458 atoi(star_match[0]) == ics_gamenum)
2462 ics_user_moved = FALSE;
2467 /* Advance leftover_start past any newlines we find,
2468 so only partial lines can get reparsed */
2469 if (looking_at(buf, &i, "\n")) {
2470 prevColor = curColor;
2471 if (curColor != ColorNormal) {
2472 if (oldi > next_out) {
2473 SendToPlayer(&buf[next_out], oldi - next_out);
2476 Colorize(ColorNormal, FALSE);
2477 curColor = ColorNormal;
2479 if (started == STARTED_BOARD) {
2480 started = STARTED_NONE;
2481 parse[parse_pos] = NULLCHAR;
2482 ParseBoard12(parse);
2485 /* Send premove here */
2486 if (appData.premove) {
2488 if (currentMove == 0 &&
2489 gameMode == IcsPlayingWhite &&
2490 appData.premoveWhite) {
2491 sprintf(str, "%s%s\n", ics_prefix,
2492 appData.premoveWhiteText);
2493 if (appData.debugMode)
2494 fprintf(debugFP, "Sending premove:\n");
2496 } else if (currentMove == 1 &&
2497 gameMode == IcsPlayingBlack &&
2498 appData.premoveBlack) {
2499 sprintf(str, "%s%s\n", ics_prefix,
2500 appData.premoveBlackText);
2501 if (appData.debugMode)
2502 fprintf(debugFP, "Sending premove:\n");
2504 } else if (gotPremove) {
2506 ClearPremoveHighlights();
2507 if (appData.debugMode)
2508 fprintf(debugFP, "Sending premove:\n");
2509 UserMoveEvent(premoveFromX, premoveFromY,
2510 premoveToX, premoveToY,
2515 /* Usually suppress following prompt */
2516 if (!(forwardMostMove == 0 && gameMode == IcsExamining)) {
2517 if (looking_at(buf, &i, "*% ")) {
2518 savingComment = FALSE;
2522 } else if (started == STARTED_HOLDINGS) {
2524 char new_piece[MSG_SIZ];
2525 started = STARTED_NONE;
2526 parse[parse_pos] = NULLCHAR;
2527 if (appData.debugMode)
2528 fprintf(debugFP, "Parsing holdings: %s\n", parse);
2529 if (sscanf(parse, " game %d", &gamenum) == 1 &&
2530 gamenum == ics_gamenum) {
2531 if (gameInfo.variant == VariantNormal) {
2532 gameInfo.variant = VariantCrazyhouse; /*temp guess*/
2533 /* Get a move list just to see the header, which
2534 will tell us whether this is really bug or zh */
2535 if (ics_getting_history == H_FALSE) {
2536 ics_getting_history = H_REQUESTED;
2537 sprintf(str, "%smoves %d\n", ics_prefix, gamenum);
2541 new_piece[0] = NULLCHAR;
2542 sscanf(parse, "game %d white [%s black [%s <- %s",
2543 &gamenum, white_holding, black_holding,
2545 white_holding[strlen(white_holding)-1] = NULLCHAR;
2546 black_holding[strlen(black_holding)-1] = NULLCHAR;
2548 if (appData.zippyPlay && first.initDone) {
2549 ZippyHoldings(white_holding, black_holding,
2553 if (tinyLayout || smallLayout) {
2554 char wh[16], bh[16];
2555 PackHolding(wh, white_holding);
2556 PackHolding(bh, black_holding);
2557 sprintf(str, "[%s-%s] %s-%s", wh, bh,
2558 gameInfo.white, gameInfo.black);
2560 sprintf(str, "%s [%s] vs. %s [%s]",
2561 gameInfo.white, white_holding,
2562 gameInfo.black, black_holding);
2564 DrawPosition(FALSE, NULL);
2567 /* Suppress following prompt */
2568 if (looking_at(buf, &i, "*% ")) {
2569 savingComment = FALSE;
2576 i++; /* skip unparsed character and loop back */
2579 if (started != STARTED_MOVES && started != STARTED_BOARD &&
2580 started != STARTED_HOLDINGS && i > next_out) {
2581 SendToPlayer(&buf[next_out], i - next_out);
2585 leftover_len = buf_len - leftover_start;
2586 /* if buffer ends with something we couldn't parse,
2587 reparse it after appending the next read */
2589 } else if (count == 0) {
2590 RemoveInputSource(isr);
2591 DisplayFatalError(_("Connection closed by ICS"), 0, 0);
2593 DisplayFatalError(_("Error reading from ICS"), error, 1);
2598 /* Board style 12 looks like this:
2600 <12> r-b---k- pp----pp ---bP--- ---p---- q------- ------P- P--Q--BP -----R-K W -1 0 0 0 0 0 0 paf MaxII 0 2 12 21 25 234 174 24 Q/d7-a4 (0:06) Qxa4 0 0
2602 * The "<12> " is stripped before it gets to this routine. The two
2603 * trailing 0's (flip state and clock ticking) are later addition, and
2604 * some chess servers may not have them, or may have only the first.
2605 * Additional trailing fields may be added in the future.
2608 #define PATTERN "%72c%c%d%d%d%d%d%d%d%s%s%d%d%d%d%d%d%d%d%s%s%s%d%d"
2610 #define RELATION_OBSERVING_PLAYED 0
2611 #define RELATION_OBSERVING_STATIC -2 /* examined, oldmoves, or smoves */
2612 #define RELATION_PLAYING_MYMOVE 1
2613 #define RELATION_PLAYING_NOTMYMOVE -1
2614 #define RELATION_EXAMINING 2
2615 #define RELATION_ISOLATED_BOARD -3
2616 #define RELATION_STARTING_POSITION -4 /* FICS only */
2619 ParseBoard12(string)
2622 GameMode newGameMode;
2623 int gamenum, newGame, newMove, relation, basetime, increment, ics_flip = 0;
2624 int j, k, n, moveNum, white_stren, black_stren, white_time, black_time;
2625 int double_push, castle_ws, castle_wl, castle_bs, castle_bl, irrev_count;
2626 char to_play, board_chars[72];
2627 char move_str[500], str[500], elapsed_time[500];
2628 char black[32], white[32];
2630 int prevMove = currentMove;
2633 int fromX, fromY, toX, toY;
2636 fromX = fromY = toX = toY = -1;
2640 if (appData.debugMode)
2641 fprintf(debugFP, _("Parsing board: %s\n"), string);
2643 move_str[0] = NULLCHAR;
2644 elapsed_time[0] = NULLCHAR;
2645 n = sscanf(string, PATTERN, board_chars, &to_play, &double_push,
2646 &castle_ws, &castle_wl, &castle_bs, &castle_bl, &irrev_count,
2647 &gamenum, white, black, &relation, &basetime, &increment,
2648 &white_stren, &black_stren, &white_time, &black_time,
2649 &moveNum, str, elapsed_time, move_str, &ics_flip,
2653 sprintf(str, _("Failed to parse board string:\n\"%s\""), string);
2654 DisplayError(str, 0);
2658 /* Convert the move number to internal form */
2659 moveNum = (moveNum - 1) * 2;
2660 if (to_play == 'B') moveNum++;
2661 if (moveNum >= MAX_MOVES) {
2662 DisplayFatalError(_("Game too long; increase MAX_MOVES and recompile"),
2668 case RELATION_OBSERVING_PLAYED:
2669 case RELATION_OBSERVING_STATIC:
2670 if (gamenum == -1) {
2671 /* Old ICC buglet */
2672 relation = RELATION_OBSERVING_STATIC;
2674 newGameMode = IcsObserving;
2676 case RELATION_PLAYING_MYMOVE:
2677 case RELATION_PLAYING_NOTMYMOVE:
2679 ((relation == RELATION_PLAYING_MYMOVE) == (to_play == 'W')) ?
2680 IcsPlayingWhite : IcsPlayingBlack;
2682 case RELATION_EXAMINING:
2683 newGameMode = IcsExamining;
2685 case RELATION_ISOLATED_BOARD:
2687 /* Just display this board. If user was doing something else,
2688 we will forget about it until the next board comes. */
2689 newGameMode = IcsIdle;
2691 case RELATION_STARTING_POSITION:
2692 newGameMode = gameMode;
2696 /* Modify behavior for initial board display on move listing
2699 switch (ics_getting_history) {
2703 case H_GOT_REQ_HEADER:
2704 case H_GOT_UNREQ_HEADER:
2705 /* This is the initial position of the current game */
2706 gamenum = ics_gamenum;
2707 moveNum = 0; /* old ICS bug workaround */
2708 if (to_play == 'B') {
2709 startedFromSetupPosition = TRUE;
2710 blackPlaysFirst = TRUE;
2712 if (forwardMostMove == 0) forwardMostMove = 1;
2713 if (backwardMostMove == 0) backwardMostMove = 1;
2714 if (currentMove == 0) currentMove = 1;
2716 newGameMode = gameMode;
2717 relation = RELATION_STARTING_POSITION; /* ICC needs this */
2719 case H_GOT_UNWANTED_HEADER:
2720 /* This is an initial board that we don't want */
2722 case H_GETTING_MOVES:
2723 /* Should not happen */
2724 DisplayError(_("Error gathering move list: extra board"), 0);
2725 ics_getting_history = H_FALSE;
2729 /* Take action if this is the first board of a new game, or of a
2730 different game than is currently being displayed. */
2731 if (gamenum != ics_gamenum || newGameMode != gameMode ||
2732 relation == RELATION_ISOLATED_BOARD) {
2734 /* Forget the old game and get the history (if any) of the new one */
2735 if (gameMode != BeginningOfGame) {
2739 if (appData.autoRaiseBoard) BoardToTop();
2741 if (gamenum == -1) {
2742 newGameMode = IcsIdle;
2743 } else if (moveNum > 0 && newGameMode != IcsIdle &&
2744 appData.getMoveList) {
2745 /* Need to get game history */
2746 ics_getting_history = H_REQUESTED;
2747 sprintf(str, "%smoves %d\n", ics_prefix, gamenum);
2751 /* Initially flip the board to have black on the bottom if playing
2752 black or if the ICS flip flag is set, but let the user change
2753 it with the Flip View button. */
2754 flipView = appData.autoFlipView ?
2755 (newGameMode == IcsPlayingBlack) || ics_flip :
2758 /* Done with values from previous mode; copy in new ones */
2759 gameMode = newGameMode;
2761 ics_gamenum = gamenum;
2762 if (gamenum == gs_gamenum) {
2763 int klen = strlen(gs_kind);
2764 if (gs_kind[klen - 1] == '.') gs_kind[klen - 1] = NULLCHAR;
2765 sprintf(str, "ICS %s", gs_kind);
2766 gameInfo.event = StrSave(str);
2768 gameInfo.event = StrSave("ICS game");
2770 gameInfo.site = StrSave(appData.icsHost);
2771 gameInfo.date = PGNDate();
2772 gameInfo.round = StrSave("-");
2773 gameInfo.white = StrSave(white);
2774 gameInfo.black = StrSave(black);
2775 timeControl = basetime * 60 * 1000;
2776 timeIncrement = increment * 1000;
2777 movesPerSession = 0;
2778 gameInfo.timeControl = TimeControlTagValue();
2779 gameInfo.variant = StringToVariant(gameInfo.event);
2781 /* Do we have the ratings? */
2782 if (strcmp(player1Name, white) == 0 &&
2783 strcmp(player2Name, black) == 0) {
2784 if (appData.debugMode)
2785 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
2786 player1Rating, player2Rating);
2787 gameInfo.whiteRating = player1Rating;
2788 gameInfo.blackRating = player2Rating;
2789 } else if (strcmp(player2Name, white) == 0 &&
2790 strcmp(player1Name, black) == 0) {
2791 if (appData.debugMode)
2792 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
2793 player2Rating, player1Rating);
2794 gameInfo.whiteRating = player2Rating;
2795 gameInfo.blackRating = player1Rating;
2797 player1Name[0] = player2Name[0] = NULLCHAR;
2799 /* Silence shouts if requested */
2800 if (appData.quietPlay &&
2801 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)) {
2802 SendToICS(ics_prefix);
2803 SendToICS("set shout 0\n");
2807 /* Deal with midgame name changes */
2809 if (!gameInfo.white || strcmp(gameInfo.white, white) != 0) {
2810 if (gameInfo.white) free(gameInfo.white);
2811 gameInfo.white = StrSave(white);
2813 if (!gameInfo.black || strcmp(gameInfo.black, black) != 0) {
2814 if (gameInfo.black) free(gameInfo.black);
2815 gameInfo.black = StrSave(black);
2819 /* Throw away game result if anything actually changes in examine mode */
2820 if (gameMode == IcsExamining && !newGame) {
2821 gameInfo.result = GameUnfinished;
2822 if (gameInfo.resultDetails != NULL) {
2823 free(gameInfo.resultDetails);
2824 gameInfo.resultDetails = NULL;
2828 /* In pausing && IcsExamining mode, we ignore boards coming
2829 in if they are in a different variation than we are. */
2830 if (pauseExamInvalid) return;
2831 if (pausing && gameMode == IcsExamining) {
2832 if (moveNum <= pauseExamForwardMostMove) {
2833 pauseExamInvalid = TRUE;
2834 forwardMostMove = pauseExamForwardMostMove;
2839 /* Parse the board */
2840 for (k = 0; k < 8; k++)
2841 for (j = 0; j < 8; j++)
2842 board[k][j] = CharToPiece(board_chars[(7-k)*9 + j]);
2843 CopyBoard(boards[moveNum], board);
2845 startedFromSetupPosition =
2846 !CompareBoards(board, initialPosition);
2849 if (ics_getting_history == H_GOT_REQ_HEADER ||
2850 ics_getting_history == H_GOT_UNREQ_HEADER) {
2851 /* This was an initial position from a move list, not
2852 the current position */
2856 /* Update currentMove and known move number limits */
2857 newMove = newGame || moveNum > forwardMostMove;
2859 forwardMostMove = backwardMostMove = currentMove = moveNum;
2860 if (gameMode == IcsExamining && moveNum == 0) {
2861 /* Workaround for ICS limitation: we are not told the wild
2862 type when starting to examine a game. But if we ask for
2863 the move list, the move list header will tell us */
2864 ics_getting_history = H_REQUESTED;
2865 sprintf(str, "%smoves %d\n", ics_prefix, gamenum);
2868 } else if (moveNum == forwardMostMove + 1 || moveNum == forwardMostMove
2869 || (moveNum < forwardMostMove && moveNum >= backwardMostMove)) {
2870 forwardMostMove = moveNum;
2871 if (!pausing || currentMove > forwardMostMove)
2872 currentMove = forwardMostMove;
2874 /* New part of history that is not contiguous with old part */
2875 if (pausing && gameMode == IcsExamining) {
2876 pauseExamInvalid = TRUE;
2877 forwardMostMove = pauseExamForwardMostMove;
2880 forwardMostMove = backwardMostMove = currentMove = moveNum;
2881 if (gameMode == IcsExamining && moveNum > 0 && appData.getMoveList) {
2882 ics_getting_history = H_REQUESTED;
2883 sprintf(str, "%smoves %d\n", ics_prefix, gamenum);
2888 /* Update the clocks */
2889 if (strchr(elapsed_time, '.')) {
2891 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time;
2892 timeRemaining[1][moveNum] = blackTimeRemaining = black_time;
2894 /* Time is in seconds */
2895 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time * 1000;
2896 timeRemaining[1][moveNum] = blackTimeRemaining = black_time * 1000;
2901 if (appData.zippyPlay && newGame &&
2902 gameMode != IcsObserving && gameMode != IcsIdle &&
2903 gameMode != IcsExamining)
2904 ZippyFirstBoard(moveNum, basetime, increment);
2907 /* Put the move on the move list, first converting
2908 to canonical algebraic form. */
2910 if (moveNum <= backwardMostMove) {
2911 /* We don't know what the board looked like before
2913 strcpy(parseList[moveNum - 1], move_str);
2914 strcat(parseList[moveNum - 1], " ");
2915 strcat(parseList[moveNum - 1], elapsed_time);
2916 moveList[moveNum - 1][0] = NULLCHAR;
2917 } else if (ParseOneMove(move_str, moveNum - 1, &moveType,
2918 &fromX, &fromY, &toX, &toY, &promoChar)) {
2919 (void) CoordsToAlgebraic(boards[moveNum - 1],
2920 PosFlags(moveNum - 1), EP_UNKNOWN,
2921 fromY, fromX, toY, toX, promoChar,
2922 parseList[moveNum-1]);
2923 switch (MateTest(boards[moveNum], PosFlags(moveNum), EP_UNKNOWN)){
2929 strcat(parseList[moveNum - 1], "+");
2932 strcat(parseList[moveNum - 1], "#");
2935 strcat(parseList[moveNum - 1], " ");
2936 strcat(parseList[moveNum - 1], elapsed_time);
2937 /* currentMoveString is set as a side-effect of ParseOneMove */
2938 strcpy(moveList[moveNum - 1], currentMoveString);
2939 strcat(moveList[moveNum - 1], "\n");
2940 } else if (strcmp(move_str, "none") == 0) {
2941 /* Again, we don't know what the board looked like;
2942 this is really the start of the game. */
2943 parseList[moveNum - 1][0] = NULLCHAR;
2944 moveList[moveNum - 1][0] = NULLCHAR;
2945 backwardMostMove = moveNum;
2946 startedFromSetupPosition = TRUE;
2947 fromX = fromY = toX = toY = -1;
2949 /* Move from ICS was illegal!? Punt. */
2951 if (appData.testLegality && appData.debugMode) {
2952 sprintf(str, "Illegal move \"%s\" from ICS", move_str);
2953 DisplayError(str, 0);
2956 strcpy(parseList[moveNum - 1], move_str);
2957 strcat(parseList[moveNum - 1], " ");
2958 strcat(parseList[moveNum - 1], elapsed_time);
2959 moveList[moveNum - 1][0] = NULLCHAR;
2960 fromX = fromY = toX = toY = -1;
2964 /* Send move to chess program (BEFORE animating it). */
2965 if (appData.zippyPlay && !newGame && newMove &&
2966 (!appData.getMoveList || backwardMostMove == 0) && first.initDone) {
2968 if ((gameMode == IcsPlayingWhite && WhiteOnMove(moveNum)) ||
2969 (gameMode == IcsPlayingBlack && !WhiteOnMove(moveNum))) {
2970 if (moveList[moveNum - 1][0] == NULLCHAR) {
2971 sprintf(str, _("Couldn't parse move \"%s\" from ICS"),
2973 DisplayError(str, 0);
2975 if (first.sendTime) {
2976 SendTimeRemaining(&first, gameMode == IcsPlayingWhite);
2978 SendMoveToProgram(moveNum - 1, &first);
2981 if (first.useColors) {
2982 SendToProgram(gameMode == IcsPlayingWhite ?
2984 "black\ngo\n", &first);
2986 SendToProgram("go\n", &first);
2988 first.maybeThinking = TRUE;
2991 } else if (gameMode == IcsObserving || gameMode == IcsExamining) {
2992 if (moveList[moveNum - 1][0] == NULLCHAR) {
2993 sprintf(str, _("Couldn't parse move \"%s\" from ICS"), move_str);
2994 DisplayError(str, 0);
2996 SendMoveToProgram(moveNum - 1, &first);
3003 if (moveNum > 0 && !gotPremove) {
3004 /* If move comes from a remote source, animate it. If it
3005 isn't remote, it will have already been animated. */
3006 if (!pausing && !ics_user_moved && prevMove == moveNum - 1) {
3007 AnimateMove(boards[moveNum - 1], fromX, fromY, toX, toY);
3009 if (!pausing && appData.highlightLastMove) {
3010 SetHighlights(fromX, fromY, toX, toY);
3014 /* Start the clocks */
3015 whiteFlag = blackFlag = FALSE;
3016 appData.clockMode = !(basetime == 0 && increment == 0);
3018 ics_clock_paused = TRUE;
3020 } else if (ticking == 1) {
3021 ics_clock_paused = FALSE;
3023 if (gameMode == IcsIdle ||
3024 relation == RELATION_OBSERVING_STATIC ||
3025 relation == RELATION_EXAMINING ||
3027 DisplayBothClocks();
3031 /* Display opponents and material strengths */
3032 if (gameInfo.variant != VariantBughouse &&
3033 gameInfo.variant != VariantCrazyhouse) {
3034 if (tinyLayout || smallLayout) {
3035 sprintf(str, "%s(%d) %s(%d) {%d %d}",
3036 gameInfo.white, white_stren, gameInfo.black, black_stren,
3037 basetime, increment);
3039 sprintf(str, "%s (%d) vs. %s (%d) {%d %d}",
3040 gameInfo.white, white_stren, gameInfo.black, black_stren,
3041 basetime, increment);
3047 /* Display the board */
3050 if (appData.premove)
3052 ((gameMode == IcsPlayingWhite) && (WhiteOnMove(currentMove))) ||
3053 ((gameMode == IcsPlayingBlack) && (!WhiteOnMove(currentMove))))
3054 ClearPremoveHighlights();
3056 DrawPosition(FALSE, boards[currentMove]);
3057 DisplayMove(moveNum - 1);
3058 if (appData.ringBellAfterMoves && !ics_user_moved)
3062 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
3069 if (appData.icsActive && gameMode != IcsIdle && ics_gamenum > 0) {
3070 ics_getting_history = H_REQUESTED;
3071 sprintf(buf, "%smoves %d\n", ics_prefix, ics_gamenum);
3077 AnalysisPeriodicEvent(force)
3080 if (((programStats.ok_to_send == 0 || programStats.line_is_book)
3081 && !force) || !appData.periodicUpdates)
3084 /* Send . command to Crafty to collect stats */
3085 SendToProgram(".\n", &first);
3087 /* Don't send another until we get a response (this makes
3088 us stop sending to old Crafty's which don't understand
3089 the "." command (sending illegal cmds resets node count & time,
3090 which looks bad)) */
3091 programStats.ok_to_send = 0;
3095 SendMoveToProgram(moveNum, cps)
3097 ChessProgramState *cps;
3100 if (cps->useUsermove) {
3101 SendToProgram("usermove ", cps);
3105 if ((space = strchr(parseList[moveNum], ' ')) != NULL) {
3106 int len = space - parseList[moveNum];
3107 memcpy(buf, parseList[moveNum], len);
3109 buf[len] = NULLCHAR;
3111 sprintf(buf, "%s\n", parseList[moveNum]);
3113 SendToProgram(buf, cps);
3115 SendToProgram(moveList[moveNum], cps);
3120 SendMoveToICS(moveType, fromX, fromY, toX, toY)
3122 int fromX, fromY, toX, toY;
3124 char user_move[MSG_SIZ];
3128 sprintf(user_move, "say Internal error; bad moveType %d (%d,%d-%d,%d)",
3129 (int)moveType, fromX, fromY, toX, toY);
3130 DisplayError(user_move + strlen("say "), 0);
3132 case WhiteKingSideCastle:
3133 case BlackKingSideCastle:
3134 case WhiteQueenSideCastleWild:
3135 case BlackQueenSideCastleWild:
3136 sprintf(user_move, "o-o\n");
3138 case WhiteQueenSideCastle:
3139 case BlackQueenSideCastle:
3140 case WhiteKingSideCastleWild:
3141 case BlackKingSideCastleWild:
3142 sprintf(user_move, "o-o-o\n");
3144 case WhitePromotionQueen:
3145 case BlackPromotionQueen:
3146 case WhitePromotionRook:
3147 case BlackPromotionRook:
3148 case WhitePromotionBishop:
3149 case BlackPromotionBishop:
3150 case WhitePromotionKnight:
3151 case BlackPromotionKnight:
3152 case WhitePromotionKing:
3153 case BlackPromotionKing:
3154 sprintf(user_move, "%c%c%c%c=%c\n",
3155 'a' + fromX, '1' + fromY, 'a' + toX, '1' + toY,
3156 PieceToChar(PromoPiece(moveType)));
3160 sprintf(user_move, "%c@%c%c\n",
3161 ToUpper(PieceToChar((ChessSquare) fromX)),
3162 'a' + toX, '1' + toY);
3165 case WhiteCapturesEnPassant:
3166 case BlackCapturesEnPassant:
3167 case IllegalMove: /* could be a variant we don't quite understand */
3168 sprintf(user_move, "%c%c%c%c\n",
3169 'a' + fromX, '1' + fromY, 'a' + toX, '1' + toY);
3172 SendToICS(user_move);
3176 CoordsToComputerAlgebraic(rf, ff, rt, ft, promoChar, move)
3181 if (rf == DROP_RANK) {
3182 sprintf(move, "%c@%c%c\n",
3183 ToUpper(PieceToChar((ChessSquare) ff)), 'a' + ft, '1' + rt);
3185 if (promoChar == 'x' || promoChar == NULLCHAR) {
3186 sprintf(move, "%c%c%c%c\n",
3187 'a' + ff, '1' + rf, 'a' + ft, '1' + rt);
3189 sprintf(move, "%c%c%c%c%c\n",
3190 'a' + ff, '1' + rf, 'a' + ft, '1' + rt, promoChar);
3196 ProcessICSInitScript(f)
3201 while (fgets(buf, MSG_SIZ, f)) {
3202 SendToICSDelayed(buf,(long)appData.msLoginDelay);
3209 /* Parser for moves from gnuchess, ICS, or user typein box */
3211 ParseOneMove(move, moveNum, moveType, fromX, fromY, toX, toY, promoChar)
3214 ChessMove *moveType;
3215 int *fromX, *fromY, *toX, *toY;
3218 *moveType = yylexstr(moveNum, move);
3219 switch (*moveType) {
3220 case WhitePromotionQueen:
3221 case BlackPromotionQueen:
3222 case WhitePromotionRook:
3223 case BlackPromotionRook:
3224 case WhitePromotionBishop:
3225 case BlackPromotionBishop:
3226 case WhitePromotionKnight:
3227 case BlackPromotionKnight:
3228 case WhitePromotionKing:
3229 case BlackPromotionKing:
3231 case WhiteCapturesEnPassant:
3232 case BlackCapturesEnPassant:
3233 case WhiteKingSideCastle:
3234 case WhiteQueenSideCastle:
3235 case BlackKingSideCastle:
3236 case BlackQueenSideCastle:
3237 case WhiteKingSideCastleWild:
3238 case WhiteQueenSideCastleWild:
3239 case BlackKingSideCastleWild:
3240 case BlackQueenSideCastleWild:
3241 case IllegalMove: /* bug or odd chess variant */
3242 *fromX = currentMoveString[0] - 'a';
3243 *fromY = currentMoveString[1] - '1';
3244 *toX = currentMoveString[2] - 'a';
3245 *toY = currentMoveString[3] - '1';
3246 *promoChar = currentMoveString[4];
3247 if (*fromX < 0 || *fromX > 7 || *fromY < 0 || *fromY > 7 ||
3248 *toX < 0 || *toX > 7 || *toY < 0 || *toY > 7) {
3249 *fromX = *fromY = *toX = *toY = 0;
3252 if (appData.testLegality) {
3253 return (*moveType != IllegalMove);
3255 return !(fromX == fromY && toX == toY);
3260 *fromX = *moveType == WhiteDrop ?
3261 (int) CharToPiece(ToUpper(currentMoveString[0])) :
3262 (int) CharToPiece(ToLower(currentMoveString[0]));
3264 *toX = currentMoveString[2] - 'a';
3265 *toY = currentMoveString[3] - '1';
3266 *promoChar = NULLCHAR;
3270 case ImpossibleMove:
3271 case (ChessMove) 0: /* end of file */
3281 *fromX = *fromY = *toX = *toY = 0;
3282 *promoChar = NULLCHAR;
3289 InitPosition(redraw)
3292 currentMove = forwardMostMove = backwardMostMove = 0;
3293 switch (gameInfo.variant) {
3295 CopyBoard(boards[0], initialPosition);
3297 case VariantTwoKings:
3298 CopyBoard(boards[0], twoKingsPosition);
3299 startedFromSetupPosition = TRUE;
3301 case VariantWildCastle:
3302 CopyBoard(boards[0], initialPosition);
3303 /* !!?shuffle with kings guaranteed to be on d or e file */
3305 case VariantNoCastle:
3306 CopyBoard(boards[0], initialPosition);
3307 /* !!?unconstrained back-rank shuffle */
3309 case VariantFischeRandom:
3310 CopyBoard(boards[0], initialPosition);
3311 /* !!shuffle according to FR rules */
3315 DrawPosition(FALSE, boards[currentMove]);
3319 SendBoard(cps, moveNum)
3320 ChessProgramState *cps;
3323 char message[MSG_SIZ];
3325 if (cps->useSetboard) {
3326 char* fen = PositionToFEN(moveNum);
3327 sprintf(message, "setboard %s\n", fen);
3328 SendToProgram(message, cps);
3334 /* Kludge to set black to move, avoiding the troublesome and now
3335 * deprecated "black" command.
3337 if (!WhiteOnMove(moveNum)) SendToProgram("a2a3\n", cps);
3339 SendToProgram("edit\n", cps);
3340 SendToProgram("#\n", cps);
3341 for (i = BOARD_SIZE - 1; i >= 0; i--) {
3342 bp = &boards[moveNum][i][0];
3343 for (j = 0; j < BOARD_SIZE; j++, bp++) {
3344 if ((int) *bp < (int) BlackPawn) {
3345 sprintf(message, "%c%c%c\n", PieceToChar(*bp),
3347 SendToProgram(message, cps);
3352 SendToProgram("c\n", cps);
3353 for (i = BOARD_SIZE - 1; i >= 0; i--) {
3354 bp = &boards[moveNum][i][0];
3355 for (j = 0; j < BOARD_SIZE; j++, bp++) {
3356 if (((int) *bp != (int) EmptySquare)
3357 && ((int) *bp >= (int) BlackPawn)) {
3358 sprintf(message, "%c%c%c\n", ToUpper(PieceToChar(*bp)),
3360 SendToProgram(message, cps);
3365 SendToProgram(".\n", cps);
3370 IsPromotion(fromX, fromY, toX, toY)
3371 int fromX, fromY, toX, toY;
3373 return gameMode != EditPosition &&
3374 fromX >=0 && fromY >= 0 && toX >= 0 && toY >= 0 &&
3375 ((boards[currentMove][fromY][fromX] == WhitePawn && toY == 7) ||
3376 (boards[currentMove][fromY][fromX] == BlackPawn && toY == 0));
3381 PieceForSquare (x, y)
3385 if (x < 0 || x >= BOARD_SIZE || y < 0 || y >= BOARD_SIZE)
3388 return boards[currentMove][y][x];
3392 OKToStartUserMove(x, y)
3395 ChessSquare from_piece;
3398 if (matchMode) return FALSE;
3399 if (gameMode == EditPosition) return TRUE;
3401 if (x >= 0 && y >= 0)
3402 from_piece = boards[currentMove][y][x];
3404 from_piece = EmptySquare;
3406 if (from_piece == EmptySquare) return FALSE;
3408 white_piece = (int)from_piece >= (int)WhitePawn &&
3409 (int)from_piece <= (int)WhiteKing;
3412 case PlayFromGameFile:
3414 case TwoMachinesPlay:
3422 case MachinePlaysWhite:
3423 case IcsPlayingBlack:
3424 if (appData.zippyPlay) return FALSE;
3426 DisplayMoveError(_("You are playing Black"));
3431 case MachinePlaysBlack:
3432 case IcsPlayingWhite:
3433 if (appData.zippyPlay) return FALSE;
3435 DisplayMoveError(_("You are playing White"));
3441 if (!white_piece && WhiteOnMove(currentMove)) {
3442 DisplayMoveError(_("It is White's turn"));
3445 if (white_piece && !WhiteOnMove(currentMove)) {
3446 DisplayMoveError(_("It is Black's turn"));
3449 if (cmailMsgLoaded && (currentMove < cmailOldMove)) {
3450 /* Editing correspondence game history */
3451 /* Could disallow this or prompt for confirmation */
3454 if (currentMove < forwardMostMove) {
3455 /* Discarding moves */
3456 /* Could prompt for confirmation here,
3457 but I don't think that's such a good idea */
3458 forwardMostMove = currentMove;
3462 case BeginningOfGame:
3463 if (appData.icsActive) return FALSE;
3464 if (!appData.noChessProgram) {
3466 DisplayMoveError(_("You are playing White"));
3473 if (!white_piece && WhiteOnMove(currentMove)) {
3474 DisplayMoveError(_("It is White's turn"));
3477 if (white_piece && !WhiteOnMove(currentMove)) {
3478 DisplayMoveError(_("It is Black's turn"));
3487 if (currentMove != forwardMostMove && gameMode != AnalyzeMode
3488 && gameMode != AnalyzeFile && gameMode != Training) {
3489 DisplayMoveError(_("Displayed position is not current"));
3495 FILE *lastLoadGameFP = NULL, *lastLoadPositionFP = NULL;
3496 int lastLoadGameNumber = 0, lastLoadPositionNumber = 0;
3497 int lastLoadGameUseList = FALSE;
3498 char lastLoadGameTitle[MSG_SIZ], lastLoadPositionTitle[MSG_SIZ];
3499 ChessMove lastLoadGameStart = (ChessMove) 0;
3503 UserMoveEvent(fromX, fromY, toX, toY, promoChar)
3504 int fromX, fromY, toX, toY;
3509 if (fromX < 0 || fromY < 0) return;
3510 if ((fromX == toX) && (fromY == toY)) {
3514 /* Check if the user is playing in turn. This is complicated because we
3515 let the user "pick up" a piece before it is his turn. So the piece he
3516 tried to pick up may have been captured by the time he puts it down!
3517 Therefore we use the color the user is supposed to be playing in this
3518 test, not the color of the piece that is currently on the starting
3519 square---except in EditGame mode, where the user is playing both
3520 sides; fortunately there the capture race can't happen. (It can
3521 now happen in IcsExamining mode, but that's just too bad. The user
3522 will get a somewhat confusing message in that case.)
3526 case PlayFromGameFile:
3528 case TwoMachinesPlay:
3532 /* We switched into a game mode where moves are not accepted,
3533 perhaps while the mouse button was down. */
3536 case MachinePlaysWhite:
3537 /* User is moving for Black */
3538 if (WhiteOnMove(currentMove)) {
3539 DisplayMoveError(_("It is White's turn"));
3544 case MachinePlaysBlack:
3545 /* User is moving for White */
3546 if (!WhiteOnMove(currentMove)) {
3547 DisplayMoveError(_("It is Black's turn"));
3554 case BeginningOfGame:
3557 if ((int) boards[currentMove][fromY][fromX] >= (int) BlackPawn &&
3558 (int) boards[currentMove][fromY][fromX] <= (int) BlackKing) {
3559 /* User is moving for Black */
3560 if (WhiteOnMove(currentMove)) {
3561 DisplayMoveError(_("It is White's turn"));
3565 /* User is moving for White */
3566 if (!WhiteOnMove(currentMove)) {
3567 DisplayMoveError(_("It is Black's turn"));
3573 case IcsPlayingBlack:
3574 /* User is moving for Black */
3575 if (WhiteOnMove(currentMove)) {
3576 if (!appData.premove) {
3577 DisplayMoveError(_("It is White's turn"));
3578 } else if (toX >= 0 && toY >= 0) {
3581 premoveFromX = fromX;
3582 premoveFromY = fromY;
3583 premovePromoChar = promoChar;
3585 if (appData.debugMode)
3586 fprintf(debugFP, "Got premove: fromX %d,"
3587 "fromY %d, toX %d, toY %d\n",
3588 fromX, fromY, toX, toY);
3594 case IcsPlayingWhite:
3595 /* User is moving for White */
3596 if (!WhiteOnMove(currentMove)) {
3597 if (!appData.premove) {
3598 DisplayMoveError(_("It is Black's turn"));
3599 } else if (toX >= 0 && toY >= 0) {
3602 premoveFromX = fromX;
3603 premoveFromY = fromY;
3604 premovePromoChar = promoChar;
3606 if (appData.debugMode)
3607 fprintf(debugFP, "Got premove: fromX %d,"
3608 "fromY %d, toX %d, toY %d\n",
3609 fromX, fromY, toX, toY);
3619 if (toX == -2 || toY == -2) {
3620 boards[0][fromY][fromX] = EmptySquare;
3621 DrawPosition(FALSE, boards[currentMove]);
3622 } else if (toX >= 0 && toY >= 0) {
3623 boards[0][toY][toX] = boards[0][fromY][fromX];
3624 boards[0][fromY][fromX] = EmptySquare;
3625 DrawPosition(FALSE, boards[currentMove]);
3630 if (toX < 0 || toY < 0) return;
3631 userOfferedDraw = FALSE;
3633 if (appData.testLegality) {
3634 moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
3635 EP_UNKNOWN, fromY, fromX, toY, toX, promoChar);
3636 if (moveType == IllegalMove || moveType == ImpossibleMove) {
3637 DisplayMoveError(_("Illegal move"));
3641 moveType = PromoCharToMoveType(WhiteOnMove(currentMove), promoChar);
3644 if (gameMode == Training) {
3645 /* compare the move played on the board to the next move in the
3646 * game. If they match, display the move and the opponent's response.
3647 * If they don't match, display an error message.
3651 CopyBoard(testBoard, boards[currentMove]);
3652 ApplyMove(fromX, fromY, toX, toY, promoChar, testBoard);
3654 if (CompareBoards(testBoard, boards[currentMove+1])) {
3655 ForwardInner(currentMove+1);
3657 /* Autoplay the opponent's response.
3658 * if appData.animate was TRUE when Training mode was entered,
3659 * the response will be animated.
3661 saveAnimate = appData.animate;
3662 appData.animate = animateTraining;
3663 ForwardInner(currentMove+1);
3664 appData.animate = saveAnimate;
3666 /* check for the end of the game */
3667 if (currentMove >= forwardMostMove) {
3668 gameMode = PlayFromGameFile;
3670 SetTrainingModeOff();
3671 DisplayInformation(_("End of game"));
3674 DisplayError(_("Incorrect move"), 0);
3679 FinishMove(moveType, fromX, fromY, toX, toY, promoChar);
3682 /* Common tail of UserMoveEvent and DropMenuEvent */
3684 FinishMove(moveType, fromX, fromY, toX, toY, promoChar)
3686 int fromX, fromY, toX, toY;
3687 /*char*/int promoChar;
3689 /* Ok, now we know that the move is good, so we can kill
3690 the previous line in Analysis Mode */
3691 if (gameMode == AnalyzeMode && currentMove < forwardMostMove) {
3692 forwardMostMove = currentMove;
3695 /* If we need the chess program but it's dead, restart it */
3696 ResurrectChessProgram();
3698 /* A user move restarts a paused game*/
3702 thinkOutput[0] = NULLCHAR;
3704 MakeMove(fromX, fromY, toX, toY, promoChar); /*updates forwardMostMove*/
3706 if (gameMode == BeginningOfGame) {
3707 if (appData.noChessProgram) {
3708 gameMode = EditGame;
3712 gameMode = MachinePlaysBlack;
3714 sprintf(buf, "%s vs. %s", gameInfo.white, gameInfo.black);
3716 if (first.sendName) {
3717 sprintf(buf, "name %s\n", gameInfo.white);
3718 SendToProgram(buf, &first);
3724 /* Relay move to ICS or chess engine */
3725 if (appData.icsActive) {
3726 if (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
3727 gameMode == IcsExamining) {
3728 SendMoveToICS(moveType, fromX, fromY, toX, toY);
3732 if (first.sendTime && (gameMode == BeginningOfGame ||
3733 gameMode == MachinePlaysWhite ||
3734 gameMode == MachinePlaysBlack)) {
3735 SendTimeRemaining(&first, gameMode != MachinePlaysBlack);
3737 SendMoveToProgram(forwardMostMove-1, &first);
3738 if (gameMode != EditGame && gameMode != PlayFromGameFile) {
3739 first.maybeThinking = TRUE;
3741 if (currentMove == cmailOldMove + 1) {
3742 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
3746 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
3750 switch (MateTest(boards[currentMove], PosFlags(currentMove),
3756 if (WhiteOnMove(currentMove)) {
3757 GameEnds(BlackWins, "Black mates", GE_PLAYER);
3759 GameEnds(WhiteWins, "White mates", GE_PLAYER);
3763 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
3768 case MachinePlaysBlack:
3769 case MachinePlaysWhite:
3770 /* disable certain menu options while machine is thinking */
3771 SetMachineThinkingEnables();
3780 HandleMachineMove(message, cps)
3782 ChessProgramState *cps;
3784 char machineMove[MSG_SIZ], buf1[MSG_SIZ*10], buf2[MSG_SIZ];
3785 char realname[MSG_SIZ];
3786 int fromX, fromY, toX, toY;
3793 * Kludge to ignore BEL characters
3795 while (*message == '\007') message++;
3798 * Look for book output
3800 if (cps == &first && bookRequested) {
3801 if (message[0] == '\t' || message[0] == ' ') {
3802 /* Part of the book output is here; append it */
3803 strcat(bookOutput, message);
3804 strcat(bookOutput, " \n");
3806 } else if (bookOutput[0] != NULLCHAR) {
3807 /* All of book output has arrived; display it */
3808 char *p = bookOutput;
3809 while (*p != NULLCHAR) {
3810 if (*p == '\t') *p = ' ';
3813 DisplayInformation(bookOutput);
3814 bookRequested = FALSE;
3815 /* Fall through to parse the current output */
3820 * Look for machine move.
3822 if ((sscanf(message, "%s %s %s", buf1, buf2, machineMove) == 3 &&
3823 strcmp(buf2, "...") == 0) ||
3824 (sscanf(message, "%s %s", buf1, machineMove) == 2 &&
3825 strcmp(buf1, "move") == 0)) {
3827 /* This method is only useful on engines that support ping */
3828 if (cps->lastPing != cps->lastPong) {
3829 if (gameMode == BeginningOfGame) {
3830 /* Extra move from before last new; ignore */
3831 if (appData.debugMode) {
3832 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
3835 if (appData.debugMode) {
3836 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
3837 cps->which, gameMode);
3839 SendToProgram("undo\n", cps);
3845 case BeginningOfGame:
3846 /* Extra move from before last reset; ignore */
3847 if (appData.debugMode) {
3848 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
3855 /* Extra move after we tried to stop. The mode test is
3856 not a reliable way of detecting this problem, but it's
3857 the best we can do on engines that don't support ping.
3859 if (appData.debugMode) {
3860 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
3861 cps->which, gameMode);
3863 SendToProgram("undo\n", cps);
3866 case MachinePlaysWhite:
3867 case IcsPlayingWhite:
3868 machineWhite = TRUE;
3871 case MachinePlaysBlack:
3872 case IcsPlayingBlack:
3873 machineWhite = FALSE;
3876 case TwoMachinesPlay:
3877 machineWhite = (cps->twoMachinesColor[0] == 'w');
3880 if (WhiteOnMove(forwardMostMove) != machineWhite) {
3881 if (appData.debugMode) {
3883 "Ignoring move out of turn by %s, gameMode %d"
3884 ", forwardMost %d\n",
3885 cps->which, gameMode, forwardMostMove);
3890 if (!ParseOneMove(machineMove, forwardMostMove, &moveType,
3891 &fromX, &fromY, &toX, &toY, &promoChar)) {
3892 /* Machine move could not be parsed; ignore it. */
3893 sprintf(buf1, _("Illegal move \"%s\" from %s machine"),
3894 machineMove, cps->which);
3895 DisplayError(buf1, 0);
3896 if (gameMode == TwoMachinesPlay) {
3897 GameEnds(machineWhite ? BlackWins : WhiteWins,
3898 "Forfeit due to illegal move", GE_XBOARD);
3903 hintRequested = FALSE;
3904 lastHint[0] = NULLCHAR;
3905 bookRequested = FALSE;
3906 /* Program may be pondering now */
3907 cps->maybeThinking = TRUE;
3908 if (cps->sendTime == 2) cps->sendTime = 1;
3909 if (cps->offeredDraw) cps->offeredDraw--;
3912 if ((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack) &&
3914 SendMoveToICS(moveType, fromX, fromY, toX, toY);
3918 /* currentMoveString is set as a side-effect of ParseOneMove */
3919 strcpy(machineMove, currentMoveString);
3920 strcat(machineMove, "\n");
3921 strcpy(moveList[forwardMostMove], machineMove);
3923 MakeMove(fromX, fromY, toX, toY, promoChar);/*updates forwardMostMove*/
3925 if (gameMode == TwoMachinesPlay) {
3926 if (cps->other->sendTime) {
3927 SendTimeRemaining(cps->other,
3928 cps->other->twoMachinesColor[0] == 'w');
3930 SendMoveToProgram(forwardMostMove-1, cps->other);
3933 if (cps->other->useColors) {
3934 SendToProgram(cps->other->twoMachinesColor, cps->other);
3936 SendToProgram("go\n", cps->other);
3938 cps->other->maybeThinking = TRUE;
3941 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
3942 if (!pausing && appData.ringBellAfterMoves) {
3946 * Reenable menu items that were disabled while
3947 * machine was thinking
3949 if (gameMode != TwoMachinesPlay)
3950 SetUserThinkingEnables();
3954 /* Set special modes for chess engines. Later something general
3955 * could be added here; for now there is just one kludge feature,
3956 * needed because Crafty 15.10 and earlier don't ignore SIGINT
3957 * when "xboard" is given as an interactive command.
3959 if (strncmp(message, "kibitz Hello from Crafty", 24) == 0) {
3960 cps->useSigint = FALSE;
3961 cps->useSigterm = FALSE;
3965 * Look for communication commands
3967 if (!strncmp(message, "telluser ", 9)) {
3968 DisplayNote(message + 9);
3971 if (!strncmp(message, "tellusererror ", 14)) {
3972 DisplayError(message + 14, 0);
3975 if (!strncmp(message, "tellopponent ", 13)) {
3976 if (appData.icsActive) {
3978 sprintf(buf1, "%ssay %s\n", ics_prefix, message + 13);
3982 DisplayNote(message + 13);
3986 if (!strncmp(message, "tellothers ", 11)) {
3987 if (appData.icsActive) {
3989 sprintf(buf1, "%swhisper %s\n", ics_prefix, message + 11);
3995 if (!strncmp(message, "tellall ", 8)) {
3996 if (appData.icsActive) {
3998 sprintf(buf1, "%skibitz %s\n", ics_prefix, message + 8);
4002 DisplayNote(message + 8);
4006 if (strncmp(message, "warning", 7) == 0) {
4007 /* Undocumented feature, use tellusererror in new code */
4008 DisplayError(message, 0);
4011 if (sscanf(message, "askuser %s %[^\n]", buf1, buf2) == 2) {
4012 strcpy(realname, cps->tidy);
4013 strcat(realname, " query");
4014 AskQuestion(realname, buf2, buf1, cps->pr);
4017 /* Commands from the engine directly to ICS. We don't allow these to be
4018 * sent until we are logged on. Crafty kibitzes have been known to
4019 * interfere with the login process.
4022 if (!strncmp(message, "tellics ", 8)) {
4023 SendToICS(message + 8);
4027 if (!strncmp(message, "tellicsnoalias ", 15)) {
4028 SendToICS(ics_prefix);
4029 SendToICS(message + 15);
4033 /* The following are for backward compatibility only */
4034 if (!strncmp(message,"whisper",7) || !strncmp(message,"kibitz",6) ||
4035 !strncmp(message,"draw",4) || !strncmp(message,"tell",3)) {
4036 SendToICS(ics_prefix);
4042 if (strncmp(message, "feature ", 8) == 0) {
4043 ParseFeatures(message+8, cps);
4045 if (sscanf(message, "pong %d", &cps->lastPong) == 1) {
4049 * If the move is illegal, cancel it and redraw the board.
4050 * Also deal with other error cases. Matching is rather loose
4051 * here to accommodate engines written before the spec.
4053 if (strncmp(message + 1, "llegal move", 11) == 0 ||
4054 strncmp(message, "Error", 5) == 0) {
4055 if (StrStr(message, "name") ||
4056 StrStr(message, "rating") || StrStr(message, "?") ||
4057 StrStr(message, "result") || StrStr(message, "board") ||
4058 StrStr(message, "bk") || StrStr(message, "computer") ||
4059 StrStr(message, "variant") || StrStr(message, "hint") ||
4060 StrStr(message, "random") || StrStr(message, "depth") ||
4061 StrStr(message, "accepted")) {
4064 if (StrStr(message, "protover")) {
4065 /* Program is responding to input, so it's apparently done
4066 initializing, and this error message indicates it is
4067 protocol version 1. So we don't need to wait any longer
4068 for it to initialize and send feature commands. */
4069 FeatureDone(cps, 1);
4070 cps->protocolVersion = 1;
4073 cps->maybeThinking = FALSE;
4075 if (StrStr(message, "draw")) {
4076 /* Program doesn't have "draw" command */
4077 cps->sendDrawOffers = 0;
4080 if (cps->sendTime != 1 &&
4081 (StrStr(message, "time") || StrStr(message, "otim"))) {
4082 /* Program apparently doesn't have "time" or "otim" command */
4086 if (StrStr(message, "analyze")) {
4087 cps->analysisSupport = FALSE;
4088 cps->analyzing = FALSE;
4090 sprintf(buf2, "%s does not support analysis", cps->tidy);
4091 DisplayError(buf2, 0);
4094 if (StrStr(message, "(no matching move)st")) {
4095 /* Special kludge for GNU Chess 4 only */
4096 cps->stKludge = TRUE;
4097 SendTimeControl(cps, movesPerSession, timeControl,
4098 timeIncrement, appData.searchDepth,
4102 if (StrStr(message, "(no matching move)sd")) {
4103 /* Special kludge for GNU Chess 4 only */
4104 cps->sdKludge = TRUE;
4105 SendTimeControl(cps, movesPerSession, timeControl,
4106 timeIncrement, appData.searchDepth,
4110 if (!StrStr(message, "llegal")) return;
4111 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
4112 gameMode == IcsIdle) return;
4113 if (forwardMostMove <= backwardMostMove) return;
4115 /* Following removed: it caused a bug where a real illegal move
4116 message in analyze mored would be ignored. */
4117 if (cps == &first && programStats.ok_to_send == 0) {
4118 /* Bogus message from Crafty responding to "." This filtering
4119 can miss some of the bad messages, but fortunately the bug
4120 is fixed in current Crafty versions, so it doesn't matter. */
4124 if (pausing) PauseEvent();
4125 if (gameMode == PlayFromGameFile) {
4126 /* Stop reading this game file */
4127 gameMode = EditGame;
4130 currentMove = --forwardMostMove;
4131 DisplayMove(currentMove-1); /* before DisplayMoveError */
4133 DisplayBothClocks();
4134 sprintf(buf1, _("Illegal move \"%s\" (rejected by %s chess program)"),
4135 parseList[currentMove], cps->which);
4136 DisplayMoveError(buf1);
4137 DrawPosition(FALSE, boards[currentMove]);
4140 if (strncmp(message, "time", 4) == 0 && StrStr(message, "Illegal")) {
4141 /* Program has a broken "time" command that
4142 outputs a string not ending in newline.
4148 * If chess program startup fails, exit with an error message.
4149 * Attempts to recover here are futile.
4151 if ((StrStr(message, "unknown host") != NULL)
4152 || (StrStr(message, "No remote directory") != NULL)
4153 || (StrStr(message, "not found") != NULL)
4154 || (StrStr(message, "No such file") != NULL)
4155 || (StrStr(message, "can't alloc") != NULL)
4156 || (StrStr(message, "Permission denied") != NULL)) {
4158 cps->maybeThinking = FALSE;
4159 sprintf(buf1, _("Failed to start %s chess program %s on %s: %s\n"),
4160 cps->which, cps->program, cps->host, message);
4161 RemoveInputSource(cps->isr);
4162 DisplayFatalError(buf1, 0, 1);
4167 * Look for hint output
4169 if (sscanf(message, "Hint: %s", buf1) == 1) {
4170 if (cps == &first && hintRequested) {
4171 hintRequested = FALSE;
4172 if (ParseOneMove(buf1, forwardMostMove, &moveType,
4173 &fromX, &fromY, &toX, &toY, &promoChar)) {
4174 (void) CoordsToAlgebraic(boards[forwardMostMove],
4175 PosFlags(forwardMostMove), EP_UNKNOWN,
4176 fromY, fromX, toY, toX, promoChar, buf1);
4177 sprintf(buf2, "Hint: %s", buf1);
4178 DisplayInformation(buf2);
4180 /* Hint move could not be parsed!? */
4182 _("Illegal hint move \"%s\"\nfrom %s chess program"),
4184 DisplayError(buf2, 0);
4187 strcpy(lastHint, buf1);
4193 * Ignore other messages if game is not in progress
4195 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
4196 gameMode == IcsIdle || cps->lastPing != cps->lastPong) return;
4199 * look for win, lose, draw, or draw offer
4201 if (strncmp(message, "1-0", 3) == 0) {
4202 char *p, *q, *r = "";
4203 p = strchr(message, '{');
4211 GameEnds(WhiteWins, r, GE_ENGINE);
4213 } else if (strncmp(message, "0-1", 3) == 0) {
4214 char *p, *q, *r = "";
4215 p = strchr(message, '{');
4223 /* Kludge for Arasan 4.1 bug */
4224 if (strcmp(r, "Black resigns") == 0) {
4225 GameEnds(WhiteWins, r, GE_ENGINE);
4228 GameEnds(BlackWins, r, GE_ENGINE);
4230 } else if (strncmp(message, "1/2", 3) == 0) {
4231 char *p, *q, *r = "";
4232 p = strchr(message, '{');
4240 GameEnds(GameIsDrawn, r, GE_ENGINE);
4243 } else if (strncmp(message, "White resign", 12) == 0) {
4244 GameEnds(BlackWins, "White resigns", GE_ENGINE);
4246 } else if (strncmp(message, "Black resign", 12) == 0) {
4247 GameEnds(WhiteWins, "Black resigns", GE_ENGINE);
4249 } else if (strncmp(message, "White", 5) == 0 &&
4250 message[5] != '(' &&
4251 StrStr(message, "Black") == NULL) {
4252 GameEnds(WhiteWins, "White mates", GE_ENGINE);
4254 } else if (strncmp(message, "Black", 5) == 0 &&
4255 message[5] != '(') {
4256 GameEnds(BlackWins, "Black mates", GE_ENGINE);
4258 } else if (strcmp(message, "resign") == 0 ||
4259 strcmp(message, "computer resigns") == 0) {
4261 case MachinePlaysBlack:
4262 case IcsPlayingBlack:
4263 GameEnds(WhiteWins, "Black resigns", GE_ENGINE);
4265 case MachinePlaysWhite:
4266 case IcsPlayingWhite:
4267 GameEnds(BlackWins, "White resigns", GE_ENGINE);
4269 case TwoMachinesPlay:
4270 if (cps->twoMachinesColor[0] == 'w')
4271 GameEnds(BlackWins, "White resigns", GE_ENGINE);
4273 GameEnds(WhiteWins, "Black resigns", GE_ENGINE);
4280 } else if (strncmp(message, "opponent mates", 14) == 0) {
4282 case MachinePlaysBlack:
4283 case IcsPlayingBlack:
4284 GameEnds(WhiteWins, "White mates", GE_ENGINE);
4286 case MachinePlaysWhite:
4287 case IcsPlayingWhite:
4288 GameEnds(BlackWins, "Black mates", GE_ENGINE);
4290 case TwoMachinesPlay:
4291 if (cps->twoMachinesColor[0] == 'w')
4292 GameEnds(BlackWins, "Black mates", GE_ENGINE);
4294 GameEnds(WhiteWins, "White mates", GE_ENGINE);
4301 } else if (strncmp(message, "computer mates", 14) == 0) {
4303 case MachinePlaysBlack:
4304 case IcsPlayingBlack:
4305 GameEnds(BlackWins, "Black mates", GE_ENGINE);
4307 case MachinePlaysWhite:
4308 case IcsPlayingWhite:
4309 GameEnds(WhiteWins, "White mates", GE_ENGINE);
4311 case TwoMachinesPlay:
4312 if (cps->twoMachinesColor[0] == 'w')
4313 GameEnds(WhiteWins, "White mates", GE_ENGINE);
4315 GameEnds(BlackWins, "Black mates", GE_ENGINE);
4322 } else if (strncmp(message, "checkmate", 9) == 0) {
4323 if (WhiteOnMove(forwardMostMove)) {
4324 GameEnds(BlackWins, "Black mates", GE_ENGINE);
4326 GameEnds(WhiteWins, "White mates", GE_ENGINE);
4329 } else if (strstr(message, "Draw") != NULL ||
4330 strstr(message, "game is a draw") != NULL) {
4331 GameEnds(GameIsDrawn, "Draw", GE_ENGINE);
4333 } else if (strstr(message, "offer") != NULL &&
4334 strstr(message, "draw") != NULL) {
4336 if (appData.zippyPlay && first.initDone) {
4337 /* Relay offer to ICS */
4338 SendToICS(ics_prefix);
4339 SendToICS("draw\n");
4342 cps->offeredDraw = 2; /* valid until this engine moves twice */
4343 if (gameMode == TwoMachinesPlay) {
4344 if (cps->other->offeredDraw) {
4345 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
4347 if (cps->other->sendDrawOffers) {
4348 SendToProgram("draw\n", cps->other);
4351 } else if (gameMode == MachinePlaysWhite ||
4352 gameMode == MachinePlaysBlack) {
4353 if (userOfferedDraw) {
4354 DisplayInformation(_("Machine accepts your draw offer"));
4355 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
4357 DisplayInformation(_("Machine offers a draw\nSelect Action / Draw to agree"));
4364 * Look for thinking output
4366 if (appData.showThinking) {
4367 int plylev, mvleft, mvtot, curscore, time;
4368 char mvname[MOVE_LEN];
4372 int prefixHint = FALSE;
4373 mvname[0] = NULLCHAR;
4376 case MachinePlaysBlack:
4377 case IcsPlayingBlack:
4378 if (WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
4380 case MachinePlaysWhite:
4381 case IcsPlayingWhite:
4382 if (!WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
4387 case TwoMachinesPlay:
4388 if ((cps->twoMachinesColor[0] == 'w') !=
4389 WhiteOnMove(forwardMostMove)) {
4400 if (sscanf(message, "%d%c %d %d" u64Display "%[^\n]\n",
4401 &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5) {
4403 if (plyext != ' ' && plyext != '\t') {
4406 programStats.depth = plylev;
4407 programStats.nodes = nodes;
4408 programStats.time = time;
4409 programStats.score = curscore;
4410 programStats.got_only_move = 0;
4412 /* Buffer overflow protection */
4413 if (buf1[0] != NULLCHAR) {
4414 if (strlen(buf1) >= sizeof(programStats.movelist)
4415 && appData.debugMode) {
4417 "PV is too long; using the first %d bytes.\n",
4418 sizeof(programStats.movelist) - 1);
4420 strncpy(programStats.movelist, buf1,
4421 sizeof(programStats.movelist));
4422 programStats.movelist[sizeof(programStats.movelist) - 1]
4425 sprintf(programStats.movelist, " no PV\n");
4428 if (programStats.seen_stat) {
4429 programStats.ok_to_send = 1;
4432 if (strchr(programStats.movelist, '(') != NULL) {
4433 programStats.line_is_book = 1;
4434 programStats.nr_moves = 0;
4435 programStats.moves_left = 0;
4437 programStats.line_is_book = 0;
4440 sprintf(thinkOutput, "[%d]%c%+.2f %s%s%s",
4442 (gameMode == TwoMachinesPlay ?
4443 ToUpper(cps->twoMachinesColor[0]) : ' '),
4444 ((double) curscore) / 100.0,
4445 prefixHint ? lastHint : "",
4446 prefixHint ? " " : "", buf1);
4448 if (currentMove == forwardMostMove ||
4449 gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
4450 DisplayMove(currentMove - 1);
4455 } else if ((p=StrStr(message, "(only move)")) != NULL) {
4456 /* crafty (9.25+) says "(only move) <move>"
4457 * if there is only 1 legal move
4459 sscanf(p, "(only move) %s", buf1);
4460 sprintf(thinkOutput, "%s (only move)", buf1);
4461 sprintf(programStats.movelist, "%s (only move)", buf1);
4462 programStats.depth = 1;
4463 programStats.nr_moves = 1;
4464 programStats.moves_left = 1;
4465 programStats.nodes = 1;
4466 programStats.time = 1;
4467 programStats.got_only_move = 1;
4469 /* Not really, but we also use this member to
4470 mean "line isn't going to change" (Crafty
4471 isn't searching, so stats won't change) */
4472 programStats.line_is_book = 1;
4474 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
4475 gameMode == AnalyzeFile) {
4476 DisplayMove(currentMove - 1);
4480 } else if (sscanf(message,"stat01: %d" u64Display "%d %d %d %s",
4481 &time, &nodes, &plylev, &mvleft,
4482 &mvtot, mvname) >= 5) {
4483 /* The stat01: line is from Crafty (9.29+) in response
4484 to the "." command */
4485 programStats.seen_stat = 1;
4486 cps->maybeThinking = TRUE;
4488 if (programStats.got_only_move || !appData.periodicUpdates)
4491 programStats.depth = plylev;
4492 programStats.time = time;
4493 programStats.nodes = nodes;
4494 programStats.moves_left = mvleft;
4495 programStats.nr_moves = mvtot;
4496 strcpy(programStats.move_name, mvname);
4497 programStats.ok_to_send = 1;
4501 } else if (strncmp(message,"++",2) == 0) {
4502 /* Crafty 9.29+ outputs this */
4503 programStats.got_fail = 2;
4506 } else if (strncmp(message,"--",2) == 0) {
4507 /* Crafty 9.29+ outputs this */
4508 programStats.got_fail = 1;
4511 } else if (thinkOutput[0] != NULLCHAR &&
4512 strncmp(message, " ", 4) == 0) {
4514 while (*p && *p == ' ') p++;
4515 strcat(thinkOutput, " ");
4516 strcat(thinkOutput, p);
4517 strcat(programStats.movelist, " ");
4518 strcat(programStats.movelist, p);
4519 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
4520 gameMode == AnalyzeFile) {
4521 DisplayMove(currentMove - 1);
4531 /* Parse a game score from the character string "game", and
4532 record it as the history of the current game. The game
4533 score is NOT assumed to start from the standard position.
4534 The display is not updated in any way.
4537 ParseGameHistory(game)
4541 int fromX, fromY, toX, toY, boardIndex;
4546 if (appData.debugMode)
4547 fprintf(debugFP, "Parsing game history: %s\n", game);
4549 if (gameInfo.event == NULL) gameInfo.event = StrSave("ICS game");
4550 gameInfo.site = StrSave(appData.icsHost);
4551 gameInfo.date = PGNDate();
4552 gameInfo.round = StrSave("-");
4554 /* Parse out names of players */
4555 while (*game == ' ') game++;
4557 while (*game != ' ') *p++ = *game++;
4559 gameInfo.white = StrSave(buf);
4560 while (*game == ' ') game++;
4562 while (*game != ' ' && *game != '\n') *p++ = *game++;
4564 gameInfo.black = StrSave(buf);
4567 boardIndex = blackPlaysFirst ? 1 : 0;
4570 yyboardindex = boardIndex;
4571 moveType = (ChessMove) yylex();
4573 case WhitePromotionQueen:
4574 case BlackPromotionQueen:
4575 case WhitePromotionRook:
4576 case BlackPromotionRook:
4577 case WhitePromotionBishop:
4578 case BlackPromotionBishop:
4579 case WhitePromotionKnight:
4580 case BlackPromotionKnight:
4581 case WhitePromotionKing:
4582 case BlackPromotionKing:
4584 case WhiteCapturesEnPassant:
4585 case BlackCapturesEnPassant:
4586 case WhiteKingSideCastle:
4587 case WhiteQueenSideCastle:
4588 case BlackKingSideCastle:
4589 case BlackQueenSideCastle:
4590 case WhiteKingSideCastleWild:
4591 case WhiteQueenSideCastleWild:
4592 case BlackKingSideCastleWild:
4593 case BlackQueenSideCastleWild:
4594 case IllegalMove: /* maybe suicide chess, etc. */
4595 fromX = currentMoveString[0] - 'a';
4596 fromY = currentMoveString[1] - '1';
4597 toX = currentMoveString[2] - 'a';
4598 toY = currentMoveString[3] - '1';
4599 promoChar = currentMoveString[4];
4603 fromX = moveType == WhiteDrop ?
4604 (int) CharToPiece(ToUpper(currentMoveString[0])) :
4605 (int) CharToPiece(ToLower(currentMoveString[0]));
4607 toX = currentMoveString[2] - 'a';
4608 toY = currentMoveString[3] - '1';
4609 promoChar = NULLCHAR;
4613 sprintf(buf, _("Ambiguous move in ICS output: \"%s\""), yy_text);
4614 DisplayError(buf, 0);
4616 case ImpossibleMove:
4618 sprintf(buf, _("Illegal move in ICS output: \"%s\""), yy_text);
4619 DisplayError(buf, 0);
4621 case (ChessMove) 0: /* end of file */
4622 if (boardIndex < backwardMostMove) {
4623 /* Oops, gap. How did that happen? */
4624 DisplayError(_("Gap in move list"), 0);
4627 backwardMostMove = blackPlaysFirst ? 1 : 0;
4628 if (boardIndex > forwardMostMove) {
4629 forwardMostMove = boardIndex;
4633 if (boardIndex > (blackPlaysFirst ? 1 : 0)) {
4634 strcat(parseList[boardIndex-1], " ");
4635 strcat(parseList[boardIndex-1], yy_text);
4647 case GameUnfinished:
4648 if (gameMode == IcsExamining) {
4649 if (boardIndex < backwardMostMove) {
4650 /* Oops, gap. How did that happen? */
4653 backwardMostMove = blackPlaysFirst ? 1 : 0;
4656 gameInfo.result = moveType;
4657 p = strchr(yy_text, '{');
4658 if (p == NULL) p = strchr(yy_text, '(');
4661 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
4663 q = strchr(p, *p == '{' ? '}' : ')');
4664 if (q != NULL) *q = NULLCHAR;
4667 gameInfo.resultDetails = StrSave(p);
4670 if (boardIndex >= forwardMostMove &&
4671 !(gameMode == IcsObserving && ics_gamenum == -1)) {
4672 backwardMostMove = blackPlaysFirst ? 1 : 0;
4675 (void) CoordsToAlgebraic(boards[boardIndex], PosFlags(boardIndex),
4676 EP_UNKNOWN, fromY, fromX, toY, toX, promoChar,
4677 parseList[boardIndex]);
4678 CopyBoard(boards[boardIndex + 1], boards[boardIndex]);
4679 /* currentMoveString is set as a side-effect of yylex */
4680 strcpy(moveList[boardIndex], currentMoveString);
4681 strcat(moveList[boardIndex], "\n");
4683 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[boardIndex]);
4684 switch (MateTest(boards[boardIndex],
4685 PosFlags(boardIndex), EP_UNKNOWN)) {
4691 strcat(parseList[boardIndex - 1], "+");
4694 strcat(parseList[boardIndex - 1], "#");
4701 /* Apply a move to the given board */
4703 ApplyMove(fromX, fromY, toX, toY, promoChar, board)
4704 int fromX, fromY, toX, toY;
4708 ChessSquare captured = board[toY][toX];
4709 if (fromY == DROP_RANK) {
4711 board[toY][toX] = (ChessSquare) fromX;
4712 } else if (fromX == toX && fromY == toY) {
4714 } else if (fromY == 0 && fromX == 4
4715 && board[fromY][fromX] == WhiteKing
4716 && toY == 0 && toX == 6) {
4717 board[fromY][fromX] = EmptySquare;
4718 board[toY][toX] = WhiteKing;
4719 board[fromY][7] = EmptySquare;
4720 board[toY][5] = WhiteRook;
4721 } else if (fromY == 0 && fromX == 4
4722 && board[fromY][fromX] == WhiteKing
4723 && toY == 0 && toX == 2) {
4724 board[fromY][fromX] = EmptySquare;
4725 board[toY][toX] = WhiteKing;
4726 board[fromY][0] = EmptySquare;
4727 board[toY][3] = WhiteRook;
4728 } else if (fromY == 0 && fromX == 3
4729 && board[fromY][fromX] == WhiteKing
4730 && toY == 0 && toX == 5) {
4731 board[fromY][fromX] = EmptySquare;
4732 board[toY][toX] = WhiteKing;
4733 board[fromY][7] = EmptySquare;
4734 board[toY][4] = WhiteRook;
4735 } else if (fromY == 0 && fromX == 3
4736 && board[fromY][fromX] == WhiteKing
4737 && toY == 0 && toX == 1) {
4738 board[fromY][fromX] = EmptySquare;
4739 board[toY][toX] = WhiteKing;
4740 board[fromY][0] = EmptySquare;
4741 board[toY][2] = WhiteRook;
4742 } else if (board[fromY][fromX] == WhitePawn
4744 /* white pawn promotion */
4745 board[7][toX] = CharToPiece(ToUpper(promoChar));
4746 if (board[7][toX] == EmptySquare) {
4747 board[7][toX] = WhiteQueen;
4749 board[fromY][fromX] = EmptySquare;
4750 } else if ((fromY == 4)
4752 && (board[fromY][fromX] == WhitePawn)
4753 && (board[toY][toX] == EmptySquare)) {
4754 board[fromY][fromX] = EmptySquare;
4755 board[toY][toX] = WhitePawn;
4756 captured = board[toY - 1][toX];
4757 board[toY - 1][toX] = EmptySquare;
4758 } else if (fromY == 7 && fromX == 4
4759 && board[fromY][fromX] == BlackKing
4760 && toY == 7 && toX == 6) {
4761 board[fromY][fromX] = EmptySquare;
4762 board[toY][toX] = BlackKing;
4763 board[fromY][7] = EmptySquare;
4764 board[toY][5] = BlackRook;
4765 } else if (fromY == 7 && fromX == 4
4766 && board[fromY][fromX] == BlackKing
4767 && toY == 7 && toX == 2) {
4768 board[fromY][fromX] = EmptySquare;
4769 board[toY][toX] = BlackKing;
4770 board[fromY][0] = EmptySquare;
4771 board[toY][3] = BlackRook;
4772 } else if (fromY == 7 && fromX == 3
4773 && board[fromY][fromX] == BlackKing
4774 && toY == 7 && toX == 5) {
4775 board[fromY][fromX] = EmptySquare;
4776 board[toY][toX] = BlackKing;
4777 board[fromY][7] = EmptySquare;
4778 board[toY][4] = BlackRook;
4779 } else if (fromY == 7 && fromX == 3
4780 && board[fromY][fromX] == BlackKing
4781 && toY == 7 && toX == 1) {
4782 board[fromY][fromX] = EmptySquare;
4783 board[toY][toX] = BlackKing;
4784 board[fromY][0] = EmptySquare;
4785 board[toY][2] = BlackRook;
4786 } else if (board[fromY][fromX] == BlackPawn
4788 /* black pawn promotion */
4789 board[0][toX] = CharToPiece(ToLower(promoChar));
4790 if (board[0][toX] == EmptySquare) {
4791 board[0][toX] = BlackQueen;
4793 board[fromY][fromX] = EmptySquare;
4794 } else if ((fromY == 3)
4796 && (board[fromY][fromX] == BlackPawn)
4797 && (board[toY][toX] == EmptySquare)) {
4798 board[fromY][fromX] = EmptySquare;
4799 board[toY][toX] = BlackPawn;
4800 captured = board[toY + 1][toX];
4801 board[toY + 1][toX] = EmptySquare;
4803 board[toY][toX] = board[fromY][fromX];
4804 board[fromY][fromX] = EmptySquare;
4806 if (gameInfo.variant == VariantCrazyhouse) {
4808 /* !!A lot more code needs to be written to support holdings */
4809 if (fromY == DROP_RANK) {
4810 /* Delete from holdings */
4811 if (holdings[(int) fromX] > 0) holdings[(int) fromX]--;
4813 if (captured != EmptySquare) {
4814 /* Add to holdings */
4815 if (captured < BlackPawn) {
4816 holdings[(int)captured - (int)BlackPawn + (int)WhitePawn]++;
4818 holdings[(int)captured - (int)WhitePawn + (int)BlackPawn]++;
4822 } else if (gameInfo.variant == VariantAtomic) {
4823 if (captured != EmptySquare) {
4825 for (y = toY-1; y <= toY+1; y++) {
4826 for (x = toX-1; x <= toX+1; x++) {
4827 if (y >= 0 && y <= 7 && x >= 0 && x <= 7 &&
4828 board[y][x] != WhitePawn && board[y][x] != BlackPawn) {
4829 board[y][x] = EmptySquare;
4833 board[toY][toX] = EmptySquare;
4838 /* Updates forwardMostMove */
4840 MakeMove(fromX, fromY, toX, toY, promoChar)
4841 int fromX, fromY, toX, toY;
4845 if (forwardMostMove >= MAX_MOVES) {
4846 DisplayFatalError(_("Game too long; increase MAX_MOVES and recompile"),
4851 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
4852 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
4853 if (commentList[forwardMostMove] != NULL) {
4854 free(commentList[forwardMostMove]);
4855 commentList[forwardMostMove] = NULL;
4857 CopyBoard(boards[forwardMostMove], boards[forwardMostMove - 1]);
4858 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[forwardMostMove]);
4859 gameInfo.result = GameUnfinished;
4860 if (gameInfo.resultDetails != NULL) {
4861 free(gameInfo.resultDetails);
4862 gameInfo.resultDetails = NULL;
4864 CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar,
4865 moveList[forwardMostMove - 1]);
4866 (void) CoordsToAlgebraic(boards[forwardMostMove - 1],
4867 PosFlags(forwardMostMove - 1), EP_UNKNOWN,
4868 fromY, fromX, toY, toX, promoChar,
4869 parseList[forwardMostMove - 1]);
4870 switch (MateTest(boards[forwardMostMove],
4871 PosFlags(forwardMostMove), EP_UNKNOWN)){
4877 strcat(parseList[forwardMostMove - 1], "+");
4880 strcat(parseList[forwardMostMove - 1], "#");
4885 /* Updates currentMove if not pausing */
4887 ShowMove(fromX, fromY, toX, toY)
4889 int instant = (gameMode == PlayFromGameFile) ?
4890 (matchMode || (appData.timeDelay == 0 && !pausing)) : pausing;
4891 if (!pausing || gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
4893 if (forwardMostMove == currentMove + 1) {
4894 AnimateMove(boards[forwardMostMove - 1],
4895 fromX, fromY, toX, toY);
4897 if (appData.highlightLastMove) {
4898 SetHighlights(fromX, fromY, toX, toY);
4901 currentMove = forwardMostMove;
4904 if (instant) return;
4905 DisplayMove(currentMove - 1);
4906 DrawPosition(FALSE, boards[currentMove]);
4907 DisplayBothClocks();
4908 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
4913 InitChessProgram(cps)
4914 ChessProgramState *cps;
4917 if (appData.noChessProgram) return;
4918 hintRequested = FALSE;
4919 bookRequested = FALSE;
4920 SendToProgram(cps->initString, cps);
4921 if (gameInfo.variant != VariantNormal &&
4922 gameInfo.variant != VariantLoadable) {
4923 char *v = VariantName(gameInfo.variant);
4924 if (StrStr(cps->variants, v) == NULL) {
4925 sprintf(buf, _("Variant %s not supported by %s"), v, cps->tidy);
4926 DisplayFatalError(buf, 0, 1);
4929 sprintf(buf, "variant %s\n", VariantName(gameInfo.variant));
4930 SendToProgram(buf, cps);
4933 sprintf(buf, "ics %s\n", appData.icsActive ? appData.icsHost : "-");
4934 SendToProgram(buf, cps);
4936 cps->maybeThinking = FALSE;
4937 cps->offeredDraw = 0;
4938 if (!appData.icsActive) {
4939 SendTimeControl(cps, movesPerSession, timeControl,
4940 timeIncrement, appData.searchDepth,
4943 if (appData.showThinking) {
4944 SendToProgram("post\n", cps);
4946 SendToProgram("hard\n", cps);
4947 if (!appData.ponderNextMove) {
4948 /* Warning: "easy" is a toggle in GNU Chess, so don't send
4949 it without being sure what state we are in first. "hard"
4950 is not a toggle, so that one is OK.
4952 SendToProgram("easy\n", cps);
4955 sprintf(buf, "ping %d\n", ++cps->lastPing);
4956 SendToProgram(buf, cps);
4958 cps->initDone = TRUE;
4963 StartChessProgram(cps)
4964 ChessProgramState *cps;
4969 if (appData.noChessProgram) return;
4970 cps->initDone = FALSE;
4972 if (strcmp(cps->host, "localhost") == 0) {
4973 err = StartChildProcess(cps->program, cps->dir, &cps->pr);
4974 } else if (*appData.remoteShell == NULLCHAR) {
4975 err = OpenRcmd(cps->host, appData.remoteUser, cps->program, &cps->pr);
4977 if (*appData.remoteUser == NULLCHAR) {
4978 sprintf(buf, "%s %s %s", appData.remoteShell, cps->host,
4981 sprintf(buf, "%s %s -l %s %s", appData.remoteShell,
4982 cps->host, appData.remoteUser, cps->program);
4984 err = StartChildProcess(buf, "", &cps->pr);
4988 sprintf(buf, "Startup failure on '%s'", cps->program);
4989 DisplayFatalError(buf, err, 1);
4995 cps->isr = AddInputSource(cps->pr, TRUE, ReceiveFromProgram, cps);
4996 if (cps->protocolVersion > 1) {
4997 sprintf(buf, "xboard\nprotover %d\n", cps->protocolVersion);
4998 SendToProgram(buf, cps);
5000 SendToProgram("xboard\n", cps);
5006 TwoMachinesEventIfReady P((void))
5008 if (first.lastPing != first.lastPong) {
5009 DisplayMessage("", "Waiting for first chess program");
5010 ScheduleDelayedEvent(TwoMachinesEventIfReady, 1000);
5013 if (second.lastPing != second.lastPong) {
5014 DisplayMessage("", "Waiting for second chess program");
5015 ScheduleDelayedEvent(TwoMachinesEventIfReady, 1000);
5023 NextMatchGame P((void))
5026 if (*appData.loadGameFile != NULLCHAR) {
5027 LoadGameFromFile(appData.loadGameFile,
5028 appData.loadGameIndex,
5029 appData.loadGameFile, FALSE);
5030 } else if (*appData.loadPositionFile != NULLCHAR) {
5031 LoadPositionFromFile(appData.loadPositionFile,
5032 appData.loadPositionIndex,
5033 appData.loadPositionFile);
5035 TwoMachinesEventIfReady();
5039 GameEnds(result, resultDetails, whosays)
5041 char *resultDetails;
5044 GameMode nextGameMode;
5047 if (appData.debugMode) {
5048 fprintf(debugFP, "GameEnds(%d, %s, %d)\n",
5049 result, resultDetails ? resultDetails : "(null)", whosays);
5052 if (appData.icsActive && whosays == GE_ENGINE) {
5053 /* If we are playing on ICS, the server decides when the
5054 game is over, but the engine can offer to draw, claim
5058 if (appData.zippyPlay && first.initDone) {
5059 if (result == GameIsDrawn) {
5060 /* In case draw still needs to be claimed */
5061 SendToICS(ics_prefix);
5062 SendToICS("draw\n");
5063 } else if (StrCaseStr(resultDetails, "resign")) {
5064 SendToICS(ics_prefix);
5065 SendToICS("resign\n");
5072 /* If we're loading the game from a file, stop */
5073 if (whosays == GE_FILE) {
5074 (void) StopLoadGameTimer();
5078 /* Cancel draw offers */
5079 first.offeredDraw = second.offeredDraw = 0;
5081 /* If this is an ICS game, only ICS can really say it's done;
5082 if not, anyone can. */
5083 isIcsGame = (gameMode == IcsPlayingWhite ||
5084 gameMode == IcsPlayingBlack ||
5085 gameMode == IcsObserving ||
5086 gameMode == IcsExamining);
5088 if (!isIcsGame || whosays == GE_ICS) {
5089 /* OK -- not an ICS game, or ICS said it was done */
5091 if (!isIcsGame && !appData.noChessProgram)
5092 SetUserThinkingEnables();
5094 if (resultDetails != NULL) {
5095 gameInfo.result = result;
5096 gameInfo.resultDetails = StrSave(resultDetails);
5098 /* Tell program how game ended in case it is learning */
5099 if (gameMode == MachinePlaysWhite ||
5100 gameMode == MachinePlaysBlack ||
5101 gameMode == TwoMachinesPlay ||
5102 gameMode == IcsPlayingWhite ||
5103 gameMode == IcsPlayingBlack ||
5104 gameMode == BeginningOfGame) {
5106 sprintf(buf, "result %s {%s}\n", PGNResult(result),
5108 if (first.pr != NoProc) {
5109 SendToProgram(buf, &first);
5111 if (second.pr != NoProc &&
5112 gameMode == TwoMachinesPlay) {
5113 SendToProgram(buf, &second);
5117 /* display last move only if game was not loaded from file */
5118 if ((whosays != GE_FILE) && (currentMove == forwardMostMove))
5119 DisplayMove(currentMove - 1);
5121 if (forwardMostMove != 0) {
5122 if (gameMode != PlayFromGameFile && gameMode != EditGame) {
5123 if (*appData.saveGameFile != NULLCHAR) {
5124 SaveGameToFile(appData.saveGameFile, TRUE);
5125 } else if (appData.autoSaveGames) {
5128 if (*appData.savePositionFile != NULLCHAR) {
5129 SavePositionToFile(appData.savePositionFile);
5135 if (appData.icsActive) {
5136 if (appData.quietPlay &&
5137 (gameMode == IcsPlayingWhite ||
5138 gameMode == IcsPlayingBlack)) {
5139 SendToICS(ics_prefix);
5140 SendToICS("set shout 1\n");
5142 nextGameMode = IcsIdle;
5143 ics_user_moved = FALSE;
5144 /* clean up premove. It's ugly when the game has ended and the
5145 * premove highlights are still on the board.
5149 ClearPremoveHighlights();
5150 DrawPosition(FALSE, boards[currentMove]);
5152 if (whosays == GE_ICS) {
5155 if (gameMode == IcsPlayingWhite)
5157 else if(gameMode == IcsPlayingBlack)
5161 if (gameMode == IcsPlayingBlack)
5163 else if(gameMode == IcsPlayingWhite)
5170 PlayIcsUnfinishedSound();
5173 } else if (gameMode == EditGame ||
5174 gameMode == PlayFromGameFile ||
5175 gameMode == AnalyzeMode ||
5176 gameMode == AnalyzeFile) {
5177 nextGameMode = gameMode;
5179 nextGameMode = EndOfGame;
5184 nextGameMode = gameMode;
5187 if (appData.noChessProgram) {
5188 gameMode = nextGameMode;
5194 /* Put first chess program into idle state */
5195 if (first.pr != NoProc &&
5196 (gameMode == MachinePlaysWhite ||
5197 gameMode == MachinePlaysBlack ||
5198 gameMode == TwoMachinesPlay ||
5199 gameMode == IcsPlayingWhite ||
5200 gameMode == IcsPlayingBlack ||
5201 gameMode == BeginningOfGame)) {
5202 SendToProgram("force\n", &first);
5203 if (first.usePing) {
5205 sprintf(buf, "ping %d\n", ++first.lastPing);
5206 SendToProgram(buf, &first);
5209 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
5210 /* Kill off first chess program */
5211 if (first.isr != NULL)
5212 RemoveInputSource(first.isr);
5215 if (first.pr != NoProc) {
5217 SendToProgram("quit\n", &first);
5218 DestroyChildProcess(first.pr, first.useSigterm);
5223 /* Put second chess program into idle state */
5224 if (second.pr != NoProc &&
5225 gameMode == TwoMachinesPlay) {
5226 SendToProgram("force\n", &second);
5227 if (second.usePing) {
5229 sprintf(buf, "ping %d\n", ++second.lastPing);
5230 SendToProgram(buf, &second);
5233 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
5234 /* Kill off second chess program */
5235 if (second.isr != NULL)
5236 RemoveInputSource(second.isr);
5239 if (second.pr != NoProc) {
5240 SendToProgram("quit\n", &second);
5241 DestroyChildProcess(second.pr, second.useSigterm);
5246 if (matchMode && gameMode == TwoMachinesPlay) {
5249 if (first.twoMachinesColor[0] == 'w') {
5256 if (first.twoMachinesColor[0] == 'b') {
5265 if (matchGame < appData.matchGames) {
5267 tmp = first.twoMachinesColor;
5268 first.twoMachinesColor = second.twoMachinesColor;
5269 second.twoMachinesColor = tmp;
5270 gameMode = nextGameMode;
5272 ScheduleDelayedEvent(NextMatchGame, 10000);
5276 gameMode = nextGameMode;
5277 sprintf(buf, _("Match %s vs. %s: final score %d-%d-%d"),
5278 first.tidy, second.tidy,
5279 first.matchWins, second.matchWins,
5280 appData.matchGames - (first.matchWins + second.matchWins));
5281 DisplayFatalError(buf, 0, 0);
5284 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile) &&
5285 !(nextGameMode == AnalyzeMode || nextGameMode == AnalyzeFile))
5287 gameMode = nextGameMode;
5291 /* Assumes program was just initialized (initString sent).
5292 Leaves program in force mode. */
5294 FeedMovesToProgram(cps, upto)
5295 ChessProgramState *cps;
5300 if (appData.debugMode)
5301 fprintf(debugFP, "Feeding %smoves %d through %d to %s chess program\n",
5302 startedFromSetupPosition ? "position and " : "",
5303 backwardMostMove, upto, cps->which);
5304 SendToProgram("force\n", cps);
5305 if (startedFromSetupPosition) {
5306 SendBoard(cps, backwardMostMove);
5308 for (i = backwardMostMove; i < upto; i++) {
5309 SendMoveToProgram(i, cps);
5315 ResurrectChessProgram()
5317 /* The chess program may have exited.
5318 If so, restart it and feed it all the moves made so far. */
5320 if (appData.noChessProgram || first.pr != NoProc) return;
5322 StartChessProgram(&first);
5323 InitChessProgram(&first);
5324 FeedMovesToProgram(&first, currentMove);
5326 if (!first.sendTime) {
5327 /* can't tell gnuchess what its clock should read,
5328 so we bow to its notion. */
5330 timeRemaining[0][currentMove] = whiteTimeRemaining;
5331 timeRemaining[1][currentMove] = blackTimeRemaining;
5334 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile) &&
5335 first.analysisSupport) {
5336 SendToProgram("analyze\n", &first);
5337 first.analyzing = TRUE;
5350 if (appData.debugMode) {
5351 fprintf(debugFP, "Reset(%d, %d) from gameMode %d\n",
5352 redraw, init, gameMode);
5355 pausing = pauseExamInvalid = FALSE;
5356 startedFromSetupPosition = blackPlaysFirst = FALSE;
5358 whiteFlag = blackFlag = FALSE;
5359 userOfferedDraw = FALSE;
5360 hintRequested = bookRequested = FALSE;
5361 first.maybeThinking = FALSE;
5362 second.maybeThinking = FALSE;
5363 thinkOutput[0] = NULLCHAR;
5364 lastHint[0] = NULLCHAR;
5365 ClearGameInfo(&gameInfo);
5366 gameInfo.variant = StringToVariant(appData.variant);
5367 ics_user_moved = ics_clock_paused = FALSE;
5368 ics_getting_history = H_FALSE;
5370 white_holding[0] = black_holding[0] = NULLCHAR;
5371 ClearProgramStats();
5375 flipView = appData.flipView;
5376 ClearPremoveHighlights();
5378 alarmSounded = FALSE;
5380 GameEnds((ChessMove) 0, NULL, GE_PLAYER);
5382 gameMode = BeginningOfGame;
5384 InitPosition(redraw);
5385 for (i = 0; i < MAX_MOVES; i++) {
5386 if (commentList[i] != NULL) {
5387 free(commentList[i]);
5388 commentList[i] = NULL;
5392 timeRemaining[0][0] = whiteTimeRemaining;
5393 timeRemaining[1][0] = blackTimeRemaining;
5394 if (first.pr == NULL) {
5395 StartChessProgram(&first);
5397 if (init) InitChessProgram(&first);
5399 DisplayMessage("", "");
5400 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
5407 if (!AutoPlayOneMove())
5409 if (matchMode || appData.timeDelay == 0)
5411 if (appData.timeDelay < 0 || gameMode == AnalyzeFile)
5413 StartLoadGameTimer((long)(1000.0 * appData.timeDelay));
5422 int fromX, fromY, toX, toY;
5424 if (appData.debugMode) {
5425 fprintf(debugFP, "AutoPlayOneMove(): current %d\n", currentMove);
5428 if (gameMode != PlayFromGameFile)
5431 if (currentMove >= forwardMostMove) {
5432 gameMode = EditGame;
5437 toX = moveList[currentMove][2] - 'a';
5438 toY = moveList[currentMove][3] - '1';
5440 if (moveList[currentMove][1] == '@') {
5441 if (appData.highlightLastMove) {
5442 SetHighlights(-1, -1, toX, toY);
5445 fromX = moveList[currentMove][0] - 'a';
5446 fromY = moveList[currentMove][1] - '1';
5447 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
5449 if (appData.highlightLastMove) {
5450 SetHighlights(fromX, fromY, toX, toY);
5453 DisplayMove(currentMove);
5454 SendMoveToProgram(currentMove++, &first);
5455 DisplayBothClocks();
5456 DrawPosition(FALSE, boards[currentMove]);
5457 if (commentList[currentMove] != NULL) {
5458 DisplayComment(currentMove - 1, commentList[currentMove]);
5465 LoadGameOneMove(readAhead)
5466 ChessMove readAhead;
5468 int fromX = 0, fromY = 0, toX = 0, toY = 0, done;
5469 char promoChar = NULLCHAR;
5474 if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile &&
5475 gameMode != AnalyzeMode && gameMode != Training) {
5480 yyboardindex = forwardMostMove;
5481 if (readAhead != (ChessMove)0) {
5482 moveType = readAhead;
5484 if (gameFileFP == NULL)
5486 moveType = (ChessMove) yylex();
5492 if (appData.debugMode)
5493 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
5495 if (*p == '{' || *p == '[' || *p == '(') {
5496 p[strlen(p) - 1] = NULLCHAR;
5500 /* append the comment but don't display it */
5501 while (*p == '\n') p++;
5502 AppendComment(currentMove, p);
5505 case WhiteCapturesEnPassant:
5506 case BlackCapturesEnPassant:
5507 case WhitePromotionQueen:
5508 case BlackPromotionQueen:
5509 case WhitePromotionRook:
5510 case BlackPromotionRook:
5511 case WhitePromotionBishop:
5512 case BlackPromotionBishop:
5513 case WhitePromotionKnight:
5514 case BlackPromotionKnight:
5515 case WhitePromotionKing:
5516 case BlackPromotionKing:
5518 case WhiteKingSideCastle:
5519 case WhiteQueenSideCastle:
5520 case BlackKingSideCastle:
5521 case BlackQueenSideCastle:
5522 case WhiteKingSideCastleWild:
5523 case WhiteQueenSideCastleWild:
5524 case BlackKingSideCastleWild:
5525 case BlackQueenSideCastleWild:
5526 if (appData.debugMode)
5527 fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
5528 fromX = currentMoveString[0] - 'a';
5529 fromY = currentMoveString[1] - '1';
5530 toX = currentMoveString[2] - 'a';
5531 toY = currentMoveString[3] - '1';
5532 promoChar = currentMoveString[4];
5537 if (appData.debugMode)
5538 fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
5539 fromX = moveType == WhiteDrop ?
5540 (int) CharToPiece(ToUpper(currentMoveString[0])) :
5541 (int) CharToPiece(ToLower(currentMoveString[0]));
5543 toX = currentMoveString[2] - 'a';
5544 toY = currentMoveString[3] - '1';
5550 case GameUnfinished:
5551 if (appData.debugMode)
5552 fprintf(debugFP, "Parsed game end: %s\n", yy_text);
5553 p = strchr(yy_text, '{');
5554 if (p == NULL) p = strchr(yy_text, '(');
5557 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
5559 q = strchr(p, *p == '{' ? '}' : ')');
5560 if (q != NULL) *q = NULLCHAR;
5563 GameEnds(moveType, p, GE_FILE);
5565 if (cmailMsgLoaded) {
5567 flipView = WhiteOnMove(currentMove);
5568 if (moveType == GameUnfinished) flipView = !flipView;
5569 if (appData.debugMode)
5570 fprintf(debugFP, "Setting flipView to %d\n", flipView) ;
5574 case (ChessMove) 0: /* end of file */
5575 if (appData.debugMode)
5576 fprintf(debugFP, "Parser hit end of file\n");
5577 switch (MateTest(boards[currentMove], PosFlags(currentMove),
5583 if (WhiteOnMove(currentMove)) {
5584 GameEnds(BlackWins, "Black mates", GE_FILE);
5586 GameEnds(WhiteWins, "White mates", GE_FILE);
5590 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
5597 if (lastLoadGameStart == GNUChessGame) {
5598 /* GNUChessGames have numbers, but they aren't move numbers */
5599 if (appData.debugMode)
5600 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
5601 yy_text, (int) moveType);
5602 return LoadGameOneMove((ChessMove)0); /* tail recursion */
5604 /* else fall thru */
5609 /* Reached start of next game in file */
5610 if (appData.debugMode)
5611 fprintf(debugFP, "Parsed start of next game: %s\n", yy_text);
5612 switch (MateTest(boards[currentMove], PosFlags(currentMove),
5618 if (WhiteOnMove(currentMove)) {
5619 GameEnds(BlackWins, "Black mates", GE_FILE);
5621 GameEnds(WhiteWins, "White mates", GE_FILE);
5625 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
5631 case PositionDiagram: /* should not happen; ignore */
5632 case ElapsedTime: /* ignore */
5633 case NAG: /* ignore */
5634 if (appData.debugMode)
5635 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
5636 yy_text, (int) moveType);
5637 return LoadGameOneMove((ChessMove)0); /* tail recursion */
5640 if (appData.testLegality) {
5641 if (appData.debugMode)
5642 fprintf(debugFP, "Parsed IllegalMove: %s\n", yy_text);
5643 sprintf(move, _("Illegal move: %d.%s%s"),
5644 (forwardMostMove / 2) + 1,
5645 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
5646 DisplayError(move, 0);
5649 if (appData.debugMode)
5650 fprintf(debugFP, "Parsed %s into IllegalMove %s\n",
5651 yy_text, currentMoveString);
5652 fromX = currentMoveString[0] - 'a';
5653 fromY = currentMoveString[1] - '1';
5654 toX = currentMoveString[2] - 'a';
5655 toY = currentMoveString[3] - '1';
5656 promoChar = currentMoveString[4];
5661 if (appData.debugMode)
5662 fprintf(debugFP, "Parsed AmbiguousMove: %s\n", yy_text);
5663 sprintf(move, _("Ambiguous move: %d.%s%s"),
5664 (forwardMostMove / 2) + 1,
5665 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
5666 DisplayError(move, 0);
5671 case ImpossibleMove:
5672 if (appData.debugMode)
5673 fprintf(debugFP, "Parsed ImpossibleMove: %s\n", yy_text);
5674 sprintf(move, _("Illegal move: %d.%s%s"),
5675 (forwardMostMove / 2) + 1,
5676 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
5677 DisplayError(move, 0);
5683 if (appData.matchMode || (appData.timeDelay == 0 && !pausing)) {
5684 DrawPosition(FALSE, boards[currentMove]);
5685 DisplayBothClocks();
5686 if (!appData.matchMode && commentList[currentMove] != NULL)
5687 DisplayComment(currentMove - 1, commentList[currentMove]);
5689 (void) StopLoadGameTimer();
5691 cmailOldMove = forwardMostMove;
5694 /* currentMoveString is set as a side-effect of yylex */
5695 strcat(currentMoveString, "\n");
5696 strcpy(moveList[forwardMostMove], currentMoveString);
5698 thinkOutput[0] = NULLCHAR;
5699 MakeMove(fromX, fromY, toX, toY, promoChar);
5700 currentMove = forwardMostMove;
5705 /* Load the nth game from the given file */
5707 LoadGameFromFile(filename, n, title, useList)
5711 /*Boolean*/ int useList;
5716 if (strcmp(filename, "-") == 0) {
5720 f = fopen(filename, "rb");
5722 sprintf(buf, _("Can't open \"%s\""), filename);
5723 DisplayError(buf, errno);
5727 if (fseek(f, 0, 0) == -1) {
5728 /* f is not seekable; probably a pipe */
5731 if (useList && n == 0) {
5732 int error = GameListBuild(f);
5734 DisplayError(_("Cannot build game list"), error);
5735 } else if (!ListEmpty(&gameList) &&
5736 ((ListGame *) gameList.tailPred)->number > 1) {
5737 GameListPopUp(f, title);
5744 return LoadGame(f, n, title, FALSE);
5749 MakeRegisteredMove()
5751 int fromX, fromY, toX, toY;
5753 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
5754 switch (cmailMoveType[lastLoadGameNumber - 1]) {
5757 if (appData.debugMode)
5758 fprintf(debugFP, "Restoring %s for game %d\n",
5759 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
5761 thinkOutput[0] = NULLCHAR;
5762 strcpy(moveList[currentMove], cmailMove[lastLoadGameNumber - 1]);
5763 fromX = cmailMove[lastLoadGameNumber - 1][0] - 'a';
5764 fromY = cmailMove[lastLoadGameNumber - 1][1] - '1';
5765 toX = cmailMove[lastLoadGameNumber - 1][2] - 'a';
5766 toY = cmailMove[lastLoadGameNumber - 1][3] - '1';
5767 promoChar = cmailMove[lastLoadGameNumber - 1][4];
5768 MakeMove(fromX, fromY, toX, toY, promoChar);
5769 ShowMove(fromX, fromY, toX, toY);
5771 switch (MateTest(boards[currentMove], PosFlags(currentMove),
5778 if (WhiteOnMove(currentMove)) {
5779 GameEnds(BlackWins, "Black mates", GE_PLAYER);
5781 GameEnds(WhiteWins, "White mates", GE_PLAYER);
5786 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
5793 if (WhiteOnMove(currentMove)) {
5794 GameEnds(BlackWins, "White resigns", GE_PLAYER);
5796 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
5801 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
5812 /* Wrapper around LoadGame for use when a Cmail message is loaded */
5814 CmailLoadGame(f, gameNumber, title, useList)
5822 if (gameNumber > nCmailGames) {
5823 DisplayError(_("No more games in this message"), 0);
5826 if (f == lastLoadGameFP) {
5827 int offset = gameNumber - lastLoadGameNumber;
5829 cmailMsg[0] = NULLCHAR;
5830 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
5831 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
5832 nCmailMovesRegistered--;
5834 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
5835 if (cmailResult[lastLoadGameNumber - 1] == CMAIL_NEW_RESULT) {
5836 cmailResult[lastLoadGameNumber - 1] = CMAIL_NOT_RESULT;
5839 if (! RegisterMove()) return FALSE;
5843 retVal = LoadGame(f, gameNumber, title, useList);
5845 /* Make move registered during previous look at this game, if any */
5846 MakeRegisteredMove();
5848 if (cmailCommentList[lastLoadGameNumber - 1] != NULL) {
5849 commentList[currentMove]
5850 = StrSave(cmailCommentList[lastLoadGameNumber - 1]);
5851 DisplayComment(currentMove - 1, commentList[currentMove]);
5857 /* Support for LoadNextGame, LoadPreviousGame, ReloadSameGame */
5862 int gameNumber = lastLoadGameNumber + offset;
5863 if (lastLoadGameFP == NULL) {
5864 DisplayError(_("No game has been loaded yet"), 0);
5867 if (gameNumber <= 0) {
5868 DisplayError(_("Can't back up any further"), 0);
5871 if (cmailMsgLoaded) {
5872 return CmailLoadGame(lastLoadGameFP, gameNumber,
5873 lastLoadGameTitle, lastLoadGameUseList);
5875 return LoadGame(lastLoadGameFP, gameNumber,
5876 lastLoadGameTitle, lastLoadGameUseList);
5882 /* Load the nth game from open file f */
5884 LoadGame(f, gameNumber, title, useList)
5892 int gn = gameNumber;
5893 ListGame *lg = NULL;
5896 GameMode oldGameMode;
5898 if (appData.debugMode)
5899 fprintf(debugFP, "LoadGame(): on entry, gameMode %d\n", gameMode);
5901 if (gameMode == Training )
5902 SetTrainingModeOff();
5904 oldGameMode = gameMode;
5905 if (gameMode != BeginningOfGame) {
5910 if (lastLoadGameFP != NULL && lastLoadGameFP != f) {
5911 fclose(lastLoadGameFP);
5915 lg = (ListGame *) ListElem(&gameList, gameNumber-1);
5918 fseek(f, lg->offset, 0);
5919 GameListHighlight(gameNumber);
5923 DisplayError(_("Game number out of range"), 0);
5928 if (fseek(f, 0, 0) == -1) {
5929 if (f == lastLoadGameFP ?
5930 gameNumber == lastLoadGameNumber + 1 :
5934 DisplayError(_("Can't seek on game file"), 0);
5940 lastLoadGameNumber = gameNumber;
5941 strcpy(lastLoadGameTitle, title);
5942 lastLoadGameUseList = useList;
5947 if (lg && lg->gameInfo.white && lg->gameInfo.black) {
5948 sprintf(buf, "%s vs. %s", lg->gameInfo.white,
5949 lg->gameInfo.black);
5951 } else if (*title != NULLCHAR) {
5952 if (gameNumber > 1) {
5953 sprintf(buf, "%s %d", title, gameNumber);
5956 DisplayTitle(title);
5960 if (gameMode != AnalyzeFile && gameMode != AnalyzeMode) {
5961 gameMode = PlayFromGameFile;
5965 currentMove = forwardMostMove = backwardMostMove = 0;
5966 CopyBoard(boards[0], initialPosition);
5970 * Skip the first gn-1 games in the file.
5971 * Also skip over anything that precedes an identifiable
5972 * start of game marker, to avoid being confused by
5973 * garbage at the start of the file. Currently
5974 * recognized start of game markers are the move number "1",
5975 * the pattern "gnuchess .* game", the pattern
5976 * "^[#;%] [^ ]* game file", and a PGN tag block.
5977 * A game that starts with one of the latter two patterns
5978 * will also have a move number 1, possibly
5979 * following a position diagram.
5980 * 5-4-02: Let's try being more lenient and allowing a game to
5981 * start with an unnumbered move. Does that break anything?
5983 cm = lastLoadGameStart = (ChessMove) 0;
5985 yyboardindex = forwardMostMove;
5986 cm = (ChessMove) yylex();
5989 if (cmailMsgLoaded) {
5990 nCmailGames = CMAIL_MAX_GAMES - gn;
5993 DisplayError(_("Game not found in file"), 0);
6000 lastLoadGameStart = cm;
6004 switch (lastLoadGameStart) {
6011 gn--; /* count this game */
6012 lastLoadGameStart = cm;
6021 switch (lastLoadGameStart) {
6026 gn--; /* count this game */
6027 lastLoadGameStart = cm;
6030 lastLoadGameStart = cm; /* game counted already */
6038 yyboardindex = forwardMostMove;
6039 cm = (ChessMove) yylex();
6040 } while (cm == PGNTag || cm == Comment);
6047 if (cmailMsgLoaded && (CMAIL_MAX_GAMES == lastLoadGameNumber)) {
6048 if ( cmailResult[CMAIL_MAX_GAMES - gn - 1]
6049 != CMAIL_OLD_RESULT) {
6051 cmailResult[ CMAIL_MAX_GAMES
6052 - gn - 1] = CMAIL_OLD_RESULT;
6058 /* Only a NormalMove can be at the start of a game
6059 * without a position diagram. */
6060 if (lastLoadGameStart == (ChessMove) 0) {
6062 lastLoadGameStart = MoveNumberOne;
6071 if (appData.debugMode)
6072 fprintf(debugFP, "Parsed game start '%s' (%d)\n", yy_text, (int) cm);
6074 if (cm == XBoardGame) {
6075 /* Skip any header junk before position diagram and/or move 1 */
6077 yyboardindex = forwardMostMove;
6078 cm = (ChessMove) yylex();
6080 if (cm == (ChessMove) 0 ||
6081 cm == GNUChessGame || cm == XBoardGame) {
6082 /* Empty game; pretend end-of-file and handle later */
6087 if (cm == MoveNumberOne || cm == PositionDiagram ||
6088 cm == PGNTag || cm == Comment)
6091 } else if (cm == GNUChessGame) {
6092 if (gameInfo.event != NULL) {
6093 free(gameInfo.event);
6095 gameInfo.event = StrSave(yy_text);
6098 startedFromSetupPosition = FALSE;
6099 while (cm == PGNTag) {
6100 if (appData.debugMode)
6101 fprintf(debugFP, "Parsed PGNTag: %s\n", yy_text);
6102 err = ParsePGNTag(yy_text, &gameInfo);
6103 if (!err) numPGNTags++;
6105 if (gameInfo.fen != NULL) {
6106 Board initial_position;
6107 startedFromSetupPosition = TRUE;
6108 if (!ParseFEN(initial_position, &blackPlaysFirst, gameInfo.fen)) {
6110 DisplayError(_("Bad FEN position in file"), 0);
6113 CopyBoard(boards[0], initial_position);
6114 if (blackPlaysFirst) {
6115 currentMove = forwardMostMove = backwardMostMove = 1;
6116 CopyBoard(boards[1], initial_position);
6117 strcpy(moveList[0], "");
6118 strcpy(parseList[0], "");
6119 timeRemaining[0][1] = whiteTimeRemaining;
6120 timeRemaining[1][1] = blackTimeRemaining;
6121 if (commentList[0] != NULL) {
6122 commentList[1] = commentList[0];
6123 commentList[0] = NULL;
6126 currentMove = forwardMostMove = backwardMostMove = 0;
6128 yyboardindex = forwardMostMove;
6130 gameInfo.fen = NULL;
6133 yyboardindex = forwardMostMove;
6134 cm = (ChessMove) yylex();
6136 /* Handle comments interspersed among the tags */
6137 while (cm == Comment) {
6139 if (appData.debugMode)
6140 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
6142 if (*p == '{' || *p == '[' || *p == '(') {
6143 p[strlen(p) - 1] = NULLCHAR;
6146 while (*p == '\n') p++;
6147 AppendComment(currentMove, p);
6148 yyboardindex = forwardMostMove;
6149 cm = (ChessMove) yylex();
6153 /* don't rely on existence of Event tag since if game was
6154 * pasted from clipboard the Event tag may not exist
6156 if (numPGNTags > 0){
6158 if (gameInfo.variant == VariantNormal) {
6159 gameInfo.variant = StringToVariant(gameInfo.event);
6162 tags = PGNTags(&gameInfo);
6163 TagsPopUp(tags, CmailMsg());
6167 /* Make something up, but don't display it now */
6172 if (cm == PositionDiagram) {
6175 Board initial_position;
6177 if (appData.debugMode)
6178 fprintf(debugFP, "Parsed PositionDiagram: %s\n", yy_text);
6180 if (!startedFromSetupPosition) {
6182 for (i = BOARD_SIZE - 1; i >= 0; i--)
6183 for (j = 0; j < BOARD_SIZE; p++)
6193 initial_position[i][j++] = CharToPiece(*p);
6196 while (*p == ' ' || *p == '\t' ||
6197 *p == '\n' || *p == '\r') p++;
6199 if (strncmp(p, "black", strlen("black"))==0)
6200 blackPlaysFirst = TRUE;
6202 blackPlaysFirst = FALSE;
6203 startedFromSetupPosition = TRUE;
6205 CopyBoard(boards[0], initial_position);
6206 if (blackPlaysFirst) {
6207 currentMove = forwardMostMove = backwardMostMove = 1;
6208 CopyBoard(boards[1], initial_position);
6209 strcpy(moveList[0], "");
6210 strcpy(parseList[0], "");
6211 timeRemaining[0][1] = whiteTimeRemaining;
6212 timeRemaining[1][1] = blackTimeRemaining;
6213 if (commentList[0] != NULL) {
6214 commentList[1] = commentList[0];
6215 commentList[0] = NULL;
6218 currentMove = forwardMostMove = backwardMostMove = 0;
6221 yyboardindex = forwardMostMove;
6222 cm = (ChessMove) yylex();
6225 if (first.pr == NoProc) {
6226 StartChessProgram(&first);
6228 InitChessProgram(&first);
6229 SendToProgram("force\n", &first);
6230 if (startedFromSetupPosition) {
6231 SendBoard(&first, forwardMostMove);
6232 DisplayBothClocks();
6235 while (cm == Comment) {
6237 if (appData.debugMode)
6238 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
6240 if (*p == '{' || *p == '[' || *p == '(') {
6241 p[strlen(p) - 1] = NULLCHAR;
6244 while (*p == '\n') p++;
6245 AppendComment(currentMove, p);
6246 yyboardindex = forwardMostMove;
6247 cm = (ChessMove) yylex();
6250 if ((cm == (ChessMove) 0 && lastLoadGameStart != (ChessMove) 0) ||
6251 cm == WhiteWins || cm == BlackWins ||
6252 cm == GameIsDrawn || cm == GameUnfinished) {
6253 DisplayMessage("", _("No moves in game"));
6254 if (cmailMsgLoaded) {
6255 if (appData.debugMode)
6256 fprintf(debugFP, "Setting flipView to %d.\n", FALSE);
6260 DrawPosition(FALSE, boards[currentMove]);
6261 DisplayBothClocks();
6262 gameMode = EditGame;
6269 if (commentList[currentMove] != NULL) {
6270 if (!matchMode && (pausing || appData.timeDelay != 0)) {
6271 DisplayComment(currentMove - 1, commentList[currentMove]);
6274 if (!matchMode && appData.timeDelay != 0)
6275 DrawPosition(FALSE, boards[currentMove]);
6277 if (gameMode == AnalyzeFile || gameMode == AnalyzeMode) {
6278 programStats.ok_to_send = 1;
6281 /* if the first token after the PGN tags is a move
6282 * and not move number 1, retrieve it from the parser
6284 if (cm != MoveNumberOne)
6285 LoadGameOneMove(cm);
6287 /* load the remaining moves from the file */
6288 while (LoadGameOneMove((ChessMove)0)) {
6289 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
6290 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
6293 /* rewind to the start of the game */
6294 currentMove = backwardMostMove;
6296 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
6298 if (oldGameMode == AnalyzeFile ||
6299 oldGameMode == AnalyzeMode) {
6303 if (matchMode || appData.timeDelay == 0) {
6305 gameMode = EditGame;
6307 } else if (appData.timeDelay > 0) {
6311 if (appData.debugMode)
6312 fprintf(debugFP, "LoadGame(): on exit, gameMode %d\n", gameMode);
6316 /* Support for LoadNextPosition, LoadPreviousPosition, ReloadSamePosition */
6318 ReloadPosition(offset)
6321 int positionNumber = lastLoadPositionNumber + offset;
6322 if (lastLoadPositionFP == NULL) {
6323 DisplayError(_("No position has been loaded yet"), 0);
6326 if (positionNumber <= 0) {
6327 DisplayError(_("Can't back up any further"), 0);
6330 return LoadPosition(lastLoadPositionFP, positionNumber,
6331 lastLoadPositionTitle);
6334 /* Load the nth position from the given file */
6336 LoadPositionFromFile(filename, n, title)
6344 if (strcmp(filename, "-") == 0) {
6345 return LoadPosition(stdin, n, "stdin");
6347 f = fopen(filename, "rb");
6349 sprintf(buf, _("Can't open \"%s\""), filename);
6350 DisplayError(buf, errno);
6353 return LoadPosition(f, n, title);
6358 /* Load the nth position from the given open file, and close it */
6360 LoadPosition(f, positionNumber, title)
6365 char *p, line[MSG_SIZ];
6366 Board initial_position;
6367 int i, j, fenMode, pn;
6369 if (gameMode == Training )
6370 SetTrainingModeOff();
6372 if (gameMode != BeginningOfGame) {
6375 if (lastLoadPositionFP != NULL && lastLoadPositionFP != f) {
6376 fclose(lastLoadPositionFP);
6378 if (positionNumber == 0) positionNumber = 1;
6379 lastLoadPositionFP = f;
6380 lastLoadPositionNumber = positionNumber;
6381 strcpy(lastLoadPositionTitle, title);
6382 if (first.pr == NoProc) {
6383 StartChessProgram(&first);
6384 InitChessProgram(&first);
6386 pn = positionNumber;
6387 if (positionNumber < 0) {
6388 /* Negative position number means to seek to that byte offset */
6389 if (fseek(f, -positionNumber, 0) == -1) {
6390 DisplayError(_("Can't seek on position file"), 0);
6395 if (fseek(f, 0, 0) == -1) {
6396 if (f == lastLoadPositionFP ?
6397 positionNumber == lastLoadPositionNumber + 1 :
6398 positionNumber == 1) {
6401 DisplayError(_("Can't seek on position file"), 0);
6406 /* See if this file is FEN or old-style xboard */
6407 if (fgets(line, MSG_SIZ, f) == NULL) {
6408 DisplayError(_("Position not found in file"), 0);
6416 case 'p': case 'n': case 'b': case 'r': case 'q': case 'k':
6417 case 'P': case 'N': case 'B': case 'R': case 'Q': case 'K':
6418 case '1': case '2': case '3': case '4': case '5': case '6':
6425 if (fenMode || line[0] == '#') pn--;
6427 /* skip postions before number pn */
6428 if (fgets(line, MSG_SIZ, f) == NULL) {
6430 DisplayError(_("Position not found in file"), 0);
6433 if (fenMode || line[0] == '#') pn--;
6438 if (!ParseFEN(initial_position, &blackPlaysFirst, line)) {
6439 DisplayError(_("Bad FEN position in file"), 0);
6443 (void) fgets(line, MSG_SIZ, f);
6444 (void) fgets(line, MSG_SIZ, f);
6446 for (i = BOARD_SIZE - 1; i >= 0; i--) {
6447 (void) fgets(line, MSG_SIZ, f);
6448 for (p = line, j = 0; j < BOARD_SIZE; p++) {
6451 initial_position[i][j++] = CharToPiece(*p);
6455 blackPlaysFirst = FALSE;
6457 (void) fgets(line, MSG_SIZ, f);
6458 if (strncmp(line, "black", strlen("black"))==0)
6459 blackPlaysFirst = TRUE;
6462 startedFromSetupPosition = TRUE;
6464 SendToProgram("force\n", &first);
6465 CopyBoard(boards[0], initial_position);
6466 if (blackPlaysFirst) {
6467 currentMove = forwardMostMove = backwardMostMove = 1;
6468 strcpy(moveList[0], "");
6469 strcpy(parseList[0], "");
6470 CopyBoard(boards[1], initial_position);
6471 DisplayMessage("", _("Black to play"));
6473 currentMove = forwardMostMove = backwardMostMove = 0;
6474 DisplayMessage("", _("White to play"));
6476 SendBoard(&first, forwardMostMove);
6478 if (positionNumber > 1) {
6479 sprintf(line, "%s %d", title, positionNumber);
6482 DisplayTitle(title);
6484 gameMode = EditGame;
6487 timeRemaining[0][1] = whiteTimeRemaining;
6488 timeRemaining[1][1] = blackTimeRemaining;
6489 DrawPosition(FALSE, boards[currentMove]);
6496 CopyPlayerNameIntoFileName(dest, src)
6499 while (*src != NULLCHAR && *src != ',') {
6504 *(*dest)++ = *src++;
6509 char *DefaultFileName(ext)
6512 static char def[MSG_SIZ];
6515 if (gameInfo.white != NULL && gameInfo.white[0] != '-') {
6517 CopyPlayerNameIntoFileName(&p, gameInfo.white);
6519 CopyPlayerNameIntoFileName(&p, gameInfo.black);
6528 /* Save the current game to the given file */
6530 SaveGameToFile(filename, append)
6537 if (strcmp(filename, "-") == 0) {
6538 return SaveGame(stdout, 0, NULL);
6540 f = fopen(filename, append ? "a" : "w");
6542 sprintf(buf, _("Can't open \"%s\""), filename);
6543 DisplayError(buf, errno);
6546 return SaveGame(f, 0, NULL);
6555 static char buf[MSG_SIZ];
6558 p = strchr(str, ' ');
6559 if (p == NULL) return str;
6560 strncpy(buf, str, p - str);
6561 buf[p - str] = NULLCHAR;
6565 #define PGN_MAX_LINE 75
6567 /* Save game in PGN style and close the file */
6572 int i, offset, linelen, newblock;
6576 int movelen, numlen, blank;
6578 tm = time((time_t *) NULL);
6580 PrintPGNTags(f, &gameInfo);
6582 if (backwardMostMove > 0 || startedFromSetupPosition) {
6583 char *fen = PositionToFEN(backwardMostMove);
6584 fprintf(f, "[FEN \"%s\"]\n[SetUp \"1\"]\n", fen);
6585 fprintf(f, "\n{--------------\n");
6586 PrintPosition(f, backwardMostMove);
6587 fprintf(f, "--------------}\n");
6593 i = backwardMostMove;
6594 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
6598 while (i < forwardMostMove) {
6599 /* Print comments preceding this move */
6600 if (commentList[i] != NULL) {
6601 if (linelen > 0) fprintf(f, "\n");
6602 fprintf(f, "{\n%s}\n", commentList[i]);
6607 /* Format move number */
6609 sprintf(numtext, "%d.", (i - offset)/2 + 1);
6612 sprintf(numtext, "%d...", (i - offset)/2 + 1);
6614 numtext[0] = NULLCHAR;
6617 numlen = strlen(numtext);
6620 /* Print move number */
6621 blank = linelen > 0 && numlen > 0;
6622 if (linelen + (blank ? 1 : 0) + numlen > PGN_MAX_LINE) {
6631 fprintf(f, numtext);
6635 movetext = SavePart(parseList[i]);
6636 movelen = strlen(movetext);
6639 blank = linelen > 0 && movelen > 0;
6640 if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
6649 fprintf(f, movetext);
6655 /* Start a new line */
6656 if (linelen > 0) fprintf(f, "\n");
6658 /* Print comments after last move */
6659 if (commentList[i] != NULL) {
6660 fprintf(f, "{\n%s}\n", commentList[i]);
6664 if (gameInfo.resultDetails != NULL &&
6665 gameInfo.resultDetails[0] != NULLCHAR) {
6666 fprintf(f, "{%s} %s\n\n", gameInfo.resultDetails,
6667 PGNResult(gameInfo.result));
6669 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
6676 /* Save game in old style and close the file */
6684 tm = time((time_t *) NULL);
6686 fprintf(f, "# %s game file -- %s", programName, ctime(&tm));
6689 if (backwardMostMove > 0 || startedFromSetupPosition) {
6690 fprintf(f, "\n[--------------\n");
6691 PrintPosition(f, backwardMostMove);
6692 fprintf(f, "--------------]\n");
6697 i = backwardMostMove;
6698 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
6700 while (i < forwardMostMove) {
6701 if (commentList[i] != NULL) {
6702 fprintf(f, "[%s]\n", commentList[i]);
6706 fprintf(f, "%d. ... %s\n", (i - offset)/2 + 1, parseList[i]);
6709 fprintf(f, "%d. %s ", (i - offset)/2 + 1, parseList[i]);
6711 if (commentList[i] != NULL) {
6715 if (i >= forwardMostMove) {
6719 fprintf(f, "%s\n", parseList[i]);
6724 if (commentList[i] != NULL) {
6725 fprintf(f, "[%s]\n", commentList[i]);
6728 /* This isn't really the old style, but it's close enough */
6729 if (gameInfo.resultDetails != NULL &&
6730 gameInfo.resultDetails[0] != NULLCHAR) {
6731 fprintf(f, "%s (%s)\n\n", PGNResult(gameInfo.result),
6732 gameInfo.resultDetails);
6734 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
6741 /* Save the current game to open file f and close the file */
6743 SaveGame(f, dummy, dummy2)
6748 if (gameMode == EditPosition) EditPositionDone();
6749 if (appData.oldSaveStyle)
6750 return SaveGameOldStyle(f);
6752 return SaveGamePGN(f);
6755 /* Save the current position to the given file */
6757 SavePositionToFile(filename)
6763 if (strcmp(filename, "-") == 0) {
6764 return SavePosition(stdout, 0, NULL);
6766 f = fopen(filename, "a");
6768 sprintf(buf, _("Can't open \"%s\""), filename);
6769 DisplayError(buf, errno);
6772 SavePosition(f, 0, NULL);
6778 /* Save the current position to the given open file and close the file */
6780 SavePosition(f, dummy, dummy2)
6788 if (appData.oldSaveStyle) {
6789 tm = time((time_t *) NULL);
6791 fprintf(f, "# %s position file -- %s", programName, ctime(&tm));
6793 fprintf(f, "[--------------\n");
6794 PrintPosition(f, currentMove);
6795 fprintf(f, "--------------]\n");
6797 fen = PositionToFEN(currentMove);
6798 fprintf(f, "%s\n", fen);
6806 ReloadCmailMsgEvent(unregister)
6810 static char *inFilename = NULL;
6811 static char *outFilename;
6813 struct stat inbuf, outbuf;
6816 /* Any registered moves are unregistered if unregister is set, */
6817 /* i.e. invoked by the signal handler */
6819 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
6820 cmailMoveRegistered[i] = FALSE;
6821 if (cmailCommentList[i] != NULL) {
6822 free(cmailCommentList[i]);
6823 cmailCommentList[i] = NULL;
6826 nCmailMovesRegistered = 0;
6829 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
6830 cmailResult[i] = CMAIL_NOT_RESULT;
6834 if (inFilename == NULL) {
6835 /* Because the filenames are static they only get malloced once */
6836 /* and they never get freed */
6837 inFilename = (char *) malloc(strlen(appData.cmailGameName) + 9);
6838 sprintf(inFilename, "%s.game.in", appData.cmailGameName);
6840 outFilename = (char *) malloc(strlen(appData.cmailGameName) + 5);
6841 sprintf(outFilename, "%s.out", appData.cmailGameName);
6844 status = stat(outFilename, &outbuf);
6846 cmailMailedMove = FALSE;
6848 status = stat(inFilename, &inbuf);
6849 cmailMailedMove = (inbuf.st_mtime < outbuf.st_mtime);
6852 /* LoadGameFromFile(CMAIL_MAX_GAMES) with cmailMsgLoaded == TRUE
6853 counts the games, notes how each one terminated, etc.
6855 It would be nice to remove this kludge and instead gather all
6856 the information while building the game list. (And to keep it
6857 in the game list nodes instead of having a bunch of fixed-size
6858 parallel arrays.) Note this will require getting each game's
6859 termination from the PGN tags, as the game list builder does
6860 not process the game moves. --mann
6862 cmailMsgLoaded = TRUE;
6863 LoadGameFromFile(inFilename, CMAIL_MAX_GAMES, "", FALSE);
6865 /* Load first game in the file or popup game menu */
6866 LoadGameFromFile(inFilename, 0, appData.cmailGameName, TRUE);
6876 char string[MSG_SIZ];
6878 if ( cmailMailedMove
6879 || (cmailResult[lastLoadGameNumber - 1] == CMAIL_OLD_RESULT)) {
6880 return TRUE; /* Allow free viewing */
6883 /* Unregister move to ensure that we don't leave RegisterMove */
6884 /* with the move registered when the conditions for registering no */
6886 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
6887 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
6888 nCmailMovesRegistered --;
6890 if (cmailCommentList[lastLoadGameNumber - 1] != NULL)
6892 free(cmailCommentList[lastLoadGameNumber - 1]);
6893 cmailCommentList[lastLoadGameNumber - 1] = NULL;
6897 if (cmailOldMove == -1) {
6898 DisplayError(_("You have edited the game history.\nUse Reload Same Game and make your move again."), 0);
6902 if (currentMove > cmailOldMove + 1) {
6903 DisplayError(_("You have entered too many moves.\nBack up to the correct position and try again."), 0);
6907 if (currentMove < cmailOldMove) {
6908 DisplayError(_("Displayed position is not current.\nStep forward to the correct position and try again."), 0);
6912 if (forwardMostMove > currentMove) {
6913 /* Silently truncate extra moves */
6917 if ( (currentMove == cmailOldMove + 1)
6918 || ( (currentMove == cmailOldMove)
6919 && ( (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_ACCEPT)
6920 || (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_RESIGN)))) {
6921 if (gameInfo.result != GameUnfinished) {
6922 cmailResult[lastLoadGameNumber - 1] = CMAIL_NEW_RESULT;
6925 if (commentList[currentMove] != NULL) {
6926 cmailCommentList[lastLoadGameNumber - 1]
6927 = StrSave(commentList[currentMove]);
6929 strcpy(cmailMove[lastLoadGameNumber - 1], moveList[currentMove - 1]);
6931 if (appData.debugMode)
6932 fprintf(debugFP, "Saving %s for game %d\n",
6933 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
6936 "%s.game.out.%d", appData.cmailGameName, lastLoadGameNumber);
6938 f = fopen(string, "w");
6939 if (appData.oldSaveStyle) {
6940 SaveGameOldStyle(f); /* also closes the file */
6942 sprintf(string, "%s.pos.out", appData.cmailGameName);
6943 f = fopen(string, "w");
6944 SavePosition(f, 0, NULL); /* also closes the file */
6946 fprintf(f, "{--------------\n");
6947 PrintPosition(f, currentMove);
6948 fprintf(f, "--------------}\n\n");
6950 SaveGame(f, 0, NULL); /* also closes the file*/
6953 cmailMoveRegistered[lastLoadGameNumber - 1] = TRUE;
6954 nCmailMovesRegistered ++;
6955 } else if (nCmailGames == 1) {
6956 DisplayError(_("You have not made a move yet"), 0);
6967 static char *partCommandString = "cmail -xv%s -remail -game %s 2>&1";
6968 FILE *commandOutput;
6969 char buffer[MSG_SIZ], msg[MSG_SIZ], string[MSG_SIZ];
6970 int nBytes = 0; /* Suppress warnings on uninitialized variables */
6976 if (! cmailMsgLoaded) {
6977 DisplayError(_("The cmail message is not loaded.\nUse Reload CMail Message and make your move again."), 0);
6981 if (nCmailGames == nCmailResults) {
6982 DisplayError(_("No unfinished games"), 0);
6986 #if CMAIL_PROHIBIT_REMAIL
6987 if (cmailMailedMove) {
6988 sprintf(msg, _("You have already mailed a move.\nWait until a move arrives from your opponent.\nTo resend the same move, type\n\"cmail -remail -game %s\"\non the command line."), appData.cmailGameName);
6989 DisplayError(msg, 0);
6994 if (! (cmailMailedMove || RegisterMove())) return;
6996 if ( cmailMailedMove
6997 || (nCmailMovesRegistered + nCmailResults == nCmailGames)) {
6998 sprintf(string, partCommandString,
6999 appData.debugMode ? " -v" : "", appData.cmailGameName);
7000 commandOutput = popen(string, "r");
7002 if (commandOutput == NULL) {
7003 DisplayError(_("Failed to invoke cmail"), 0);
7005 for (nBuffers = 0; (! feof(commandOutput)); nBuffers ++) {
7006 nBytes = fread(buffer, 1, MSG_SIZ - 1, commandOutput);
7009 (void) memcpy(msg, buffer + nBytes, MSG_SIZ - nBytes - 1);
7010 (void) memcpy(msg + MSG_SIZ - nBytes - 1, buffer, nBytes);
7011 nBytes = MSG_SIZ - 1;
7013 (void) memcpy(msg, buffer, nBytes);
7015 *(msg + nBytes) = '\0'; /* \0 for end-of-string*/
7017 if(StrStr(msg, "Mailed cmail message to ") != NULL) {
7018 cmailMailedMove = TRUE; /* Prevent >1 moves */
7021 for (i = 0; i < nCmailGames; i ++) {
7022 if (cmailResult[i] == CMAIL_NOT_RESULT) {
7027 && ( (arcDir = (char *) getenv("CMAIL_ARCDIR"))
7029 sprintf(buffer, "%s/%s.%s.archive",
7031 appData.cmailGameName,
7033 LoadGameFromFile(buffer, 1, buffer, FALSE);
7034 cmailMsgLoaded = FALSE;
7038 DisplayInformation(msg);
7039 pclose(commandOutput);
7042 if ((*cmailMsg) != '\0') {
7043 DisplayInformation(cmailMsg);
7057 int prependComma = 0;
7059 char string[MSG_SIZ]; /* Space for game-list */
7062 if (!cmailMsgLoaded) return "";
7064 if (cmailMailedMove) {
7065 sprintf(cmailMsg, _("Waiting for reply from opponent\n"));
7067 /* Create a list of games left */
7068 sprintf(string, "[");
7069 for (i = 0; i < nCmailGames; i ++) {
7070 if (! ( cmailMoveRegistered[i]
7071 || (cmailResult[i] == CMAIL_OLD_RESULT))) {
7073 sprintf(number, ",%d", i + 1);
7075 sprintf(number, "%d", i + 1);
7079 strcat(string, number);
7082 strcat(string, "]");
7084 if (nCmailMovesRegistered + nCmailResults == 0) {
7085 switch (nCmailGames) {
7088 _("Still need to make move for game\n"));
7093 _("Still need to make moves for both games\n"));
7098 _("Still need to make moves for all %d games\n"),
7103 switch (nCmailGames - nCmailMovesRegistered - nCmailResults) {
7106 _("Still need to make a move for game %s\n"),
7111 if (nCmailResults == nCmailGames) {
7112 sprintf(cmailMsg, _("No unfinished games\n"));
7114 sprintf(cmailMsg, _("Ready to send mail\n"));
7120 _("Still need to make moves for games %s\n"),
7132 if (gameMode == Training)
7133 SetTrainingModeOff();
7136 cmailMsgLoaded = FALSE;
7137 if (appData.icsActive) {
7138 SendToICS(ics_prefix);
7139 SendToICS("refresh\n");
7143 static int exiting = 0;
7151 /* Give up on clean exit */
7155 /* Keep trying for clean exit */
7159 if (appData.icsActive && appData.colorize) Colorize(ColorNone, FALSE);
7161 if (telnetISR != NULL) {
7162 RemoveInputSource(telnetISR);
7164 if (icsPR != NoProc) {
7165 DestroyChildProcess(icsPR, TRUE);
7167 /* Save game if resource set and not already saved by GameEnds() */
7168 if (gameInfo.resultDetails == NULL && forwardMostMove > 0) {
7169 if (*appData.saveGameFile != NULLCHAR) {
7170 SaveGameToFile(appData.saveGameFile, TRUE);
7171 } else if (appData.autoSaveGames) {
7174 if (*appData.savePositionFile != NULLCHAR) {
7175 SavePositionToFile(appData.savePositionFile);
7178 GameEnds((ChessMove) 0, NULL, GE_PLAYER);
7180 /* Kill off chess programs */
7181 if (first.pr != NoProc) {
7183 SendToProgram("quit\n", &first);
7184 DestroyChildProcess(first.pr, first.useSigterm);
7186 if (second.pr != NoProc) {
7187 SendToProgram("quit\n", &second);
7188 DestroyChildProcess(second.pr, second.useSigterm);
7190 if (first.isr != NULL) {
7191 RemoveInputSource(first.isr);
7193 if (second.isr != NULL) {
7194 RemoveInputSource(second.isr);
7204 if (appData.debugMode)
7205 fprintf(debugFP, "PauseEvent(): pausing %d\n", pausing);
7209 if (gameMode == MachinePlaysWhite ||
7210 gameMode == MachinePlaysBlack) {
7213 DisplayBothClocks();
7215 if (gameMode == PlayFromGameFile) {
7216 if (appData.timeDelay >= 0)
7218 } else if (gameMode == IcsExamining && pauseExamInvalid) {
7220 SendToICS(ics_prefix);
7221 SendToICS("refresh\n");
7222 } else if (currentMove < forwardMostMove) {
7223 ForwardInner(forwardMostMove);
7225 pauseExamInvalid = FALSE;
7231 pauseExamForwardMostMove = forwardMostMove;
7232 pauseExamInvalid = FALSE;
7235 case IcsPlayingWhite:
7236 case IcsPlayingBlack:
7240 case PlayFromGameFile:
7241 (void) StopLoadGameTimer();
7245 case BeginningOfGame:
7246 if (appData.icsActive) return;
7247 /* else fall through */
7248 case MachinePlaysWhite:
7249 case MachinePlaysBlack:
7250 case TwoMachinesPlay:
7251 if (forwardMostMove == 0)
7252 return; /* don't pause if no one has moved */
7253 if ((gameMode == MachinePlaysWhite &&
7254 !WhiteOnMove(forwardMostMove)) ||
7255 (gameMode == MachinePlaysBlack &&
7256 WhiteOnMove(forwardMostMove))) {
7269 char title[MSG_SIZ];
7271 if (currentMove < 1 || parseList[currentMove - 1][0] == NULLCHAR) {
7272 strcpy(title, _("Edit comment"));
7274 sprintf(title, _("Edit comment on %d.%s%s"), (currentMove - 1) / 2 + 1,
7275 WhiteOnMove(currentMove - 1) ? " " : ".. ",
7276 parseList[currentMove - 1]);
7279 EditCommentPopUp(currentMove, title, commentList[currentMove]);
7286 char *tags = PGNTags(&gameInfo);
7287 EditTagsPopUp(tags);
7294 if (appData.noChessProgram || gameMode == AnalyzeMode)
7297 if (gameMode != AnalyzeFile) {
7299 if (gameMode != EditGame) return;
7300 ResurrectChessProgram();
7301 SendToProgram("analyze\n", &first);
7302 first.analyzing = TRUE;
7303 /*first.maybeThinking = TRUE;*/
7304 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
7305 AnalysisPopUp(_("Analysis"),
7306 _("Starting analysis mode...\nIf this message stays up, your chess program does not support analysis."));
7308 gameMode = AnalyzeMode;
7313 StartAnalysisClock();
7314 GetTimeMark(&lastNodeCountTime);
7321 if (appData.noChessProgram || gameMode == AnalyzeFile)
7324 if (gameMode != AnalyzeMode) {
7326 if (gameMode != EditGame) return;
7327 ResurrectChessProgram();
7328 SendToProgram("analyze\n", &first);
7329 first.analyzing = TRUE;
7330 /*first.maybeThinking = TRUE;*/
7331 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
7332 AnalysisPopUp(_("Analysis"),
7333 _("Starting analysis mode...\nIf this message stays up, your chess program does not support analysis."));
7335 gameMode = AnalyzeFile;
7340 StartAnalysisClock();
7341 GetTimeMark(&lastNodeCountTime);
7350 if (appData.noChessProgram || (gameMode == MachinePlaysWhite))
7354 if (gameMode == PlayFromGameFile ||
7355 gameMode == TwoMachinesPlay ||
7356 gameMode == Training ||
7357 gameMode == AnalyzeMode ||
7358 gameMode == EndOfGame)
7361 if (gameMode == EditPosition)
7364 if (!WhiteOnMove(currentMove)) {
7365 DisplayError(_("It is not White's turn"), 0);
7369 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
7372 if (gameMode == EditGame || gameMode == AnalyzeMode ||
7373 gameMode == AnalyzeFile)
7376 ResurrectChessProgram(); /* in case it isn't running */
7377 gameMode = MachinePlaysWhite;
7381 sprintf(buf, "%s vs. %s", gameInfo.white, gameInfo.black);
7383 if (first.sendName) {
7384 sprintf(buf, "name %s\n", gameInfo.black);
7385 SendToProgram(buf, &first);
7387 if (first.sendTime) {
7388 if (first.useColors) {
7389 SendToProgram("black\n", &first); /*gnu kludge*/
7391 SendTimeRemaining(&first, TRUE);
7393 if (first.useColors) {
7394 SendToProgram("white\ngo\n", &first);
7396 SendToProgram("go\n", &first);
7398 SetMachineThinkingEnables();
7399 first.maybeThinking = TRUE;
7402 if (appData.autoFlipView && !flipView) {
7403 flipView = !flipView;
7404 DrawPosition(FALSE, NULL);
7413 if (appData.noChessProgram || (gameMode == MachinePlaysBlack))
7417 if (gameMode == PlayFromGameFile ||
7418 gameMode == TwoMachinesPlay ||
7419 gameMode == Training ||
7420 gameMode == AnalyzeMode ||
7421 gameMode == EndOfGame)
7424 if (gameMode == EditPosition)
7427 if (WhiteOnMove(currentMove)) {
7428 DisplayError(_("It is not Black's turn"), 0);
7432 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
7435 if (gameMode == EditGame || gameMode == AnalyzeMode ||
7436 gameMode == AnalyzeFile)
7439 ResurrectChessProgram(); /* in case it isn't running */
7440 gameMode = MachinePlaysBlack;
7444 sprintf(buf, "%s vs. %s", gameInfo.white, gameInfo.black);
7446 if (first.sendName) {
7447 sprintf(buf, "name %s\n", gameInfo.white);
7448 SendToProgram(buf, &first);
7450 if (first.sendTime) {
7451 if (first.useColors) {
7452 SendToProgram("white\n", &first); /*gnu kludge*/
7454 SendTimeRemaining(&first, FALSE);
7456 if (first.useColors) {
7457 SendToProgram("black\ngo\n", &first);
7459 SendToProgram("go\n", &first);
7461 SetMachineThinkingEnables();
7462 first.maybeThinking = TRUE;
7465 if (appData.autoFlipView && flipView) {
7466 flipView = !flipView;
7467 DrawPosition(FALSE, NULL);
7473 DisplayTwoMachinesTitle()
7476 if (appData.matchGames > 0) {
7477 if (first.twoMachinesColor[0] == 'w') {
7478 sprintf(buf, "%s vs. %s (%d-%d-%d)",
7479 gameInfo.white, gameInfo.black,
7480 first.matchWins, second.matchWins,
7481 matchGame - 1 - (first.matchWins + second.matchWins));
7483 sprintf(buf, "%s vs. %s (%d-%d-%d)",
7484 gameInfo.white, gameInfo.black,
7485 second.matchWins, first.matchWins,
7486 matchGame - 1 - (first.matchWins + second.matchWins));
7489 sprintf(buf, "%s vs. %s", gameInfo.white, gameInfo.black);
7495 TwoMachinesEvent P((void))
7499 ChessProgramState *onmove;
7501 if (appData.noChessProgram) return;
7504 case TwoMachinesPlay:
7506 case MachinePlaysWhite:
7507 case MachinePlaysBlack:
7508 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
7509 DisplayError(_("Wait until your turn,\nor select Move Now"), 0);
7513 case BeginningOfGame:
7514 case PlayFromGameFile:
7517 if (gameMode != EditGame) return;
7531 forwardMostMove = currentMove;
7532 ResurrectChessProgram(); /* in case first program isn't running */
7534 if (second.pr == NULL) {
7535 StartChessProgram(&second);
7536 if (second.protocolVersion == 1) {
7537 TwoMachinesEventIfReady();
7539 /* kludge: allow timeout for initial "feature" command */
7541 DisplayMessage("", _("Starting second chess program"));
7542 ScheduleDelayedEvent(TwoMachinesEventIfReady, FEATURE_TIMEOUT);
7546 DisplayMessage("", "");
7547 InitChessProgram(&second);
7548 SendToProgram("force\n", &second);
7549 if (startedFromSetupPosition) {
7550 SendBoard(&second, backwardMostMove);
7552 for (i = backwardMostMove; i < forwardMostMove; i++) {
7553 SendMoveToProgram(i, &second);
7556 gameMode = TwoMachinesPlay;
7560 DisplayTwoMachinesTitle();
7562 if ((first.twoMachinesColor[0] == 'w') == WhiteOnMove(forwardMostMove)) {
7568 SendToProgram(first.computerString, &first);
7569 if (first.sendName) {
7570 sprintf(buf, "name %s\n", second.tidy);
7571 SendToProgram(buf, &first);
7573 SendToProgram(second.computerString, &second);
7574 if (second.sendName) {
7575 sprintf(buf, "name %s\n", first.tidy);
7576 SendToProgram(buf, &second);
7579 if (!first.sendTime || !second.sendTime) {
7581 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
7582 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
7584 if (onmove->sendTime) {
7585 if (onmove->useColors) {
7586 SendToProgram(onmove->other->twoMachinesColor, onmove); /*gnu kludge*/
7588 SendTimeRemaining(onmove, WhiteOnMove(forwardMostMove));
7590 if (onmove->useColors) {
7591 SendToProgram(onmove->twoMachinesColor, onmove);
7593 SendToProgram("go\n", onmove);
7594 onmove->maybeThinking = TRUE;
7595 SetMachineThinkingEnables();
7603 if (gameMode == Training) {
7604 SetTrainingModeOff();
7605 gameMode = PlayFromGameFile;
7606 DisplayMessage("", _("Training mode off"));
7608 gameMode = Training;
7609 animateTraining = appData.animate;
7611 /* make sure we are not already at the end of the game */
7612 if (currentMove < forwardMostMove) {
7613 SetTrainingModeOn();
7614 DisplayMessage("", _("Training mode on"));
7616 gameMode = PlayFromGameFile;
7617 DisplayError(_("Already at end of game"), 0);
7626 if (!appData.icsActive) return;
7628 case IcsPlayingWhite:
7629 case IcsPlayingBlack:
7632 case BeginningOfGame:
7666 SetTrainingModeOff();
7668 case MachinePlaysWhite:
7669 case MachinePlaysBlack:
7670 case BeginningOfGame:
7671 SendToProgram("force\n", &first);
7672 SetUserThinkingEnables();
7674 case PlayFromGameFile:
7675 (void) StopLoadGameTimer();
7676 if (gameFileFP != NULL) {
7686 SendToProgram("force\n", &first);
7688 case TwoMachinesPlay:
7689 GameEnds((ChessMove) 0, NULL, GE_PLAYER);
7690 ResurrectChessProgram();
7691 SetUserThinkingEnables();
7694 ResurrectChessProgram();
7696 case IcsPlayingBlack:
7697 case IcsPlayingWhite:
7698 DisplayError(_("Warning: You are still playing a game"), 0);
7701 DisplayError(_("Warning: You are still observing a game"), 0);
7704 DisplayError(_("Warning: You are still examining a game"), 0);
7715 first.offeredDraw = second.offeredDraw = 0;
7717 if (gameMode == PlayFromGameFile) {
7718 whiteTimeRemaining = timeRemaining[0][currentMove];
7719 blackTimeRemaining = timeRemaining[1][currentMove];
7723 if (gameMode == MachinePlaysWhite ||
7724 gameMode == MachinePlaysBlack ||
7725 gameMode == TwoMachinesPlay ||
7726 gameMode == EndOfGame) {
7727 i = forwardMostMove;
7728 while (i > currentMove) {
7729 SendToProgram("undo\n", &first);
7732 whiteTimeRemaining = timeRemaining[0][currentMove];
7733 blackTimeRemaining = timeRemaining[1][currentMove];
7734 DisplayBothClocks();
7735 if (whiteFlag || blackFlag) {
7736 whiteFlag = blackFlag = 0;
7741 gameMode = EditGame;
7750 if (gameMode == EditPosition) {
7756 if (gameMode != EditGame) return;
7758 gameMode = EditPosition;
7761 if (currentMove > 0)
7762 CopyBoard(boards[0], boards[currentMove]);
7764 blackPlaysFirst = !WhiteOnMove(currentMove);
7766 currentMove = forwardMostMove = backwardMostMove = 0;
7767 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
7774 if (first.analysisSupport && first.analyzing) {
7775 SendToProgram("exit\n", &first);
7776 first.analyzing = FALSE;
7779 thinkOutput[0] = NULLCHAR;
7785 startedFromSetupPosition = TRUE;
7786 InitChessProgram(&first);
7787 SendToProgram("force\n", &first);
7788 if (blackPlaysFirst) {
7789 strcpy(moveList[0], "");
7790 strcpy(parseList[0], "");
7791 currentMove = forwardMostMove = backwardMostMove = 1;
7792 CopyBoard(boards[1], boards[0]);
7794 currentMove = forwardMostMove = backwardMostMove = 0;
7796 SendBoard(&first, forwardMostMove);
7798 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
7799 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
7800 gameMode = EditGame;
7802 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
7805 /* Pause for `ms' milliseconds */
7806 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
7816 } while (SubtractTimeMarks(&m2, &m1) < ms);
7819 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
7821 SendMultiLineToICS(buf)
7824 char temp[MSG_SIZ+1], *p;
7831 strncpy(temp, buf, len);
7836 if (*p == '\n' || *p == '\r')
7843 SendToPlayer(temp, strlen(temp));
7847 SetWhiteToPlayEvent()
7849 if (gameMode == EditPosition) {
7850 blackPlaysFirst = FALSE;
7851 DisplayBothClocks(); /* works because currentMove is 0 */
7852 } else if (gameMode == IcsExamining) {
7853 SendToICS(ics_prefix);
7854 SendToICS("tomove white\n");
7859 SetBlackToPlayEvent()
7861 if (gameMode == EditPosition) {
7862 blackPlaysFirst = TRUE;
7863 currentMove = 1; /* kludge */
7864 DisplayBothClocks();
7866 } else if (gameMode == IcsExamining) {
7867 SendToICS(ics_prefix);
7868 SendToICS("tomove black\n");
7873 EditPositionMenuEvent(selection, x, y)
7874 ChessSquare selection;
7879 if (gameMode != EditPosition && gameMode != IcsExamining) return;
7881 switch (selection) {
7883 if (gameMode == IcsExamining && ics_type == ICS_FICS) {
7884 SendToICS(ics_prefix);
7885 SendToICS("bsetup clear\n");
7886 } else if (gameMode == IcsExamining && ics_type == ICS_ICC) {
7887 SendToICS(ics_prefix);
7888 SendToICS("clearboard\n");
7890 for (x = 0; x < BOARD_SIZE; x++) {
7891 for (y = 0; y < BOARD_SIZE; y++) {
7892 if (gameMode == IcsExamining) {
7893 if (boards[currentMove][y][x] != EmptySquare) {
7894 sprintf(buf, "%sx@%c%c\n", ics_prefix,
7899 boards[0][y][x] = EmptySquare;
7904 if (gameMode == EditPosition) {
7905 DrawPosition(FALSE, boards[0]);
7910 SetWhiteToPlayEvent();
7914 SetBlackToPlayEvent();
7918 if (gameMode == IcsExamining) {
7919 sprintf(buf, "%sx@%c%c\n", ics_prefix, 'a' + x, '1' + y);
7922 boards[0][y][x] = EmptySquare;
7923 DrawPosition(FALSE, boards[0]);
7928 if (gameMode == IcsExamining) {
7929 sprintf(buf, "%s%c@%c%c\n", ics_prefix,
7930 PieceToChar(selection), 'a' + x, '1' + y);
7933 boards[0][y][x] = selection;
7934 DrawPosition(FALSE, boards[0]);
7942 DropMenuEvent(selection, x, y)
7943 ChessSquare selection;
7949 case IcsPlayingWhite:
7950 case MachinePlaysBlack:
7951 if (!WhiteOnMove(currentMove)) {
7952 DisplayMoveError(_("It is Black's turn"));
7955 moveType = WhiteDrop;
7957 case IcsPlayingBlack:
7958 case MachinePlaysWhite:
7959 if (WhiteOnMove(currentMove)) {
7960 DisplayMoveError(_("It is White's turn"));
7963 moveType = BlackDrop;
7966 moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
7972 if (moveType == BlackDrop && selection < BlackPawn) {
7973 selection = (ChessSquare) ((int) selection
7974 + (int) BlackPawn - (int) WhitePawn);
7976 if (boards[currentMove][y][x] != EmptySquare) {
7977 DisplayMoveError(_("That square is occupied"));
7981 FinishMove(moveType, (int) selection, DROP_RANK, x, y, NULLCHAR);
7987 /* Accept a pending offer of any kind from opponent */
7989 if (appData.icsActive) {
7990 SendToICS(ics_prefix);
7991 SendToICS("accept\n");
7992 } else if (cmailMsgLoaded) {
7993 if (currentMove == cmailOldMove &&
7994 commentList[cmailOldMove] != NULL &&
7995 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
7996 "Black offers a draw" : "White offers a draw")) {
7998 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
7999 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
8001 DisplayError(_("There is no pending offer on this move"), 0);
8002 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
8005 /* Not used for offers from chess program */
8012 /* Decline a pending offer of any kind from opponent */
8014 if (appData.icsActive) {
8015 SendToICS(ics_prefix);
8016 SendToICS("decline\n");
8017 } else if (cmailMsgLoaded) {
8018 if (currentMove == cmailOldMove &&
8019 commentList[cmailOldMove] != NULL &&
8020 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
8021 "Black offers a draw" : "White offers a draw")) {
8023 AppendComment(cmailOldMove, "Draw declined");
8024 DisplayComment(cmailOldMove - 1, "Draw declined");
8027 DisplayError(_("There is no pending offer on this move"), 0);
8030 /* Not used for offers from chess program */
8037 /* Issue ICS rematch command */
8038 if (appData.icsActive) {
8039 SendToICS(ics_prefix);
8040 SendToICS("rematch\n");
8047 /* Call your opponent's flag (claim a win on time) */
8048 if (appData.icsActive) {
8049 SendToICS(ics_prefix);
8050 SendToICS("flag\n");
8055 case MachinePlaysWhite:
8058 GameEnds(GameIsDrawn, "Both players ran out of time",
8061 GameEnds(BlackWins, "Black wins on time", GE_PLAYER);
8063 DisplayError(_("Your opponent is not out of time"), 0);
8066 case MachinePlaysBlack:
8069 GameEnds(GameIsDrawn, "Both players ran out of time",
8072 GameEnds(WhiteWins, "White wins on time", GE_PLAYER);
8074 DisplayError(_("Your opponent is not out of time"), 0);
8084 /* Offer draw or accept pending draw offer from opponent */
8086 if (appData.icsActive) {
8087 /* Note: tournament rules require draw offers to be
8088 made after you make your move but before you punch
8089 your clock. Currently ICS doesn't let you do that;
8090 instead, you immediately punch your clock after making
8091 a move, but you can offer a draw at any time. */
8093 SendToICS(ics_prefix);
8094 SendToICS("draw\n");
8095 } else if (cmailMsgLoaded) {
8096 if (currentMove == cmailOldMove &&
8097 commentList[cmailOldMove] != NULL &&
8098 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
8099 "Black offers a draw" : "White offers a draw")) {
8100 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
8101 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
8102 } else if (currentMove == cmailOldMove + 1) {
8103 char *offer = WhiteOnMove(cmailOldMove) ?
8104 "White offers a draw" : "Black offers a draw";
8105 AppendComment(currentMove, offer);
8106 DisplayComment(currentMove - 1, offer);
8107 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_DRAW;
8109 DisplayError(_("You must make your move before offering a draw"), 0);
8110 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
8112 } else if (first.offeredDraw) {
8113 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
8115 if (first.sendDrawOffers) {
8116 SendToProgram("draw\n", &first);
8117 userOfferedDraw = TRUE;
8125 /* Offer Adjourn or accept pending Adjourn offer from opponent */
8127 if (appData.icsActive) {
8128 SendToICS(ics_prefix);
8129 SendToICS("adjourn\n");
8131 /* Currently GNU Chess doesn't offer or accept Adjourns */
8139 /* Offer Abort or accept pending Abort offer from opponent */
8141 if (appData.icsActive) {
8142 SendToICS(ics_prefix);
8143 SendToICS("abort\n");
8145 GameEnds(GameUnfinished, "Game aborted", GE_PLAYER);
8152 /* Resign. You can do this even if it's not your turn. */
8154 if (appData.icsActive) {
8155 SendToICS(ics_prefix);
8156 SendToICS("resign\n");
8159 case MachinePlaysWhite:
8160 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
8162 case MachinePlaysBlack:
8163 GameEnds(BlackWins, "White resigns", GE_PLAYER);
8166 if (cmailMsgLoaded) {
8168 if (WhiteOnMove(cmailOldMove)) {
8169 GameEnds(BlackWins, "White resigns", GE_PLAYER);
8171 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
8173 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_RESIGN;
8184 StopObservingEvent()
8186 /* Stop observing current games */
8187 SendToICS(ics_prefix);
8188 SendToICS("unobserve\n");
8192 StopExaminingEvent()
8194 /* Stop observing current game */
8195 SendToICS(ics_prefix);
8196 SendToICS("unexamine\n");
8200 ForwardInner(target)
8205 if (appData.debugMode)
8206 fprintf(debugFP, "ForwardInner(%d), current %d, forward %d\n",
8207 target, currentMove, forwardMostMove);
8209 if (gameMode == EditPosition)
8212 if (gameMode == PlayFromGameFile && !pausing)
8215 if (gameMode == IcsExamining && pausing)
8216 limit = pauseExamForwardMostMove;
8218 limit = forwardMostMove;
8220 if (target > limit) target = limit;
8222 if (target > 0 && moveList[target - 1][0]) {
8223 int fromX, fromY, toX, toY;
8224 toX = moveList[target - 1][2] - 'a';
8225 toY = moveList[target - 1][3] - '1';
8226 if (moveList[target - 1][1] == '@') {
8227 if (appData.highlightLastMove) {
8228 SetHighlights(-1, -1, toX, toY);
8231 fromX = moveList[target - 1][0] - 'a';
8232 fromY = moveList[target - 1][1] - '1';
8233 if (target == currentMove + 1) {
8234 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
8236 if (appData.highlightLastMove) {
8237 SetHighlights(fromX, fromY, toX, toY);
8241 if (gameMode == EditGame || gameMode == AnalyzeMode ||
8242 gameMode == Training || gameMode == PlayFromGameFile ||
8243 gameMode == AnalyzeFile) {
8244 while (currentMove < target) {
8245 SendMoveToProgram(currentMove++, &first);
8248 currentMove = target;
8251 if (gameMode == EditGame || gameMode == EndOfGame) {
8252 whiteTimeRemaining = timeRemaining[0][currentMove];
8253 blackTimeRemaining = timeRemaining[1][currentMove];
8255 DisplayBothClocks();
8256 DisplayMove(currentMove - 1);
8257 DrawPosition(FALSE, boards[currentMove]);
8258 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
8259 if (commentList[currentMove] && !matchMode && gameMode != Training) {
8260 DisplayComment(currentMove - 1, commentList[currentMove]);
8268 if (gameMode == IcsExamining && !pausing) {
8269 SendToICS(ics_prefix);
8270 SendToICS("forward\n");
8272 ForwardInner(currentMove + 1);
8279 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
8280 /* to optimze, we temporarily turn off analysis mode while we feed
8281 * the remaining moves to the engine. Otherwise we get analysis output
8284 if (first.analysisSupport) {
8285 SendToProgram("exit\nforce\n", &first);
8286 first.analyzing = FALSE;
8290 if (gameMode == IcsExamining && !pausing) {
8291 SendToICS(ics_prefix);
8292 SendToICS("forward 999999\n");
8294 ForwardInner(forwardMostMove);
8297 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
8298 /* we have fed all the moves, so reactivate analysis mode */
8299 SendToProgram("analyze\n", &first);
8300 first.analyzing = TRUE;
8301 /*first.maybeThinking = TRUE;*/
8302 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
8307 BackwardInner(target)
8310 if (appData.debugMode)
8311 fprintf(debugFP, "BackwardInner(%d), current %d, forward %d\n",
8312 target, currentMove, forwardMostMove);
8314 if (gameMode == EditPosition) return;
8315 if (currentMove <= backwardMostMove) {
8317 DrawPosition(FALSE, boards[currentMove]);
8320 if (gameMode == PlayFromGameFile && !pausing)
8323 if (moveList[target][0]) {
8324 int fromX, fromY, toX, toY;
8325 toX = moveList[target][2] - 'a';
8326 toY = moveList[target][3] - '1';
8327 if (moveList[target][1] == '@') {
8328 if (appData.highlightLastMove) {
8329 SetHighlights(-1, -1, toX, toY);
8332 fromX = moveList[target][0] - 'a';
8333 fromY = moveList[target][1] - '1';
8334 if (target == currentMove - 1) {
8335 AnimateMove(boards[currentMove], toX, toY, fromX, fromY);
8337 if (appData.highlightLastMove) {
8338 SetHighlights(fromX, fromY, toX, toY);
8342 if (gameMode == EditGame || gameMode==AnalyzeMode ||
8343 gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
8344 while (currentMove > target) {
8345 SendToProgram("undo\n", &first);
8349 currentMove = target;
8352 if (gameMode == EditGame || gameMode == EndOfGame) {
8353 whiteTimeRemaining = timeRemaining[0][currentMove];
8354 blackTimeRemaining = timeRemaining[1][currentMove];
8356 DisplayBothClocks();
8357 DisplayMove(currentMove - 1);
8358 DrawPosition(FALSE, boards[currentMove]);
8359 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
8360 if (commentList[currentMove] != NULL) {
8361 DisplayComment(currentMove - 1, commentList[currentMove]);
8368 if (gameMode == IcsExamining && !pausing) {
8369 SendToICS(ics_prefix);
8370 SendToICS("backward\n");
8372 BackwardInner(currentMove - 1);
8379 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
8380 /* to optimze, we temporarily turn off analysis mode while we undo
8381 * all the moves. Otherwise we get analysis output after each undo.
8383 if (first.analysisSupport) {
8384 SendToProgram("exit\nforce\n", &first);
8385 first.analyzing = FALSE;
8389 if (gameMode == IcsExamining && !pausing) {
8390 SendToICS(ics_prefix);
8391 SendToICS("backward 999999\n");
8393 BackwardInner(backwardMostMove);
8396 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
8397 /* we have fed all the moves, so reactivate analysis mode */
8398 SendToProgram("analyze\n", &first);
8399 first.analyzing = TRUE;
8400 /*first.maybeThinking = TRUE;*/
8401 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
8408 if (gameMode == PlayFromGameFile && !pausing) PauseEvent();
8409 if (to >= forwardMostMove) to = forwardMostMove;
8410 if (to <= backwardMostMove) to = backwardMostMove;
8411 if (to < currentMove) {
8421 if (gameMode != IcsExamining) {
8422 DisplayError(_("You are not examining a game"), 0);
8426 DisplayError(_("You can't revert while pausing"), 0);
8429 SendToICS(ics_prefix);
8430 SendToICS("revert\n");
8437 case MachinePlaysWhite:
8438 case MachinePlaysBlack:
8439 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
8440 DisplayError(_("Wait until your turn,\nor select Move Now"), 0);
8443 if (forwardMostMove < 2) return;
8444 currentMove = forwardMostMove = forwardMostMove - 2;
8445 whiteTimeRemaining = timeRemaining[0][currentMove];
8446 blackTimeRemaining = timeRemaining[1][currentMove];
8447 DisplayBothClocks();
8448 DisplayMove(currentMove - 1);
8449 ClearHighlights();/*!! could figure this out*/
8450 DrawPosition(FALSE, boards[currentMove]);
8451 SendToProgram("remove\n", &first);
8452 /*first.maybeThinking = TRUE;*/ /* GNU Chess does not ponder here */
8455 case BeginningOfGame:
8459 case IcsPlayingWhite:
8460 case IcsPlayingBlack:
8461 if (WhiteOnMove(forwardMostMove) == (gameMode == IcsPlayingWhite)) {
8462 SendToICS(ics_prefix);
8463 SendToICS("takeback 2\n");
8465 SendToICS(ics_prefix);
8466 SendToICS("takeback 1\n");
8475 ChessProgramState *cps;
8478 case MachinePlaysWhite:
8479 if (!WhiteOnMove(forwardMostMove)) {
8480 DisplayError(_("It is your turn"), 0);
8485 case MachinePlaysBlack:
8486 if (WhiteOnMove(forwardMostMove)) {
8487 DisplayError(_("It is your turn"), 0);
8492 case TwoMachinesPlay:
8493 if (WhiteOnMove(forwardMostMove) ==
8494 (first.twoMachinesColor[0] == 'w')) {
8500 case BeginningOfGame:
8504 SendToProgram("?\n", cps);
8511 if (gameMode != EditGame) return;
8518 if (forwardMostMove > currentMove) {
8519 if (gameInfo.resultDetails != NULL) {
8520 free(gameInfo.resultDetails);
8521 gameInfo.resultDetails = NULL;
8522 gameInfo.result = GameUnfinished;
8524 forwardMostMove = currentMove;
8525 HistorySet(parseList, backwardMostMove, forwardMostMove,
8533 if (appData.noChessProgram) return;
8535 case MachinePlaysWhite:
8536 if (WhiteOnMove(forwardMostMove)) {
8537 DisplayError(_("Wait until your turn"), 0);
8541 case BeginningOfGame:
8542 case MachinePlaysBlack:
8543 if (!WhiteOnMove(forwardMostMove)) {
8544 DisplayError(_("Wait until your turn"), 0);
8549 DisplayError(_("No hint available"), 0);
8552 SendToProgram("hint\n", &first);
8553 hintRequested = TRUE;
8559 if (appData.noChessProgram) return;
8561 case MachinePlaysWhite:
8562 if (WhiteOnMove(forwardMostMove)) {
8563 DisplayError(_("Wait until your turn"), 0);
8567 case BeginningOfGame:
8568 case MachinePlaysBlack:
8569 if (!WhiteOnMove(forwardMostMove)) {
8570 DisplayError(_("Wait until your turn"), 0);
8577 case TwoMachinesPlay:
8582 SendToProgram("bk\n", &first);
8583 bookOutput[0] = NULLCHAR;
8584 bookRequested = TRUE;
8590 char *tags = PGNTags(&gameInfo);
8591 TagsPopUp(tags, CmailMsg());
8595 /* end button procedures */
8598 PrintPosition(fp, move)
8604 for (i = BOARD_SIZE - 1; i >= 0; i--) {
8605 for (j = 0; j < BOARD_SIZE; j++) {
8606 char c = PieceToChar(boards[move][i][j]);
8607 fputc(c == 'x' ? '.' : c, fp);
8608 fputc(j == BOARD_SIZE - 1 ? '\n' : ' ', fp);
8611 if ((gameMode == EditPosition) ? !blackPlaysFirst : (move % 2 == 0))
8612 fprintf(fp, "white to play\n");
8614 fprintf(fp, "black to play\n");
8621 if (gameInfo.white != NULL) {
8622 fprintf(fp, "\t%s vs. %s\n", gameInfo.white, gameInfo.black);
8628 /* Find last component of program's own name, using some heuristics */
8630 TidyProgramName(prog, host, buf)
8631 char *prog, *host, buf[MSG_SIZ];
8634 int local = (strcmp(host, "localhost") == 0);
8635 while (!local && (p = strchr(prog, ';')) != NULL) {
8637 while (*p == ' ') p++;
8640 if (*prog == '"' || *prog == '\'') {
8641 q = strchr(prog + 1, *prog);
8643 q = strchr(prog, ' ');
8645 if (q == NULL) q = prog + strlen(prog);
8647 while (p >= prog && *p != '/' && *p != '\\') p--;
8649 if (q - p >= 4 && StrCaseCmp(q - 4, ".exe") == 0) q -= 4;
8650 memcpy(buf, p, q - p);
8651 buf[q - p] = NULLCHAR;
8659 TimeControlTagValue()
8662 if (!appData.clockMode) {
8664 } else if (movesPerSession > 0) {
8665 sprintf(buf, "%d/%ld", movesPerSession, timeControl/1000);
8666 } else if (timeIncrement == 0) {
8667 sprintf(buf, "%ld", timeControl/1000);
8669 sprintf(buf, "%ld+%ld", timeControl/1000, timeIncrement/1000);
8671 return StrSave(buf);
8677 /* This routine is used only for certain modes */
8678 VariantClass v = gameInfo.variant;
8679 ClearGameInfo(&gameInfo);
8680 gameInfo.variant = v;
8683 case MachinePlaysWhite:
8684 gameInfo.event = StrSave("Computer chess game");
8685 gameInfo.site = StrSave(HostName());
8686 gameInfo.date = PGNDate();
8687 gameInfo.round = StrSave("-");
8688 gameInfo.white = StrSave(first.tidy);
8689 gameInfo.black = StrSave(UserName());
8690 gameInfo.timeControl = TimeControlTagValue();
8693 case MachinePlaysBlack:
8694 gameInfo.event = StrSave("Computer chess game");
8695 gameInfo.site = StrSave(HostName());
8696 gameInfo.date = PGNDate();
8697 gameInfo.round = StrSave("-");
8698 gameInfo.white = StrSave(UserName());
8699 gameInfo.black = StrSave(first.tidy);
8700 gameInfo.timeControl = TimeControlTagValue();
8703 case TwoMachinesPlay:
8704 gameInfo.event = StrSave("Computer chess game");
8705 gameInfo.site = StrSave(HostName());
8706 gameInfo.date = PGNDate();
8707 if (matchGame > 0) {
8709 sprintf(buf, "%d", matchGame);
8710 gameInfo.round = StrSave(buf);
8712 gameInfo.round = StrSave("-");
8714 if (first.twoMachinesColor[0] == 'w') {
8715 gameInfo.white = StrSave(first.tidy);
8716 gameInfo.black = StrSave(second.tidy);
8718 gameInfo.white = StrSave(second.tidy);
8719 gameInfo.black = StrSave(first.tidy);
8721 gameInfo.timeControl = TimeControlTagValue();
8725 gameInfo.event = StrSave("Edited game");
8726 gameInfo.site = StrSave(HostName());
8727 gameInfo.date = PGNDate();
8728 gameInfo.round = StrSave("-");
8729 gameInfo.white = StrSave("-");
8730 gameInfo.black = StrSave("-");
8734 gameInfo.event = StrSave("Edited position");
8735 gameInfo.site = StrSave(HostName());
8736 gameInfo.date = PGNDate();
8737 gameInfo.round = StrSave("-");
8738 gameInfo.white = StrSave("-");
8739 gameInfo.black = StrSave("-");
8742 case IcsPlayingWhite:
8743 case IcsPlayingBlack:
8748 case PlayFromGameFile:
8749 gameInfo.event = StrSave("Game from non-PGN file");
8750 gameInfo.site = StrSave(HostName());
8751 gameInfo.date = PGNDate();
8752 gameInfo.round = StrSave("-");
8753 gameInfo.white = StrSave("?");
8754 gameInfo.black = StrSave("?");
8763 ReplaceComment(index, text)
8769 while (*text == '\n') text++;
8771 while (len > 0 && text[len - 1] == '\n') len--;
8773 if (commentList[index] != NULL)
8774 free(commentList[index]);
8777 commentList[index] = NULL;
8780 commentList[index] = (char *) malloc(len + 2);
8781 strncpy(commentList[index], text, len);
8782 commentList[index][len] = '\n';
8783 commentList[index][len + 1] = NULLCHAR;
8796 if (ch == '\r') continue;
8798 } while (ch != '\0');
8802 AppendComment(index, text)
8810 while (*text == '\n') text++;
8812 while (len > 0 && text[len - 1] == '\n') len--;
8814 if (len == 0) return;
8816 if (commentList[index] != NULL) {
8817 old = commentList[index];
8818 oldlen = strlen(old);
8819 commentList[index] = (char *) malloc(oldlen + len + 2);
8820 strcpy(commentList[index], old);
8822 strncpy(&commentList[index][oldlen], text, len);
8823 commentList[index][oldlen + len] = '\n';
8824 commentList[index][oldlen + len + 1] = NULLCHAR;
8826 commentList[index] = (char *) malloc(len + 2);
8827 strncpy(commentList[index], text, len);
8828 commentList[index][len] = '\n';
8829 commentList[index][len + 1] = NULLCHAR;
8834 SendToProgram(message, cps)
8836 ChessProgramState *cps;
8838 int count, outCount, error;
8841 if (cps->pr == NULL) return;
8844 if (appData.debugMode) {
8847 fprintf(debugFP, "%ld >%-6s: %s",
8848 SubtractTimeMarks(&now, &programStartTime),
8849 cps->which, message);
8852 count = strlen(message);
8853 outCount = OutputToProcess(cps->pr, message, count, &error);
8854 if (outCount < count && !exiting) {
8855 sprintf(buf, _("Error writing to %s chess program"), cps->which);
8856 DisplayFatalError(buf, error, 1);
8861 ReceiveFromProgram(isr, closure, message, count, error)
8870 ChessProgramState *cps = (ChessProgramState *)closure;
8872 if (isr != cps->isr) return; /* Killed intentionally */
8876 _("Error: %s chess program (%s) exited unexpectedly"),
8877 cps->which, cps->program);
8878 RemoveInputSource(cps->isr);
8879 DisplayFatalError(buf, 0, 1);
8882 _("Error reading from %s chess program (%s)"),
8883 cps->which, cps->program);
8884 RemoveInputSource(cps->isr);
8885 DisplayFatalError(buf, error, 1);
8887 GameEnds((ChessMove) 0, NULL, GE_PLAYER);
8891 if ((end_str = strchr(message, '\r')) != NULL)
8892 *end_str = NULLCHAR;
8893 if ((end_str = strchr(message, '\n')) != NULL)
8894 *end_str = NULLCHAR;
8896 if (appData.debugMode) {
8899 fprintf(debugFP, "%ld <%-6s: %s\n",
8900 SubtractTimeMarks(&now, &programStartTime),
8901 cps->which, message);
8903 HandleMachineMove(message, cps);
8908 SendTimeControl(cps, mps, tc, inc, sd, st)
8909 ChessProgramState *cps;
8910 int mps, inc, sd, st;
8914 int seconds = (tc / 1000) % 60;
8917 /* Set exact time per move, normally using st command */
8918 if (cps->stKludge) {
8919 /* GNU Chess 4 has no st command; uses level in a nonstandard way */
8922 sprintf(buf, "level 1 %d\n", st/60);
8924 sprintf(buf, "level 1 %d:%02d\n", st/60, seconds);
8927 sprintf(buf, "st %d\n", st);
8930 /* Set conventional or incremental time control, using level command */
8932 /* Note old gnuchess bug -- minutes:seconds used to not work.
8933 Fixed in later versions, but still avoid :seconds
8934 when seconds is 0. */
8935 sprintf(buf, "level %d %ld %d\n", mps, tc/60000, inc/1000);
8937 sprintf(buf, "level %d %ld:%02d %d\n", mps, tc/60000,
8941 SendToProgram(buf, cps);
8943 /* Orthoganally (except for GNU Chess 4), limit time to st seconds */
8944 /* Orthogonally, limit search to given depth */
8946 if (cps->sdKludge) {
8947 sprintf(buf, "depth\n%d\n", sd);
8949 sprintf(buf, "sd %d\n", sd);
8951 SendToProgram(buf, cps);
8956 SendTimeRemaining(cps, machineWhite)
8957 ChessProgramState *cps;
8958 int /*boolean*/ machineWhite;
8960 char message[MSG_SIZ];
8963 /* Note: this routine must be called when the clocks are stopped
8964 or when they have *just* been set or switched; otherwise
8965 it will be off by the time since the current tick started.
8968 time = whiteTimeRemaining / 10;
8969 otime = blackTimeRemaining / 10;
8971 time = blackTimeRemaining / 10;
8972 otime = whiteTimeRemaining / 10;
8974 if (time <= 0) time = 1;
8975 if (otime <= 0) otime = 1;
8977 sprintf(message, "time %ld\notim %ld\n", time, otime);
8978 SendToProgram(message, cps);
8982 BoolFeature(p, name, loc, cps)
8986 ChessProgramState *cps;
8989 int len = strlen(name);
8991 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
8993 sscanf(*p, "%d", &val);
8995 while (**p && **p != ' ') (*p)++;
8996 sprintf(buf, "accepted %s\n", name);
8997 SendToProgram(buf, cps);
9004 IntFeature(p, name, loc, cps)
9008 ChessProgramState *cps;
9011 int len = strlen(name);
9012 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
9014 sscanf(*p, "%d", loc);
9015 while (**p && **p != ' ') (*p)++;
9016 sprintf(buf, "accepted %s\n", name);
9017 SendToProgram(buf, cps);
9024 StringFeature(p, name, loc, cps)
9028 ChessProgramState *cps;
9031 int len = strlen(name);
9032 if (strncmp((*p), name, len) == 0
9033 && (*p)[len] == '=' && (*p)[len+1] == '\"') {
9035 sscanf(*p, "%[^\"]", loc);
9036 while (**p && **p != '\"') (*p)++;
9037 if (**p == '\"') (*p)++;
9038 sprintf(buf, "accepted %s\n", name);
9039 SendToProgram(buf, cps);
9046 FeatureDone(cps, val)
9047 ChessProgramState* cps;
9050 DelayedEventCallback cb = GetDelayedEvent();
9051 if ((cb == InitBackEnd3 && cps == &first) ||
9052 (cb == TwoMachinesEventIfReady && cps == &second)) {
9053 CancelDelayedEvent();
9054 ScheduleDelayedEvent(cb, val ? 1 : 3600000);
9056 cps->initDone = val;
9059 /* Parse feature command from engine */
9061 ParseFeatures(args, cps)
9063 ChessProgramState *cps;
9071 while (*p == ' ') p++;
9072 if (*p == NULLCHAR) return;
9074 if (BoolFeature(&p, "setboard", &cps->useSetboard, cps)) continue;
9075 if (BoolFeature(&p, "time", &cps->sendTime, cps)) continue;
9076 if (BoolFeature(&p, "draw", &cps->sendDrawOffers, cps)) continue;
9077 if (BoolFeature(&p, "sigint", &cps->useSigint, cps)) continue;
9078 if (BoolFeature(&p, "sigterm", &cps->useSigterm, cps)) continue;
9079 if (BoolFeature(&p, "reuse", &val, cps)) {
9080 /* Engine can disable reuse, but can't enable it if user said no */
9081 if (!val) cps->reuse = FALSE;
9084 if (BoolFeature(&p, "analyze", &cps->analysisSupport, cps)) continue;
9085 if (StringFeature(&p, "myname", &cps->tidy, cps)) {
9086 if (gameMode == TwoMachinesPlay) {
9087 DisplayTwoMachinesTitle();
9093 if (StringFeature(&p, "variants", &cps->variants, cps)) continue;
9094 if (BoolFeature(&p, "san", &cps->useSAN, cps)) continue;
9095 if (BoolFeature(&p, "ping", &cps->usePing, cps)) continue;
9096 if (BoolFeature(&p, "playother", &cps->usePlayother, cps)) continue;
9097 if (BoolFeature(&p, "colors", &cps->useColors, cps)) continue;
9098 if (BoolFeature(&p, "usermove", &cps->useUsermove, cps)) continue;
9099 if (BoolFeature(&p, "ics", &cps->sendICS, cps)) continue;
9100 if (BoolFeature(&p, "name", &cps->sendName, cps)) continue;
9101 if (BoolFeature(&p, "pause", &val, cps)) continue; /* unused at present */
9102 if (IntFeature(&p, "done", &val, cps)) {
9103 FeatureDone(cps, val);
9107 /* unknown feature: complain and skip */
9109 while (*q && *q != '=') q++;
9110 sprintf(buf, "rejected %.*s\n", q-p, p);
9111 SendToProgram(buf, cps);
9117 while (*p && *p != '\"') p++;
9118 if (*p == '\"') p++;
9120 while (*p && *p != ' ') p++;
9128 PeriodicUpdatesEvent(newState)
9131 if (newState == appData.periodicUpdates)
9134 appData.periodicUpdates=newState;
9136 /* Display type changes, so update it now */
9139 /* Get the ball rolling again... */
9141 AnalysisPeriodicEvent(1);
9142 StartAnalysisClock();
9147 PonderNextMoveEvent(newState)
9150 if (newState == appData.ponderNextMove) return;
9151 if (gameMode == EditPosition) EditPositionDone();
9153 SendToProgram("hard\n", &first);
9154 if (gameMode == TwoMachinesPlay) {
9155 SendToProgram("hard\n", &second);
9158 SendToProgram("easy\n", &first);
9159 thinkOutput[0] = NULLCHAR;
9160 if (gameMode == TwoMachinesPlay) {
9161 SendToProgram("easy\n", &second);
9164 appData.ponderNextMove = newState;
9168 ShowThinkingEvent(newState)
9171 if (newState == appData.showThinking) return;
9172 if (gameMode == EditPosition) EditPositionDone();
9174 SendToProgram("post\n", &first);
9175 if (gameMode == TwoMachinesPlay) {
9176 SendToProgram("post\n", &second);
9179 SendToProgram("nopost\n", &first);
9180 thinkOutput[0] = NULLCHAR;
9181 if (gameMode == TwoMachinesPlay) {
9182 SendToProgram("nopost\n", &second);
9185 appData.showThinking = newState;
9189 AskQuestionEvent(title, question, replyPrefix, which)
9190 char *title; char *question; char *replyPrefix; char *which;
9192 ProcRef pr = (which[0] == '1') ? first.pr : second.pr;
9193 if (pr == NoProc) return;
9194 AskQuestion(title, question, replyPrefix, pr);
9198 DisplayMove(moveNumber)
9201 char message[MSG_SIZ];
9203 char cpThinkOutput[MSG_SIZ];
9205 if (moveNumber == forwardMostMove - 1 ||
9206 gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
9208 strcpy(cpThinkOutput, thinkOutput);
9209 if (strchr(cpThinkOutput, '\n'))
9210 *strchr(cpThinkOutput, '\n') = NULLCHAR;
9212 *cpThinkOutput = NULLCHAR;
9215 if (moveNumber == forwardMostMove - 1 &&
9216 gameInfo.resultDetails != NULL) {
9217 if (gameInfo.resultDetails[0] == NULLCHAR) {
9218 sprintf(res, " %s", PGNResult(gameInfo.result));
9220 sprintf(res, " {%s} %s",
9221 gameInfo.resultDetails, PGNResult(gameInfo.result));
9227 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
9228 DisplayMessage(res, cpThinkOutput);
9230 sprintf(message, "%d.%s%s%s", moveNumber / 2 + 1,
9231 WhiteOnMove(moveNumber) ? " " : ".. ",
9232 parseList[moveNumber], res);
9233 DisplayMessage(message, cpThinkOutput);
9238 DisplayAnalysisText(text)
9243 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
9244 sprintf(buf, "Analysis (%s)", first.tidy);
9245 AnalysisPopUp(buf, text);
9253 while (*str && isspace(*str)) ++str;
9254 while (*str && !isspace(*str)) ++str;
9255 if (!*str) return 1;
9256 while (*str && isspace(*str)) ++str;
9257 if (!*str) return 1;
9266 static char *xtra[] = { "", " (--)", " (++)" };
9269 if (programStats.time == 0) {
9270 programStats.time = 1;
9273 if (programStats.got_only_move) {
9274 strcpy(buf, programStats.movelist);
9276 nps = (u64ToDouble(programStats.nodes) /
9277 ((double)programStats.time /100.0));
9279 cs = programStats.time % 100;
9280 s = programStats.time / 100;
9286 if (programStats.moves_left > 0 && appData.periodicUpdates) {
9287 if (programStats.move_name[0] != NULLCHAR) {
9288 sprintf(buf, "depth=%d %d/%d(%s) %+.2f %s%s\nNodes: "u64Display" NPS: %d\nTime: %02d:%02d:%02d.%02d",
9290 programStats.nr_moves-programStats.moves_left,
9291 programStats.nr_moves, programStats.move_name,
9292 ((float)programStats.score)/100.0, programStats.movelist,
9293 only_one_move(programStats.movelist)?
9294 xtra[programStats.got_fail] : "",
9295 (u64)programStats.nodes, (int)nps, h, m, s, cs);
9297 sprintf(buf, "depth=%d %d/%d %+.2f %s%s\nNodes: "u64Display" NPS: %d\nTime: %02d:%02d:%02d.%02d",
9299 programStats.nr_moves-programStats.moves_left,
9300 programStats.nr_moves, ((float)programStats.score)/100.0,
9301 programStats.movelist,
9302 only_one_move(programStats.movelist)?
9303 xtra[programStats.got_fail] : "",
9304 (u64)programStats.nodes, (int)nps, h, m, s, cs);
9307 sprintf(buf, "depth=%d %+.2f %s%s\nNodes: "u64Display" NPS: %d\nTime: %02d:%02d:%02d.%02d",
9309 ((float)programStats.score)/100.0,
9310 programStats.movelist,
9311 only_one_move(programStats.movelist)?
9312 xtra[programStats.got_fail] : "",
9313 (u64)programStats.nodes, (int)nps, h, m, s, cs);
9316 DisplayAnalysisText(buf);
9320 DisplayComment(moveNumber, text)
9324 char title[MSG_SIZ];
9326 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
9327 strcpy(title, "Comment");
9329 sprintf(title, "Comment on %d.%s%s", moveNumber / 2 + 1,
9330 WhiteOnMove(moveNumber) ? " " : ".. ",
9331 parseList[moveNumber]);
9334 CommentPopUp(title, text);
9337 /* This routine sends a ^C interrupt to gnuchess, to awaken it if it
9338 * might be busy thinking or pondering. It can be omitted if your
9339 * gnuchess is configured to stop thinking immediately on any user
9340 * input. However, that gnuchess feature depends on the FIONREAD
9341 * ioctl, which does not work properly on some flavors of Unix.
9345 ChessProgramState *cps;
9348 if (!cps->useSigint) return;
9349 if (appData.noChessProgram || (cps->pr == NoProc)) return;
9351 case MachinePlaysWhite:
9352 case MachinePlaysBlack:
9353 case TwoMachinesPlay:
9354 case IcsPlayingWhite:
9355 case IcsPlayingBlack:
9358 /* Skip if we know it isn't thinking */
9359 if (!cps->maybeThinking) return;
9360 if (appData.debugMode)
9361 fprintf(debugFP, "Interrupting %s\n", cps->which);
9362 InterruptChildProcess(cps->pr);
9363 cps->maybeThinking = FALSE;
9368 #endif /*ATTENTION*/
9374 if (whiteTimeRemaining <= 0) {
9377 if (appData.icsActive) {
9378 if (appData.autoCallFlag &&
9379 gameMode == IcsPlayingBlack && !blackFlag) {
9380 SendToICS(ics_prefix);
9381 SendToICS("flag\n");
9385 DisplayTitle(_("Both flags fell"));
9387 DisplayTitle(_("White's flag fell"));
9388 if (appData.autoCallFlag) {
9389 GameEnds(BlackWins, "Black wins on time", GE_XBOARD);
9396 if (blackTimeRemaining <= 0) {
9399 if (appData.icsActive) {
9400 if (appData.autoCallFlag &&
9401 gameMode == IcsPlayingWhite && !whiteFlag) {
9402 SendToICS(ics_prefix);
9403 SendToICS("flag\n");
9407 DisplayTitle(_("Both flags fell"));
9409 DisplayTitle(_("Black's flag fell"));
9410 if (appData.autoCallFlag) {
9411 GameEnds(WhiteWins, "White wins on time", GE_XBOARD);
9424 if (!appData.clockMode || appData.icsActive ||
9425 gameMode == PlayFromGameFile || forwardMostMove == 0) return;
9427 if (timeIncrement >= 0) {
9428 if (WhiteOnMove(forwardMostMove)) {
9429 blackTimeRemaining += timeIncrement;
9431 whiteTimeRemaining += timeIncrement;
9435 * add time to clocks when time control is achieved
9437 if (movesPerSession) {
9438 switch ((forwardMostMove + 1) % (movesPerSession * 2)) {
9440 /* White made time control */
9441 whiteTimeRemaining += timeControl;
9444 /* Black made time control */
9445 blackTimeRemaining += timeControl;
9456 int wom = gameMode == EditPosition ?
9457 !blackPlaysFirst : WhiteOnMove(currentMove);
9458 DisplayWhiteClock(whiteTimeRemaining, wom);
9459 DisplayBlackClock(blackTimeRemaining, !wom);
9463 /* Timekeeping seems to be a portability nightmare. I think everyone
9464 has ftime(), but I'm really not sure, so I'm including some ifdefs
9465 to use other calls if you don't. Clocks will be less accurate if
9466 you have neither ftime nor gettimeofday.
9469 /* Get the current time as a TimeMark */
9474 #if HAVE_GETTIMEOFDAY
9476 struct timeval timeVal;
9477 struct timezone timeZone;
9479 gettimeofday(&timeVal, &timeZone);
9480 tm->sec = (long) timeVal.tv_sec;
9481 tm->ms = (int) (timeVal.tv_usec / 1000L);
9483 #else /*!HAVE_GETTIMEOFDAY*/
9486 #include <sys/timeb.h>
9490 tm->sec = (long) timeB.time;
9491 tm->ms = (int) timeB.millitm;
9493 #else /*!HAVE_FTIME && !HAVE_GETTIMEOFDAY*/
9494 tm->sec = (long) time(NULL);
9500 /* Return the difference in milliseconds between two
9501 time marks. We assume the difference will fit in a long!
9504 SubtractTimeMarks(tm2, tm1)
9505 TimeMark *tm2, *tm1;
9507 return 1000L*(tm2->sec - tm1->sec) +
9508 (long) (tm2->ms - tm1->ms);
9513 * Code to manage the game clocks.
9515 * In tournament play, black starts the clock and then white makes a move.
9516 * We give the human user a slight advantage if he is playing white---the
9517 * clocks don't run until he makes his first move, so it takes zero time.
9518 * Also, we don't account for network lag, so we could get out of sync
9519 * with GNU Chess's clock -- but then, referees are always right.
9522 static TimeMark tickStartTM;
9523 static long intendedTickLength;
9526 NextTickLength(timeRemaining)
9529 long nominalTickLength, nextTickLength;
9531 if (timeRemaining > 0L && timeRemaining <= 10000L)
9532 nominalTickLength = 100L;
9534 nominalTickLength = 1000L;
9535 nextTickLength = timeRemaining % nominalTickLength;
9536 if (nextTickLength <= 0) nextTickLength += nominalTickLength;
9538 return nextTickLength;
9541 /* Stop clocks and reset to a fresh time control */
9545 (void) StopClockTimer();
9546 if (appData.icsActive) {
9547 whiteTimeRemaining = blackTimeRemaining = 0;
9549 whiteTimeRemaining = blackTimeRemaining = timeControl;
9551 if (whiteFlag || blackFlag) {
9553 whiteFlag = blackFlag = FALSE;
9555 DisplayBothClocks();
9558 #define FUDGE 25 /* 25ms = 1/40 sec; should be plenty even for 50 Hz clocks */
9560 /* Decrement running clock by amount of time that has passed */
9565 long lastTickLength, fudge;
9568 if (!appData.clockMode) return;
9569 if (gameMode==AnalyzeMode || gameMode == AnalyzeFile) return;
9573 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
9575 /* Fudge if we woke up a little too soon */
9576 fudge = intendedTickLength - lastTickLength;
9577 if (fudge < 0 || fudge > FUDGE) fudge = 0;
9579 if (WhiteOnMove(forwardMostMove)) {
9580 timeRemaining = whiteTimeRemaining -= lastTickLength;
9581 DisplayWhiteClock(whiteTimeRemaining - fudge,
9582 WhiteOnMove(currentMove));
9584 timeRemaining = blackTimeRemaining -= lastTickLength;
9585 DisplayBlackClock(blackTimeRemaining - fudge,
9586 !WhiteOnMove(currentMove));
9589 if (CheckFlags()) return;
9592 intendedTickLength = NextTickLength(timeRemaining - fudge) + fudge;
9593 StartClockTimer(intendedTickLength);
9595 /* if the time remaining has fallen below the alarm threshold, sound the
9596 * alarm. if the alarm has sounded and (due to a takeback or time control
9597 * with increment) the time remaining has increased to a level above the
9598 * threshold, reset the alarm so it can sound again.
9601 if (appData.icsActive && appData.icsAlarm) {
9603 /* make sure we are dealing with the user's clock */
9604 if (!( ((gameMode == IcsPlayingWhite) && WhiteOnMove(currentMove)) ||
9605 ((gameMode == IcsPlayingBlack) && !WhiteOnMove(currentMove))
9608 if (alarmSounded && (timeRemaining > appData.icsAlarmTime)) {
9609 alarmSounded = FALSE;
9610 } else if (!alarmSounded && (timeRemaining <= appData.icsAlarmTime)) {
9612 alarmSounded = TRUE;
9618 /* A player has just moved, so stop the previously running
9619 clock and (if in clock mode) start the other one.
9620 We redisplay both clocks in case we're in ICS mode, because
9621 ICS gives us an update to both clocks after every move.
9622 Note that this routine is called *after* forwardMostMove
9623 is updated, so the last fractional tick must be subtracted
9624 from the color that is *not* on move now.
9629 long lastTickLength;
9631 int flagged = FALSE;
9635 if (StopClockTimer() && appData.clockMode) {
9636 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
9637 if (WhiteOnMove(forwardMostMove)) {
9638 blackTimeRemaining -= lastTickLength;
9640 whiteTimeRemaining -= lastTickLength;
9642 flagged = CheckFlags();
9646 if (flagged || !appData.clockMode) return;
9649 case MachinePlaysBlack:
9650 case MachinePlaysWhite:
9651 case BeginningOfGame:
9652 if (pausing) return;
9656 case PlayFromGameFile:
9665 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
9666 whiteTimeRemaining : blackTimeRemaining);
9667 StartClockTimer(intendedTickLength);
9671 /* Stop both clocks */
9675 long lastTickLength;
9678 if (!StopClockTimer()) return;
9679 if (!appData.clockMode) return;
9683 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
9684 if (WhiteOnMove(forwardMostMove)) {
9685 whiteTimeRemaining -= lastTickLength;
9686 DisplayWhiteClock(whiteTimeRemaining, WhiteOnMove(currentMove));
9688 blackTimeRemaining -= lastTickLength;
9689 DisplayBlackClock(blackTimeRemaining, !WhiteOnMove(currentMove));
9694 /* Start clock of player on move. Time may have been reset, so
9695 if clock is already running, stop and restart it. */
9699 (void) StopClockTimer(); /* in case it was running already */
9700 DisplayBothClocks();
9701 if (CheckFlags()) return;
9703 if (!appData.clockMode) return;
9704 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) return;
9706 GetTimeMark(&tickStartTM);
9707 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
9708 whiteTimeRemaining : blackTimeRemaining);
9709 StartClockTimer(intendedTickLength);
9716 long second, minute, hour, day;
9718 static char buf[32];
9720 if (ms > 0 && ms <= 9900) {
9721 /* convert milliseconds to tenths, rounding up */
9722 double tenths = floor( ((double)(ms + 99L)) / 100.00 );
9724 sprintf(buf, " %03.1f ", tenths/10.0);
9728 /* convert milliseconds to seconds, rounding up */
9729 /* use floating point to avoid strangeness of integer division
9730 with negative dividends on many machines */
9731 second = (long) floor(((double) (ms + 999L)) / 1000.0);
9738 day = second / (60 * 60 * 24);
9739 second = second % (60 * 60 * 24);
9740 hour = second / (60 * 60);
9741 second = second % (60 * 60);
9742 minute = second / 60;
9743 second = second % 60;
9746 sprintf(buf, " %s%ld:%02ld:%02ld:%02ld ",
9747 sign, day, hour, minute, second);
9749 sprintf(buf, " %s%ld:%02ld:%02ld ", sign, hour, minute, second);
9751 sprintf(buf, " %s%2ld:%02ld ", sign, minute, second);
9758 * This is necessary because some C libraries aren't ANSI C compliant yet.
9761 StrStr(string, match)
9762 char *string, *match;
9766 length = strlen(match);
9768 for (i = strlen(string) - length; i >= 0; i--, string++)
9769 if (!strncmp(match, string, length))
9776 StrCaseStr(string, match)
9777 char *string, *match;
9781 length = strlen(match);
9783 for (i = strlen(string) - length; i >= 0; i--, string++) {
9784 for (j = 0; j < length; j++) {
9785 if (ToLower(match[j]) != ToLower(string[j]))
9788 if (j == length) return string;
9802 c1 = ToLower(*s1++);
9803 c2 = ToLower(*s2++);
9804 if (c1 > c2) return 1;
9805 if (c1 < c2) return -1;
9806 if (c1 == NULLCHAR) return 0;
9815 return isupper(c) ? tolower(c) : c;
9823 return islower(c) ? toupper(c) : c;
9825 #endif /* !_amigados */
9833 if ((ret = (char *) malloc(strlen(s) + 1))) {
9840 StrSavePtr(s, savePtr)
9846 if ((*savePtr = (char *) malloc(strlen(s) + 1))) {
9847 strcpy(*savePtr, s);
9859 clock = time((time_t *)NULL);
9860 tm = localtime(&clock);
9861 sprintf(buf, "%04d.%02d.%02d",
9862 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday);
9863 return StrSave(buf);
9871 int i, j, fromX, fromY, toX, toY;
9877 whiteToPlay = (gameMode == EditPosition) ?
9878 !blackPlaysFirst : (move % 2 == 0);
9881 /* Piece placement data */
9882 for (i = BOARD_SIZE - 1; i >= 0; i--) {
9884 for (j = 0; j < BOARD_SIZE; j++) {
9885 if (boards[move][i][j] == EmptySquare) {
9888 if (emptycount > 0) {
9889 *p++ = '0' + emptycount;
9892 *p++ = PieceToChar(boards[move][i][j]);
9895 if (emptycount > 0) {
9896 *p++ = '0' + emptycount;
9904 *p++ = whiteToPlay ? 'w' : 'b';
9907 /* !!We don't keep track of castling availability, so fake it */
9909 if (boards[move][0][4] == WhiteKing) {
9910 if (boards[move][0][7] == WhiteRook) *p++ = 'K';
9911 if (boards[move][0][0] == WhiteRook) *p++ = 'Q';
9913 if (boards[move][7][4] == BlackKing) {
9914 if (boards[move][7][7] == BlackRook) *p++ = 'k';
9915 if (boards[move][7][0] == BlackRook) *p++ = 'q';
9917 if (q == p) *p++ = '-';
9920 /* En passant target square */
9921 if (move > backwardMostMove) {
9922 fromX = moveList[move - 1][0] - 'a';
9923 fromY = moveList[move - 1][1] - '1';
9924 toX = moveList[move - 1][2] - 'a';
9925 toY = moveList[move - 1][3] - '1';
9926 if (fromY == (whiteToPlay ? 6 : 1) &&
9927 toY == (whiteToPlay ? 4 : 3) &&
9928 boards[move][toY][toX] == (whiteToPlay ? BlackPawn : WhitePawn) &&
9930 /* 2-square pawn move just happened */
9932 *p++ = whiteToPlay ? '6' : '3';
9940 /* !!We don't keep track of halfmove clock for 50-move rule */
9944 /* Fullmove number */
9945 sprintf(p, "%d", (move / 2) + 1);
9947 return StrSave(buf);
9951 ParseFEN(board, blackPlaysFirst, fen)
9953 int *blackPlaysFirst;
9962 /* Piece placement data */
9963 for (i = BOARD_SIZE - 1; i >= 0; i--) {
9966 if (*p == '/' || *p == ' ') {
9968 emptycount = BOARD_SIZE - j;
9969 while (emptycount--) board[i][j++] = EmptySquare;
9971 } else if (isdigit(*p)) {
9972 emptycount = *p++ - '0';
9973 if (j + emptycount > BOARD_SIZE) return FALSE;
9974 while (emptycount--) board[i][j++] = EmptySquare;
9975 } else if (isalpha(*p)) {
9976 if (j >= BOARD_SIZE) return FALSE;
9977 board[i][j++] = CharToPiece(*p++);
9983 while (*p == '/' || *p == ' ') p++;
9988 *blackPlaysFirst = FALSE;
9991 *blackPlaysFirst = TRUE;
9996 /* !!We ignore the rest of the FEN notation */
10001 EditPositionPasteFEN(char *fen)
10004 Board initial_position;
10006 if (!ParseFEN(initial_position, &blackPlaysFirst, fen)) {
10007 DisplayError(_("Bad FEN position in clipboard"), 0);
10010 int savedBlackPlaysFirst = blackPlaysFirst;
10011 EditPositionEvent();
10012 blackPlaysFirst = savedBlackPlaysFirst;
10013 CopyBoard(boards[0], initial_position);
10014 EditPositionDone();
10015 DisplayBothClocks();
10016 DrawPosition(FALSE, boards[currentMove]);