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"
111 /* A point in time */
113 long sec; /* Assuming this is >= 32 bits */
114 int ms; /* Assuming this is >= 16 bits */
117 /* Search stats from chessprogram */
119 char movelist[2*MSG_SIZ]; /* Last PV we were sent */
120 int depth; /* Current search depth */
121 int nr_moves; /* Total nr of root moves */
122 int moves_left; /* Moves remaining to be searched */
123 char move_name[MOVE_LEN]; /* Current move being searched, if provided */
124 unsigned long nodes; /* # of nodes searched */
125 int time; /* Search time (centiseconds) */
126 int score; /* Score (centipawns) */
127 int got_only_move; /* If last msg was "(only move)" */
128 int got_fail; /* 0 - nothing, 1 - got "--", 2 - got "++" */
129 int ok_to_send; /* handshaking between send & recv */
130 int line_is_book; /* 1 if movelist is book moves */
131 int seen_stat; /* 1 if we've seen the stat01: line */
134 int establish P((void));
135 void read_from_player P((InputSourceRef isr, VOIDSTAR closure,
136 char *buf, int count, int error));
137 void read_from_ics P((InputSourceRef isr, VOIDSTAR closure,
138 char *buf, int count, int error));
139 void SendToICS P((char *s));
140 void SendToICSDelayed P((char *s, long msdelay));
141 void SendMoveToICS P((ChessMove moveType, int fromX, int fromY,
143 void InitPosition P((int redraw));
144 void HandleMachineMove P((char *message, ChessProgramState *cps));
145 int AutoPlayOneMove P((void));
146 int LoadGameOneMove P((ChessMove readAhead));
147 int LoadGameFromFile P((char *filename, int n, char *title, int useList));
148 int LoadPositionFromFile P((char *filename, int n, char *title));
149 int SavePositionToFile P((char *filename));
150 void ApplyMove P((int fromX, int fromY, int toX, int toY, int promoChar,
152 void MakeMove P((int fromX, int fromY, int toX, int toY, int promoChar));
153 void ShowMove P((int fromX, int fromY, int toX, int toY));
154 void FinishMove P((ChessMove moveType, int fromX, int fromY, int toX, int toY,
155 /*char*/int promoChar));
156 void BackwardInner P((int target));
157 void ForwardInner P((int target));
158 void GameEnds P((ChessMove result, char *resultDetails, int whosays));
159 void EditPositionDone P((void));
160 void PrintOpponents P((FILE *fp));
161 void PrintPosition P((FILE *fp, int move));
162 void StartChessProgram P((ChessProgramState *cps));
163 void SendToProgram P((char *message, ChessProgramState *cps));
164 void SendMoveToProgram P((int moveNum, ChessProgramState *cps));
165 void ReceiveFromProgram P((InputSourceRef isr, VOIDSTAR closure,
166 char *buf, int count, int error));
167 void SendTimeControl P((ChessProgramState *cps,
168 int mps, long tc, int inc, int sd, int st));
169 char *TimeControlTagValue P((void));
170 void Attention P((ChessProgramState *cps));
171 void FeedMovesToProgram P((ChessProgramState *cps, int upto));
172 void ResurrectChessProgram P((void));
173 void DisplayComment P((int moveNumber, char *text));
174 void DisplayMove P((int moveNumber));
175 void DisplayAnalysis P((void));
177 void ParseGameHistory P((char *game));
178 void ParseBoard12 P((char *string));
179 void StartClocks P((void));
180 void SwitchClocks P((void));
181 void StopClocks P((void));
182 void ResetClocks P((void));
183 char *PGNDate P((void));
184 void SetGameInfo P((void));
185 Boolean ParseFEN P((Board board, int *blackPlaysFirst, char *fen));
186 int RegisterMove P((void));
187 void MakeRegisteredMove P((void));
188 void TruncateGame P((void));
189 int looking_at P((char *, int *, char *));
190 void CopyPlayerNameIntoFileName P((char **, char *));
191 char *SavePart P((char *));
192 int SaveGameOldStyle P((FILE *));
193 int SaveGamePGN P((FILE *));
194 void GetTimeMark P((TimeMark *));
195 long SubtractTimeMarks P((TimeMark *, TimeMark *));
196 int CheckFlags P((void));
197 long NextTickLength P((long));
198 void CheckTimeControl P((void));
199 void show_bytes P((FILE *, char *, int));
200 int string_to_rating P((char *str));
201 void ParseFeatures P((char* args, ChessProgramState *cps));
202 void InitBackEnd3 P((void));
203 void FeatureDone P((ChessProgramState* cps, int val));
204 void InitChessProgram P((ChessProgramState *cps));
206 extern int tinyLayout, smallLayout;
207 static ChessProgramStats programStats;
209 /* States for ics_getting_history */
211 #define H_REQUESTED 1
212 #define H_GOT_REQ_HEADER 2
213 #define H_GOT_UNREQ_HEADER 3
214 #define H_GETTING_MOVES 4
215 #define H_GOT_UNWANTED_HEADER 5
217 /* whosays values for GameEnds */
224 /* Maximum number of games in a cmail message */
225 #define CMAIL_MAX_GAMES 20
227 /* Different types of move when calling RegisterMove */
229 #define CMAIL_RESIGN 1
231 #define CMAIL_ACCEPT 3
233 /* Different types of result to remember for each game */
234 #define CMAIL_NOT_RESULT 0
235 #define CMAIL_OLD_RESULT 1
236 #define CMAIL_NEW_RESULT 2
238 /* Telnet protocol constants */
248 /* Fake up flags for now, as we aren't keeping track of castling
253 int flags = F_ALL_CASTLE_OK;
254 if ((index % 2) == 0) flags |= F_WHITE_ON_MOVE;
255 switch (gameInfo.variant) {
257 case VariantGiveaway:
258 flags |= F_IGNORE_CHECK;
259 flags &= ~F_ALL_CASTLE_OK;
262 flags |= F_IGNORE_CHECK | F_ATOMIC_CAPTURE;
264 case VariantKriegspiel:
265 flags |= F_KRIEGSPIEL_CAPTURE;
267 case VariantNoCastle:
268 flags &= ~F_ALL_CASTLE_OK;
276 FILE *gameFileFP, *debugFP;
278 char cmailMove[CMAIL_MAX_GAMES][MOVE_LEN], cmailMsg[MSG_SIZ];
279 char bookOutput[MSG_SIZ*10], thinkOutput[MSG_SIZ*10], lastHint[MSG_SIZ];
280 char thinkOutput1[MSG_SIZ*10];
282 ChessProgramState first, second;
284 /* premove variables */
287 int premoveFromX = 0;
288 int premoveFromY = 0;
289 int premovePromoChar = 0;
291 Boolean alarmSounded;
292 /* end premove variables */
294 #define ICS_GENERIC 0
297 #define ICS_CHESSNET 3 /* not really supported */
298 int ics_type = ICS_GENERIC;
299 char *ics_prefix = "$";
301 int currentMove = 0, forwardMostMove = 0, backwardMostMove = 0;
302 int pauseExamForwardMostMove = 0;
303 int nCmailGames = 0, nCmailResults = 0, nCmailMovesRegistered = 0;
304 int cmailMoveRegistered[CMAIL_MAX_GAMES], cmailResult[CMAIL_MAX_GAMES];
305 int cmailMsgLoaded = FALSE, cmailMailedMove = FALSE;
306 int cmailOldMove = -1, firstMove = TRUE, flipView = FALSE;
307 int blackPlaysFirst = FALSE, startedFromSetupPosition = FALSE;
308 int searchTime = 0, pausing = FALSE, pauseExamInvalid = FALSE;
309 int whiteFlag = FALSE, blackFlag = FALSE;
310 int userOfferedDraw = FALSE;
311 int ics_user_moved = 0, ics_gamenum = -1, ics_getting_history = H_FALSE;
312 int matchMode = FALSE, hintRequested = FALSE, bookRequested = FALSE;
313 int cmailMoveType[CMAIL_MAX_GAMES];
314 long ics_clock_paused = 0;
315 ProcRef icsPR = NoProc, cmailPR = NoProc;
316 InputSourceRef telnetISR = NULL, fromUserISR = NULL, cmailISR = NULL;
317 GameMode gameMode = BeginningOfGame;
318 char moveList[MAX_MOVES][MOVE_LEN], parseList[MAX_MOVES][MOVE_LEN * 2];
319 char *commentList[MAX_MOVES], *cmailCommentList[CMAIL_MAX_GAMES];
320 char white_holding[64], black_holding[64];
321 TimeMark lastNodeCountTime;
322 long lastNodeCount=0;
323 int have_sent_ICS_logon = 0;
325 long whiteTimeRemaining, blackTimeRemaining, timeControl, timeIncrement;
326 long timeRemaining[2][MAX_MOVES];
328 TimeMark programStartTime;
329 char ics_handle[MSG_SIZ];
330 int have_set_title = 0;
332 /* animateTraining preserves the state of appData.animate
333 * when Training mode is activated. This allows the
334 * response to be animated when appData.animate == TRUE and
335 * appData.animateDragging == TRUE.
337 Boolean animateTraining;
343 Board boards[MAX_MOVES];
344 Board initialPosition = {
345 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
346 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
347 { WhitePawn, WhitePawn, WhitePawn, WhitePawn,
348 WhitePawn, WhitePawn, WhitePawn, WhitePawn },
349 { EmptySquare, EmptySquare, EmptySquare, EmptySquare,
350 EmptySquare, EmptySquare, EmptySquare, EmptySquare },
351 { EmptySquare, EmptySquare, EmptySquare, EmptySquare,
352 EmptySquare, EmptySquare, EmptySquare, EmptySquare },
353 { EmptySquare, EmptySquare, EmptySquare, EmptySquare,
354 EmptySquare, EmptySquare, EmptySquare, EmptySquare },
355 { EmptySquare, EmptySquare, EmptySquare, EmptySquare,
356 EmptySquare, EmptySquare, EmptySquare, EmptySquare },
357 { BlackPawn, BlackPawn, BlackPawn, BlackPawn,
358 BlackPawn, BlackPawn, BlackPawn, BlackPawn },
359 { BlackRook, BlackKnight, BlackBishop, BlackQueen,
360 BlackKing, BlackBishop, BlackKnight, BlackRook }
362 Board twoKingsPosition = {
363 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
364 WhiteKing, WhiteKing, WhiteKnight, WhiteRook },
365 { WhitePawn, WhitePawn, WhitePawn, WhitePawn,
366 WhitePawn, WhitePawn, WhitePawn, WhitePawn },
367 { EmptySquare, EmptySquare, EmptySquare, EmptySquare,
368 EmptySquare, EmptySquare, EmptySquare, EmptySquare },
369 { EmptySquare, EmptySquare, EmptySquare, EmptySquare,
370 EmptySquare, EmptySquare, EmptySquare, EmptySquare },
371 { EmptySquare, EmptySquare, EmptySquare, EmptySquare,
372 EmptySquare, EmptySquare, EmptySquare, EmptySquare },
373 { EmptySquare, EmptySquare, EmptySquare, EmptySquare,
374 EmptySquare, EmptySquare, EmptySquare, EmptySquare },
375 { BlackPawn, BlackPawn, BlackPawn, BlackPawn,
376 BlackPawn, BlackPawn, BlackPawn, BlackPawn },
377 { BlackRook, BlackKnight, BlackBishop, BlackQueen,
378 BlackKing, BlackKing, BlackKnight, BlackRook }
382 /* Convert str to a rating. Checks for special cases of "----",
383 "++++", etc. Also strips ()'s */
385 string_to_rating(str)
388 while(*str && !isdigit(*str)) ++str;
390 return 0; /* One of the special "no rating" cases */
398 /* Init programStats */
399 programStats.movelist[0] = 0;
400 programStats.depth = 0;
401 programStats.nr_moves = 0;
402 programStats.moves_left = 0;
403 programStats.nodes = 0;
404 programStats.time = 100;
405 programStats.score = 0;
406 programStats.got_only_move = 0;
407 programStats.got_fail = 0;
408 programStats.line_is_book = 0;
414 int matched, min, sec;
416 GetTimeMark(&programStartTime);
419 programStats.ok_to_send = 1;
420 programStats.seen_stat = 0;
423 * Initialize game list
429 * Internet chess server status
431 if (appData.icsActive) {
432 appData.matchMode = FALSE;
433 appData.matchGames = 0;
435 appData.noChessProgram = !appData.zippyPlay;
437 appData.zippyPlay = FALSE;
438 appData.zippyTalk = FALSE;
439 appData.noChessProgram = TRUE;
441 if (*appData.icsHelper != NULLCHAR) {
442 appData.useTelnet = TRUE;
443 appData.telnetProgram = appData.icsHelper;
446 appData.zippyTalk = appData.zippyPlay = FALSE;
450 * Parse timeControl resource
452 if (!ParseTimeControl(appData.timeControl, appData.timeIncrement,
453 appData.movesPerSession)) {
455 sprintf(buf, "bad timeControl option %s", appData.timeControl);
456 DisplayFatalError(buf, 0, 2);
460 * Parse searchTime resource
462 if (*appData.searchTime != NULLCHAR) {
463 matched = sscanf(appData.searchTime, "%d:%d", &min, &sec);
465 searchTime = min * 60;
466 } else if (matched == 2) {
467 searchTime = min * 60 + sec;
470 sprintf(buf, "bad searchTime option %s", appData.searchTime);
471 DisplayFatalError(buf, 0, 2);
475 first.which = "first";
476 second.which = "second";
477 first.maybeThinking = second.maybeThinking = FALSE;
478 first.pr = second.pr = NoProc;
479 first.isr = second.isr = NULL;
480 first.sendTime = second.sendTime = 2;
481 first.sendDrawOffers = 1;
482 if (appData.firstPlaysBlack) {
483 first.twoMachinesColor = "black\n";
484 second.twoMachinesColor = "white\n";
486 first.twoMachinesColor = "white\n";
487 second.twoMachinesColor = "black\n";
489 first.program = appData.firstChessProgram;
490 second.program = appData.secondChessProgram;
491 first.host = appData.firstHost;
492 second.host = appData.secondHost;
493 first.dir = appData.firstDirectory;
494 second.dir = appData.secondDirectory;
495 first.other = &second;
496 second.other = &first;
497 first.initString = appData.initString;
498 second.initString = appData.secondInitString;
499 first.computerString = appData.firstComputerString;
500 second.computerString = appData.secondComputerString;
501 first.useSigint = second.useSigint = TRUE;
502 first.useSigterm = second.useSigterm = TRUE;
503 first.reuse = appData.reuseFirst;
504 second.reuse = appData.reuseSecond;
505 first.useSetboard = second.useSetboard = FALSE;
506 first.useSAN = second.useSAN = FALSE;
507 first.usePing = second.usePing = FALSE;
508 first.lastPing = second.lastPing = 0;
509 first.lastPong = second.lastPong = 0;
510 first.usePlayother = second.usePlayother = FALSE;
511 first.useColors = second.useColors = TRUE;
512 first.useUsermove = second.useUsermove = FALSE;
513 first.sendICS = second.sendICS = FALSE;
514 first.sendName = second.sendName = appData.icsActive;
515 first.sdKludge = second.sdKludge = FALSE;
516 first.stKludge = second.stKludge = FALSE;
517 TidyProgramName(first.program, first.host, first.tidy);
518 TidyProgramName(second.program, second.host, second.tidy);
519 first.matchWins = second.matchWins = 0;
520 strcpy(first.variants, appData.variant);
521 strcpy(second.variants, appData.variant);
522 first.analysisSupport = second.analysisSupport = 2; /* detect */
523 first.analyzing = second.analyzing = FALSE;
524 first.initDone = second.initDone = FALSE;
526 if (appData.firstProtocolVersion > PROTOVER ||
527 appData.firstProtocolVersion < 1) {
529 sprintf(buf, "protocol version %d not supported",
530 appData.firstProtocolVersion);
531 DisplayFatalError(buf, 0, 2);
533 first.protocolVersion = appData.firstProtocolVersion;
536 if (appData.secondProtocolVersion > PROTOVER ||
537 appData.secondProtocolVersion < 1) {
539 sprintf(buf, "protocol version %d not supported",
540 appData.secondProtocolVersion);
541 DisplayFatalError(buf, 0, 2);
543 second.protocolVersion = appData.secondProtocolVersion;
546 if (appData.icsActive) {
547 appData.clockMode = TRUE; /* changes dynamically in ICS mode */
548 } else if (*appData.searchTime != NULLCHAR || appData.noChessProgram) {
549 appData.clockMode = FALSE;
550 first.sendTime = second.sendTime = 0;
554 /* Override some settings from environment variables, for backward
555 compatibility. Unfortunately it's not feasible to have the env
556 vars just set defaults, at least in xboard. Ugh.
558 if (appData.icsActive && (appData.zippyPlay || appData.zippyTalk)) {
563 if (appData.noChessProgram) {
564 programVersion = (char*) malloc(5 + strlen(PRODUCT) + strlen(VERSION)
565 + strlen(PATCHLEVEL));
566 sprintf(programVersion, "%s %s.%s", PRODUCT, VERSION, PATCHLEVEL);
570 while (*q != ' ' && *q != NULLCHAR) q++;
572 while (p > first.program && *(p-1) != '/') p--;
573 programVersion = (char*) malloc(8 + strlen(PRODUCT) + strlen(VERSION)
574 + strlen(PATCHLEVEL) + (q - p));
575 sprintf(programVersion, "%s %s.%s + ", PRODUCT, VERSION, PATCHLEVEL);
576 strncat(programVersion, p, q - p);
579 if (!appData.icsActive) {
581 /* Check for variants that are supported only in ICS mode,
582 or not at all. Some that are accepted here nevertheless
583 have bugs; see comments below.
585 VariantClass variant = StringToVariant(appData.variant);
587 case VariantBughouse: /* need four players and two boards */
588 case VariantKriegspiel: /* need to hide pieces and move details */
589 case VariantFischeRandom: /* castling doesn't work, shuffle not done */
590 sprintf(buf, "Variant %s supported only in ICS mode", appData.variant);
591 DisplayFatalError(buf, 0, 2);
595 case VariantLoadable:
605 sprintf(buf, "Unknown variant name %s", appData.variant);
606 DisplayFatalError(buf, 0, 2);
609 case VariantNormal: /* definitely works! */
610 case VariantWildCastle: /* pieces not automatically shuffled */
611 case VariantNoCastle: /* pieces not automatically shuffled */
612 case VariantCrazyhouse: /* holdings not shown,
613 offboard interposition not understood */
614 case VariantLosers: /* should work except for win condition,
615 and doesn't know captures are mandatory */
616 case VariantSuicide: /* should work except for win condition,
617 and doesn't know captures are mandatory */
618 case VariantGiveaway: /* should work except for win condition,
619 and doesn't know captures are mandatory */
620 case VariantTwoKings: /* should work */
621 case VariantAtomic: /* should work except for win condition */
622 case Variant3Check: /* should work except for win condition */
623 case VariantShatranj: /* might work if TestLegality is off */
630 ParseTimeControl(tc, ti, mps)
635 int matched, min, sec;
637 matched = sscanf(tc, "%d:%d", &min, &sec);
639 timeControl = min * 60 * 1000;
640 } else if (matched == 2) {
641 timeControl = (min * 60 + sec) * 1000;
647 timeIncrement = ti * 1000; /* convert to ms */
651 movesPerSession = mps;
659 if (appData.debugMode) {
660 fprintf(debugFP, "%s\n", programVersion);
663 if (appData.matchGames > 0) {
664 appData.matchMode = TRUE;
665 } else if (appData.matchMode) {
666 appData.matchGames = 1;
669 if (appData.noChessProgram || first.protocolVersion == 1) {
672 /* kludge: allow timeout for initial "feature" commands */
674 DisplayMessage("", "Starting chess program");
675 ScheduleDelayedEvent(InitBackEnd3, FEATURE_TIMEOUT);
680 InitBackEnd3 P((void))
682 GameMode initialMode;
686 InitChessProgram(&first);
688 if (appData.icsActive) {
691 if (*appData.icsCommPort != NULLCHAR) {
692 sprintf(buf, "Could not open comm port %s",
693 appData.icsCommPort);
695 sprintf(buf, "Could not connect to host %s, port %s",
696 appData.icsHost, appData.icsPort);
698 DisplayFatalError(buf, err, 1);
703 AddInputSource(icsPR, FALSE, read_from_ics, &telnetISR);
705 AddInputSource(NoProc, FALSE, read_from_player, &fromUserISR);
706 } else if (appData.noChessProgram) {
712 if (*appData.cmailGameName != NULLCHAR) {
714 OpenLoopback(&cmailPR);
716 AddInputSource(cmailPR, FALSE, CmailSigHandlerCallBack, &cmailISR);
720 DisplayMessage("", "");
721 if (StrCaseCmp(appData.initialMode, "") == 0) {
722 initialMode = BeginningOfGame;
723 } else if (StrCaseCmp(appData.initialMode, "TwoMachines") == 0) {
724 initialMode = TwoMachinesPlay;
725 } else if (StrCaseCmp(appData.initialMode, "AnalyzeFile") == 0) {
726 initialMode = AnalyzeFile;
727 } else if (StrCaseCmp(appData.initialMode, "Analysis") == 0) {
728 initialMode = AnalyzeMode;
729 } else if (StrCaseCmp(appData.initialMode, "MachineWhite") == 0) {
730 initialMode = MachinePlaysWhite;
731 } else if (StrCaseCmp(appData.initialMode, "MachineBlack") == 0) {
732 initialMode = MachinePlaysBlack;
733 } else if (StrCaseCmp(appData.initialMode, "EditGame") == 0) {
734 initialMode = EditGame;
735 } else if (StrCaseCmp(appData.initialMode, "EditPosition") == 0) {
736 initialMode = EditPosition;
737 } else if (StrCaseCmp(appData.initialMode, "Training") == 0) {
738 initialMode = Training;
740 sprintf(buf, "Unknown initialMode %s", appData.initialMode);
741 DisplayFatalError(buf, 0, 2);
745 if (appData.matchMode) {
746 /* Set up machine vs. machine match */
747 if (appData.noChessProgram) {
748 DisplayFatalError("Can't have a match with no chess programs",
754 if (*appData.loadGameFile != NULLCHAR) {
755 if (!LoadGameFromFile(appData.loadGameFile,
756 appData.loadGameIndex,
757 appData.loadGameFile, FALSE)) {
758 DisplayFatalError("Bad game file", 0, 1);
761 } else if (*appData.loadPositionFile != NULLCHAR) {
762 if (!LoadPositionFromFile(appData.loadPositionFile,
763 appData.loadPositionIndex,
764 appData.loadPositionFile)) {
765 DisplayFatalError("Bad position file", 0, 1);
770 } else if (*appData.cmailGameName != NULLCHAR) {
771 /* Set up cmail mode */
772 ReloadCmailMsgEvent(TRUE);
774 /* Set up other modes */
775 if (initialMode == AnalyzeFile) {
776 if (*appData.loadGameFile == NULLCHAR) {
777 DisplayFatalError("AnalyzeFile mode requires a game file", 0, 1);
781 if (*appData.loadGameFile != NULLCHAR) {
782 (void) LoadGameFromFile(appData.loadGameFile,
783 appData.loadGameIndex,
784 appData.loadGameFile, TRUE);
785 } else if (*appData.loadPositionFile != NULLCHAR) {
786 (void) LoadPositionFromFile(appData.loadPositionFile,
787 appData.loadPositionIndex,
788 appData.loadPositionFile);
790 if (initialMode == AnalyzeMode) {
791 if (appData.noChessProgram) {
792 DisplayFatalError("Analysis mode requires a chess engine", 0, 2);
795 if (appData.icsActive) {
796 DisplayFatalError("Analysis mode does not work with ICS mode",0,2);
800 } else if (initialMode == AnalyzeFile) {
801 ShowThinkingEvent(TRUE);
803 AnalysisPeriodicEvent(1);
804 } else if (initialMode == MachinePlaysWhite) {
805 if (appData.noChessProgram) {
806 DisplayFatalError("MachineWhite mode requires a chess engine",
810 if (appData.icsActive) {
811 DisplayFatalError("MachineWhite mode does not work with ICS mode",
816 } else if (initialMode == MachinePlaysBlack) {
817 if (appData.noChessProgram) {
818 DisplayFatalError("MachineBlack mode requires a chess engine",
822 if (appData.icsActive) {
823 DisplayFatalError("MachineBlack mode does not work with ICS mode",
828 } else if (initialMode == TwoMachinesPlay) {
829 if (appData.noChessProgram) {
830 DisplayFatalError("TwoMachines mode requires a chess engine",
834 if (appData.icsActive) {
835 DisplayFatalError("TwoMachines mode does not work with ICS mode",
840 } else if (initialMode == EditGame) {
842 } else if (initialMode == EditPosition) {
844 } else if (initialMode == Training) {
845 if (*appData.loadGameFile == NULLCHAR) {
846 DisplayFatalError("Training mode requires a game file", 0, 2);
855 * Establish will establish a contact to a remote host.port.
856 * Sets icsPR to a ProcRef for a process (or pseudo-process)
857 * used to talk to the host.
858 * Returns 0 if okay, error code if not.
865 if (*appData.icsCommPort != NULLCHAR) {
866 /* Talk to the host through a serial comm port */
867 return OpenCommPort(appData.icsCommPort, &icsPR);
869 } else if (*appData.gateway != NULLCHAR) {
870 if (*appData.remoteShell == NULLCHAR) {
871 /* Use the rcmd protocol to run telnet program on a gateway host */
872 sprintf(buf, "%s %s %s",
873 appData.telnetProgram, appData.icsHost, appData.icsPort);
874 return OpenRcmd(appData.gateway, appData.remoteUser, buf, &icsPR);
877 /* Use the rsh program to run telnet program on a gateway host */
878 if (*appData.remoteUser == NULLCHAR) {
879 sprintf(buf, "%s %s %s %s %s", appData.remoteShell,
880 appData.gateway, appData.telnetProgram,
881 appData.icsHost, appData.icsPort);
883 sprintf(buf, "%s %s -l %s %s %s %s",
884 appData.remoteShell, appData.gateway,
885 appData.remoteUser, appData.telnetProgram,
886 appData.icsHost, appData.icsPort);
888 return StartChildProcess(buf, "", &icsPR);
891 } else if (appData.useTelnet) {
892 return OpenTelnet(appData.icsHost, appData.icsPort, &icsPR);
895 /* TCP socket interface differs somewhat between
896 Unix and NT; handle details in the front end.
898 return OpenTCP(appData.icsHost, appData.icsPort, &icsPR);
903 show_bytes(fp, buf, count)
909 if (*buf < 040 || *(unsigned char *) buf > 0177) {
910 fprintf(fp, "\\%03o", *buf & 0xff);
919 /* Returns an errno value */
921 OutputMaybeTelnet(pr, message, count, outError)
927 char buf[8192], *p, *q, *buflim;
928 int left, newcount, outcount;
930 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet ||
931 *appData.gateway != NULLCHAR) {
932 if (appData.debugMode) {
933 fprintf(debugFP, ">ICS: ");
934 show_bytes(debugFP, message, count);
935 fprintf(debugFP, "\n");
937 return OutputToProcess(pr, message, count, outError);
940 buflim = &buf[sizeof(buf)-1]; /* allow 1 byte for expanding last char */
947 if (appData.debugMode) {
948 fprintf(debugFP, ">ICS: ");
949 show_bytes(debugFP, buf, newcount);
950 fprintf(debugFP, "\n");
952 outcount = OutputToProcess(pr, buf, newcount, outError);
953 if (outcount < newcount) return -1; /* to be sure */
960 } else if (((unsigned char) *p) == TN_IAC) {
961 *q++ = (char) TN_IAC;
968 if (appData.debugMode) {
969 fprintf(debugFP, ">ICS: ");
970 show_bytes(debugFP, buf, newcount);
971 fprintf(debugFP, "\n");
973 outcount = OutputToProcess(pr, buf, newcount, outError);
974 if (outcount < newcount) return -1; /* to be sure */
979 read_from_player(isr, closure, message, count, error)
986 int outError, outCount;
987 static int gotEof = 0;
989 /* Pass data read from player on to ICS */
992 outCount = OutputMaybeTelnet(icsPR, message, count, &outError);
993 if (outCount < count) {
994 DisplayFatalError("Error writing to ICS", outError, 1);
996 } else if (count < 0) {
997 RemoveInputSource(isr);
998 DisplayFatalError("Error reading from keyboard", error, 1);
999 } else if (gotEof++ > 0) {
1000 RemoveInputSource(isr);
1001 DisplayFatalError("Got end of file from keyboard", 0, 0);
1009 int count, outCount, outError;
1011 if (icsPR == NULL) return;
1014 outCount = OutputMaybeTelnet(icsPR, s, count, &outError);
1015 if (outCount < count) {
1016 DisplayFatalError("Error writing to ICS", outError, 1);
1020 /* This is used for sending logon scripts to the ICS. Sending
1021 without a delay causes problems when using timestamp on ICC
1022 (at least on my machine). */
1024 SendToICSDelayed(s,msdelay)
1028 int count, outCount, outError;
1030 if (icsPR == NULL) return;
1033 if (appData.debugMode) {
1034 fprintf(debugFP, ">ICS: ");
1035 show_bytes(debugFP, s, count);
1036 fprintf(debugFP, "\n");
1038 outCount = OutputToProcessDelayed(icsPR, s, count, &outError,
1040 if (outCount < count) {
1041 DisplayFatalError("Error writing to ICS", outError, 1);
1046 /* Remove all highlighting escape sequences in s
1047 Also deletes any suffix starting with '('
1050 StripHighlightAndTitle(s)
1053 static char retbuf[MSG_SIZ];
1056 while (*s != NULLCHAR) {
1057 while (*s == '\033') {
1058 while (*s != NULLCHAR && !isalpha(*s)) s++;
1059 if (*s != NULLCHAR) s++;
1061 while (*s != NULLCHAR && *s != '\033') {
1062 if (*s == '(' || *s == '[') {
1073 /* Remove all highlighting escape sequences in s */
1078 static char retbuf[MSG_SIZ];
1081 while (*s != NULLCHAR) {
1082 while (*s == '\033') {
1083 while (*s != NULLCHAR && !isalpha(*s)) s++;
1084 if (*s != NULLCHAR) s++;
1086 while (*s != NULLCHAR && *s != '\033') {
1094 char *variantNames[] = VARIANT_NAMES;
1099 return variantNames[v];
1103 /* Identify a variant from the strings the chess servers use or the
1104 PGN Variant tag names we use. */
1111 VariantClass v = VariantNormal;
1112 int i, found = FALSE;
1117 for (i=0; i<sizeof(variantNames)/sizeof(char*); i++) {
1118 if (StrCaseStr(e, variantNames[i])) {
1119 v = (VariantClass) i;
1126 if ((StrCaseStr(e, "fischer") && StrCaseStr(e, "random"))
1127 || StrCaseStr(e, "wild/fr")) {
1128 v = VariantFischeRandom;
1129 } else if ((i = 4, p = StrCaseStr(e, "wild")) ||
1130 (i = 1, p = StrCaseStr(e, "w"))) {
1132 while (*p && (isspace(*p) || *p == '(' || *p == '/')) p++;
1139 case 0: /* FICS only, actually */
1141 /* Castling legal even if K starts on d-file */
1142 v = VariantWildCastle;
1147 /* Castling illegal even if K & R happen to start in
1148 normal positions. */
1149 v = VariantNoCastle;
1162 /* Castling legal iff K & R start in normal positions */
1168 /* Special wilds for position setup; unclear what to do here */
1169 v = VariantLoadable;
1172 /* Bizarre ICC game */
1173 v = VariantTwoKings;
1176 v = VariantKriegspiel;
1182 v = VariantFischeRandom;
1185 v = VariantCrazyhouse;
1188 v = VariantBughouse;
1194 /* Not quite the same as FICS suicide! */
1195 v = VariantGiveaway;
1201 v = VariantShatranj;
1204 /* Temporary names for future ICC types. The name *will* change in
1205 the next xboard/WinBoard release after ICC defines it. */
1232 /* Found "wild" or "w" in the string but no number;
1233 must assume it's normal chess. */
1237 sprintf(buf, "Unknown wild type %d", wnum);
1238 DisplayError(buf, 0);
1244 if (appData.debugMode) {
1245 fprintf(debugFP, "recognized '%s' (%d) as variant %s\n",
1246 e, wnum, VariantName(v));
1251 static int leftover_start = 0, leftover_len = 0;
1252 char star_match[STAR_MATCH_N][MSG_SIZ];
1254 /* Test whether pattern is present at &buf[*index]; if so, return TRUE,
1255 advance *index beyond it, and set leftover_start to the new value of
1256 *index; else return FALSE. If pattern contains the character '*', it
1257 matches any sequence of characters not containing '\r', '\n', or the
1258 character following the '*' (if any), and the matched sequence(s) are
1259 copied into star_match.
1262 looking_at(buf, index, pattern)
1267 char *bufp = &buf[*index], *patternp = pattern;
1269 char *matchp = star_match[0];
1272 if (*patternp == NULLCHAR) {
1273 *index = leftover_start = bufp - buf;
1277 if (*bufp == NULLCHAR) return FALSE;
1278 if (*patternp == '*') {
1279 if (*bufp == *(patternp + 1)) {
1281 matchp = star_match[++star_count];
1285 } else if (*bufp == '\n' || *bufp == '\r') {
1287 if (*patternp == NULLCHAR)
1292 *matchp++ = *bufp++;
1296 if (*patternp != *bufp) return FALSE;
1303 SendToPlayer(data, length)
1307 int error, outCount;
1308 outCount = OutputToProcess(NoProc, data, length, &error);
1309 if (outCount < length) {
1310 DisplayFatalError("Error writing to display", error, 1);
1315 PackHolding(packed, holding)
1327 switch (runlength) {
1338 sprintf(q, "%d", runlength);
1350 /* Telnet protocol requests from the front end */
1352 TelnetRequest(ddww, option)
1353 unsigned char ddww, option;
1355 unsigned char msg[3];
1356 int outCount, outError;
1358 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet) return;
1360 if (appData.debugMode) {
1361 char buf1[8], buf2[8], *ddwwStr, *optionStr;
1377 sprintf(buf1, "%d", ddww);
1386 sprintf(buf2, "%d", option);
1389 fprintf(debugFP, ">%s %s ", ddwwStr, optionStr);
1394 outCount = OutputToProcess(icsPR, (char *)msg, 3, &outError);
1396 DisplayFatalError("Error writing to ICS", outError, 1);
1403 if (!appData.icsActive) return;
1404 TelnetRequest(TN_DO, TN_ECHO);
1410 if (!appData.icsActive) return;
1411 TelnetRequest(TN_DONT, TN_ECHO);
1414 static int loggedOn = FALSE;
1416 /*-- Game start info cache: --*/
1418 char gs_kind[MSG_SIZ];
1419 static char player1Name[128] = "";
1420 static char player2Name[128] = "";
1421 static int player1Rating = -1;
1422 static int player2Rating = -1;
1423 /*----------------------------*/
1426 read_from_ics(isr, closure, data, count, error)
1433 #define BUF_SIZE 8192
1434 #define STARTED_NONE 0
1435 #define STARTED_MOVES 1
1436 #define STARTED_BOARD 2
1437 #define STARTED_OBSERVE 3
1438 #define STARTED_HOLDINGS 4
1439 #define STARTED_CHATTER 5
1440 #define STARTED_COMMENT 6
1441 #define STARTED_MOVES_NOHIDE 7
1443 static int started = STARTED_NONE;
1444 static char parse[20000];
1445 static int parse_pos = 0;
1446 static char buf[BUF_SIZE + 1];
1447 static int firstTime = TRUE, intfSet = FALSE;
1448 static ColorClass curColor = ColorNormal;
1449 static ColorClass prevColor = ColorNormal;
1450 static int savingComment = FALSE;
1459 if (appData.debugMode) {
1461 fprintf(debugFP, "<ICS: ");
1462 show_bytes(debugFP, data, count);
1463 fprintf(debugFP, "\n");
1469 /* If last read ended with a partial line that we couldn't parse,
1470 prepend it to the new read and try again. */
1471 if (leftover_len > 0) {
1472 for (i=0; i<leftover_len; i++)
1473 buf[i] = buf[leftover_start + i];
1476 /* Copy in new characters, removing nulls and \r's */
1477 buf_len = leftover_len;
1478 for (i = 0; i < count; i++) {
1479 if (data[i] != NULLCHAR && data[i] != '\r')
1480 buf[buf_len++] = data[i];
1483 buf[buf_len] = NULLCHAR;
1484 next_out = leftover_len;
1488 while (i < buf_len) {
1489 /* Deal with part of the TELNET option negotiation
1490 protocol. We refuse to do anything beyond the
1491 defaults, except that we allow the WILL ECHO option,
1492 which ICS uses to turn off password echoing when we are
1493 directly connected to it. We reject this option
1494 if localLineEditing mode is on (always on in xboard)
1495 and we are talking to port 23, which might be a real
1496 telnet server that will try to keep WILL ECHO on permanently.
1498 if (buf_len - i >= 3 && (unsigned char) buf[i] == TN_IAC) {
1499 static int remoteEchoOption = FALSE; /* telnet ECHO option */
1500 unsigned char option;
1502 switch ((unsigned char) buf[++i]) {
1504 if (appData.debugMode)
1505 fprintf(debugFP, "\n<WILL ");
1506 switch (option = (unsigned char) buf[++i]) {
1508 if (appData.debugMode)
1509 fprintf(debugFP, "ECHO ");
1510 /* Reply only if this is a change, according
1511 to the protocol rules. */
1512 if (remoteEchoOption) break;
1513 if (appData.localLineEditing &&
1514 atoi(appData.icsPort) == TN_PORT) {
1515 TelnetRequest(TN_DONT, TN_ECHO);
1518 TelnetRequest(TN_DO, TN_ECHO);
1519 remoteEchoOption = TRUE;
1523 if (appData.debugMode)
1524 fprintf(debugFP, "%d ", option);
1525 /* Whatever this is, we don't want it. */
1526 TelnetRequest(TN_DONT, option);
1531 if (appData.debugMode)
1532 fprintf(debugFP, "\n<WONT ");
1533 switch (option = (unsigned char) buf[++i]) {
1535 if (appData.debugMode)
1536 fprintf(debugFP, "ECHO ");
1537 /* Reply only if this is a change, according
1538 to the protocol rules. */
1539 if (!remoteEchoOption) break;
1541 TelnetRequest(TN_DONT, TN_ECHO);
1542 remoteEchoOption = FALSE;
1545 if (appData.debugMode)
1546 fprintf(debugFP, "%d ", (unsigned char) option);
1547 /* Whatever this is, it must already be turned
1548 off, because we never agree to turn on
1549 anything non-default, so according to the
1550 protocol rules, we don't reply. */
1555 if (appData.debugMode)
1556 fprintf(debugFP, "\n<DO ");
1557 switch (option = (unsigned char) buf[++i]) {
1559 /* Whatever this is, we refuse to do it. */
1560 if (appData.debugMode)
1561 fprintf(debugFP, "%d ", option);
1562 TelnetRequest(TN_WONT, option);
1567 if (appData.debugMode)
1568 fprintf(debugFP, "\n<DONT ");
1569 switch (option = (unsigned char) buf[++i]) {
1571 if (appData.debugMode)
1572 fprintf(debugFP, "%d ", option);
1573 /* Whatever this is, we are already not doing
1574 it, because we never agree to do anything
1575 non-default, so according to the protocol
1576 rules, we don't reply. */
1581 if (appData.debugMode)
1582 fprintf(debugFP, "\n<IAC ");
1583 /* Doubled IAC; pass it through */
1587 if (appData.debugMode)
1588 fprintf(debugFP, "\n<%d ", (unsigned char) buf[i]);
1589 /* Drop all other telnet commands on the floor */
1592 if (oldi > next_out)
1593 SendToPlayer(&buf[next_out], oldi - next_out);
1599 /* OK, this at least will *usually* work */
1600 if (!loggedOn && looking_at(buf, &i, "ics%")) {
1604 if (loggedOn && !intfSet) {
1605 if (ics_type == ICS_ICC) {
1607 "/set-quietly interface %s\n/set-quietly style 12\n",
1610 } else if (ics_type == ICS_CHESSNET) {
1611 sprintf(str, "/style 12\n");
1613 strcpy(str, "alias $ @\n$set interface ");
1614 strcat(str, programVersion);
1615 strcat(str, "\n$iset startpos 1\n$iset ms 1\n");
1617 strcat(str, "$iset nohighlight 1\n");
1619 strcat(str, "$iset lock 1\n$style 12\n");
1625 if (started == STARTED_COMMENT) {
1626 /* Accumulate characters in comment */
1627 parse[parse_pos++] = buf[i];
1628 if (buf[i] == '\n') {
1629 parse[parse_pos] = NULLCHAR;
1630 AppendComment(forwardMostMove, StripHighlight(parse));
1631 started = STARTED_NONE;
1633 /* Don't match patterns against characters in chatter */
1638 if (started == STARTED_CHATTER) {
1639 if (buf[i] != '\n') {
1640 /* Don't match patterns against characters in chatter */
1644 started = STARTED_NONE;
1647 /* Kludge to deal with rcmd protocol */
1648 if (firstTime && looking_at(buf, &i, "\001*")) {
1649 DisplayFatalError(&buf[1], 0, 1);
1655 if (!loggedOn && looking_at(buf, &i, "chessclub.com")) {
1658 if (appData.debugMode)
1659 fprintf(debugFP, "ics_type %d\n", ics_type);
1662 if (!loggedOn && looking_at(buf, &i, "freechess.org")) {
1663 ics_type = ICS_FICS;
1665 if (appData.debugMode)
1666 fprintf(debugFP, "ics_type %d\n", ics_type);
1669 if (!loggedOn && looking_at(buf, &i, "chess.net")) {
1670 ics_type = ICS_CHESSNET;
1672 if (appData.debugMode)
1673 fprintf(debugFP, "ics_type %d\n", ics_type);
1678 (looking_at(buf, &i, "\"*\" is *a registered name") ||
1679 looking_at(buf, &i, "Logging you in as \"*\"") ||
1680 looking_at(buf, &i, "will be \"*\""))) {
1681 strcpy(ics_handle, star_match[0]);
1685 if (loggedOn && !have_set_title && ics_handle[0] != NULLCHAR) {
1687 sprintf(buf, "%s@%s", ics_handle, appData.icsHost);
1688 DisplayIcsInteractionTitle(buf);
1689 have_set_title = TRUE;
1692 /* skip finger notes */
1693 if (started == STARTED_NONE &&
1694 ((buf[i] == ' ' && isdigit(buf[i+1])) ||
1695 (buf[i] == '1' && buf[i+1] == '0')) &&
1696 buf[i+2] == ':' && buf[i+3] == ' ') {
1697 started = STARTED_CHATTER;
1702 /* skip formula vars */
1703 if (started == STARTED_NONE &&
1704 buf[i] == 'f' && isdigit(buf[i+1]) && buf[i+2] == ':') {
1705 started = STARTED_CHATTER;
1711 if (appData.zippyTalk || appData.zippyPlay) {
1713 if (ZippyControl(buf, &i) ||
1714 ZippyConverse(buf, &i) ||
1715 (appData.zippyPlay && ZippyMatch(buf, &i))) {
1721 if (/* Don't color "message" or "messages" output */
1722 (tkind = 5, looking_at(buf, &i, "*. * (*:*): ")) ||
1723 looking_at(buf, &i, "*. * at *:*: ") ||
1724 looking_at(buf, &i, "--* (*:*): ") ||
1725 /* Regular tells and says */
1726 (tkind = 1, looking_at(buf, &i, "* tells you: ")) ||
1727 looking_at(buf, &i, "* (your partner) tells you: ") ||
1728 looking_at(buf, &i, "* says: ") ||
1729 /* Message notifications (same color as tells) */
1730 looking_at(buf, &i, "* has left a message ") ||
1731 looking_at(buf, &i, "* just sent you a message:\n") ||
1732 /* Whispers and kibitzes */
1733 (tkind = 2, looking_at(buf, &i, "* whispers: ")) ||
1734 looking_at(buf, &i, "* kibitzes: ") ||
1736 (tkind = 3, looking_at(buf, &i, "*(*: "))) {
1738 if (tkind == 1 && strchr(star_match[0], ':')) {
1739 /* Avoid "tells you:" spoofs in channels */
1742 if (star_match[0][0] == NULLCHAR ||
1743 strchr(star_match[0], ' ') ||
1744 (tkind == 3 && strchr(star_match[1], ' '))) {
1745 /* Reject bogus matches */
1748 if (appData.colorize) {
1749 if (oldi > next_out) {
1750 SendToPlayer(&buf[next_out], oldi - next_out);
1755 Colorize(ColorTell, FALSE);
1756 curColor = ColorTell;
1759 Colorize(ColorKibitz, FALSE);
1760 curColor = ColorKibitz;
1763 p = strrchr(star_match[1], '(');
1770 Colorize(ColorChannel1, FALSE);
1771 curColor = ColorChannel1;
1773 Colorize(ColorChannel, FALSE);
1774 curColor = ColorChannel;
1778 curColor = ColorNormal;
1782 if (started == STARTED_NONE && appData.autoComment &&
1783 (gameMode == IcsObserving ||
1784 gameMode == IcsPlayingWhite ||
1785 gameMode == IcsPlayingBlack)) {
1786 parse_pos = i - oldi;
1787 memcpy(parse, &buf[oldi], parse_pos);
1788 parse[parse_pos] = NULLCHAR;
1789 started = STARTED_COMMENT;
1790 savingComment = TRUE;
1792 started = STARTED_CHATTER;
1793 savingComment = FALSE;
1800 if (looking_at(buf, &i, "* s-shouts: ") ||
1801 looking_at(buf, &i, "* c-shouts: ")) {
1802 if (appData.colorize) {
1803 if (oldi > next_out) {
1804 SendToPlayer(&buf[next_out], oldi - next_out);
1807 Colorize(ColorSShout, FALSE);
1808 curColor = ColorSShout;
1811 started = STARTED_CHATTER;
1815 if (looking_at(buf, &i, "--->")) {
1820 if (looking_at(buf, &i, "* shouts: ") ||
1821 looking_at(buf, &i, "--> ")) {
1822 if (appData.colorize) {
1823 if (oldi > next_out) {
1824 SendToPlayer(&buf[next_out], oldi - next_out);
1827 Colorize(ColorShout, FALSE);
1828 curColor = ColorShout;
1831 started = STARTED_CHATTER;
1835 if (looking_at( buf, &i, "Challenge:")) {
1836 if (appData.colorize) {
1837 if (oldi > next_out) {
1838 SendToPlayer(&buf[next_out], oldi - next_out);
1841 Colorize(ColorChallenge, FALSE);
1842 curColor = ColorChallenge;
1848 if (looking_at(buf, &i, "* offers you") ||
1849 looking_at(buf, &i, "* offers to be") ||
1850 looking_at(buf, &i, "* would like to") ||
1851 looking_at(buf, &i, "* requests to") ||
1852 looking_at(buf, &i, "Your opponent offers") ||
1853 looking_at(buf, &i, "Your opponent requests")) {
1855 if (appData.colorize) {
1856 if (oldi > next_out) {
1857 SendToPlayer(&buf[next_out], oldi - next_out);
1860 Colorize(ColorRequest, FALSE);
1861 curColor = ColorRequest;
1866 if (looking_at(buf, &i, "* (*) seeking")) {
1867 if (appData.colorize) {
1868 if (oldi > next_out) {
1869 SendToPlayer(&buf[next_out], oldi - next_out);
1872 Colorize(ColorSeek, FALSE);
1873 curColor = ColorSeek;
1879 if (looking_at(buf, &i, "\\ ")) {
1880 if (prevColor != ColorNormal) {
1881 if (oldi > next_out) {
1882 SendToPlayer(&buf[next_out], oldi - next_out);
1885 Colorize(prevColor, TRUE);
1886 curColor = prevColor;
1888 if (savingComment) {
1889 parse_pos = i - oldi;
1890 memcpy(parse, &buf[oldi], parse_pos);
1891 parse[parse_pos] = NULLCHAR;
1892 started = STARTED_COMMENT;
1894 started = STARTED_CHATTER;
1899 if (looking_at(buf, &i, "Black Strength :") ||
1900 looking_at(buf, &i, "<<< style 10 board >>>") ||
1901 looking_at(buf, &i, "<10>") ||
1902 looking_at(buf, &i, "#@#")) {
1903 /* Wrong board style */
1905 SendToICS(ics_prefix);
1906 SendToICS("set style 12\n");
1907 SendToICS(ics_prefix);
1908 SendToICS("refresh\n");
1912 if (!have_sent_ICS_logon && looking_at(buf, &i, "login:")) {
1914 have_sent_ICS_logon = 1;
1918 if (ics_getting_history != H_GETTING_MOVES /*smpos kludge*/ &&
1919 (looking_at(buf, &i, "\n<12> ") ||
1920 looking_at(buf, &i, "<12> "))) {
1922 if (oldi > next_out) {
1923 SendToPlayer(&buf[next_out], oldi - next_out);
1926 started = STARTED_BOARD;
1931 if ((started == STARTED_NONE && looking_at(buf, &i, "\n<b1> ")) ||
1932 looking_at(buf, &i, "<b1> ")) {
1933 if (oldi > next_out) {
1934 SendToPlayer(&buf[next_out], oldi - next_out);
1937 started = STARTED_HOLDINGS;
1942 if (looking_at(buf, &i, "* *vs. * *--- *")) {
1944 /* Header for a move list -- first line */
1946 switch (ics_getting_history) {
1950 case BeginningOfGame:
1951 /* User typed "moves" or "oldmoves" while we
1952 were idle. Pretend we asked for these
1953 moves and soak them up so user can step
1954 through them and/or save them.
1957 gameMode = IcsObserving;
1960 ics_getting_history = H_GOT_UNREQ_HEADER;
1962 case EditGame: /*?*/
1963 case EditPosition: /*?*/
1964 /* Should above feature work in these modes too? */
1965 /* For now it doesn't */
1966 ics_getting_history = H_GOT_UNWANTED_HEADER;
1969 ics_getting_history = H_GOT_UNWANTED_HEADER;
1974 /* Is this the right one? */
1975 if (gameInfo.white && gameInfo.black &&
1976 strcmp(gameInfo.white, star_match[0]) == 0 &&
1977 strcmp(gameInfo.black, star_match[2]) == 0) {
1979 ics_getting_history = H_GOT_REQ_HEADER;
1982 case H_GOT_REQ_HEADER:
1983 case H_GOT_UNREQ_HEADER:
1984 case H_GOT_UNWANTED_HEADER:
1985 case H_GETTING_MOVES:
1986 /* Should not happen */
1987 DisplayError("Error gathering move list: two headers", 0);
1988 ics_getting_history = H_FALSE;
1992 /* Save player ratings into gameInfo if needed */
1993 if ((ics_getting_history == H_GOT_REQ_HEADER ||
1994 ics_getting_history == H_GOT_UNREQ_HEADER) &&
1995 (gameInfo.whiteRating == -1 ||
1996 gameInfo.blackRating == -1)) {
1998 gameInfo.whiteRating = string_to_rating(star_match[1]);
1999 gameInfo.blackRating = string_to_rating(star_match[3]);
2000 if (appData.debugMode)
2001 fprintf(debugFP, "Ratings from header: W %d, B %d\n",
2002 gameInfo.whiteRating, gameInfo.blackRating);
2007 if (looking_at(buf, &i,
2008 "* * match, initial time: * minute*, increment: * second")) {
2009 /* Header for a move list -- second line */
2010 /* Initial board will follow if this is a wild game */
2012 if (gameInfo.event != NULL) free(gameInfo.event);
2013 sprintf(str, "ICS %s %s match", star_match[0], star_match[1]);
2014 gameInfo.event = StrSave(str);
2015 gameInfo.variant = StringToVariant(gameInfo.event);
2019 if (looking_at(buf, &i, "Move ")) {
2020 /* Beginning of a move list */
2021 switch (ics_getting_history) {
2023 /* Normally should not happen */
2024 /* Maybe user hit reset while we were parsing */
2027 /* Happens if we are ignoring a move list that is not
2028 * the one we just requested. Common if the user
2029 * tries to observe two games without turning off
2032 case H_GETTING_MOVES:
2033 /* Should not happen */
2034 DisplayError("Error gathering move list: nested", 0);
2035 ics_getting_history = H_FALSE;
2037 case H_GOT_REQ_HEADER:
2038 ics_getting_history = H_GETTING_MOVES;
2039 started = STARTED_MOVES;
2041 if (oldi > next_out) {
2042 SendToPlayer(&buf[next_out], oldi - next_out);
2045 case H_GOT_UNREQ_HEADER:
2046 ics_getting_history = H_GETTING_MOVES;
2047 started = STARTED_MOVES_NOHIDE;
2050 case H_GOT_UNWANTED_HEADER:
2051 ics_getting_history = H_FALSE;
2057 if (looking_at(buf, &i, "% ") ||
2058 ((started == STARTED_MOVES || started == STARTED_MOVES_NOHIDE)
2059 && looking_at(buf, &i, "}*"))) {
2060 savingComment = FALSE;
2063 case STARTED_MOVES_NOHIDE:
2064 memcpy(&parse[parse_pos], &buf[oldi], i - oldi);
2065 parse[parse_pos + i - oldi] = NULLCHAR;
2066 ParseGameHistory(parse);
2068 if (appData.zippyPlay && first.initDone) {
2069 FeedMovesToProgram(&first, forwardMostMove);
2070 if (gameMode == IcsPlayingWhite) {
2071 if (WhiteOnMove(forwardMostMove)) {
2072 if (first.sendTime) {
2073 if (first.useColors) {
2074 SendToProgram("black\n", &first);
2076 SendTimeRemaining(&first, TRUE);
2078 if (first.useColors) {
2079 SendToProgram("white\ngo\n", &first);
2081 SendToProgram("go\n", &first);
2083 first.maybeThinking = TRUE;
2085 if (first.usePlayother) {
2086 if (first.sendTime) {
2087 SendTimeRemaining(&first, TRUE);
2089 SendToProgram("playother\n", &first);
2095 } else if (gameMode == IcsPlayingBlack) {
2096 if (!WhiteOnMove(forwardMostMove)) {
2097 if (first.sendTime) {
2098 if (first.useColors) {
2099 SendToProgram("white\n", &first);
2101 SendTimeRemaining(&first, FALSE);
2103 if (first.useColors) {
2104 SendToProgram("black\ngo\n", &first);
2106 SendToProgram("go\n", &first);
2108 first.maybeThinking = TRUE;
2110 if (first.usePlayother) {
2111 if (first.sendTime) {
2112 SendTimeRemaining(&first, FALSE);
2114 SendToProgram("playother\n", &first);
2123 if (gameMode == IcsObserving && ics_gamenum == -1) {
2124 /* Moves came from oldmoves or moves command
2125 while we weren't doing anything else.
2127 currentMove = forwardMostMove;
2128 ClearHighlights();/*!!could figure this out*/
2129 flipView = appData.flipView;
2130 DrawPosition(FALSE, boards[currentMove]);
2131 DisplayBothClocks();
2132 sprintf(str, "%s vs. %s",
2133 gameInfo.white, gameInfo.black);
2137 /* Moves were history of an active game */
2138 if (gameInfo.resultDetails != NULL) {
2139 free(gameInfo.resultDetails);
2140 gameInfo.resultDetails = NULL;
2143 HistorySet(parseList, backwardMostMove,
2144 forwardMostMove, currentMove-1);
2145 DisplayMove(currentMove - 1);
2146 if (started == STARTED_MOVES) next_out = i;
2147 started = STARTED_NONE;
2148 ics_getting_history = H_FALSE;
2151 case STARTED_OBSERVE:
2152 started = STARTED_NONE;
2153 SendToICS(ics_prefix);
2154 SendToICS("refresh\n");
2163 if ((started == STARTED_MOVES || started == STARTED_BOARD ||
2164 started == STARTED_HOLDINGS ||
2165 started == STARTED_MOVES_NOHIDE) && i >= leftover_len) {
2166 /* Accumulate characters in move list or board */
2167 parse[parse_pos++] = buf[i];
2170 /* Start of game messages. Mostly we detect start of game
2171 when the first board image arrives. On some versions
2172 of the ICS, though, we need to do a "refresh" after starting
2173 to observe in order to get the current board right away. */
2174 if (looking_at(buf, &i, "Adding game * to observation list")) {
2175 started = STARTED_OBSERVE;
2179 /* Handle auto-observe */
2180 if (appData.autoObserve &&
2181 (gameMode == IcsIdle || gameMode == BeginningOfGame) &&
2182 looking_at(buf, &i, "Game notification: * (*) vs. * (*)")) {
2184 /* Choose the player that was highlighted, if any. */
2185 if (star_match[0][0] == '\033' ||
2186 star_match[1][0] != '\033') {
2187 player = star_match[0];
2189 player = star_match[2];
2191 sprintf(str, "%sobserve %s\n",
2192 ics_prefix, StripHighlightAndTitle(player));
2195 /* Save ratings from notify string */
2196 strcpy(player1Name, star_match[0]);
2197 player1Rating = string_to_rating(star_match[1]);
2198 strcpy(player2Name, star_match[2]);
2199 player2Rating = string_to_rating(star_match[3]);
2201 if (appData.debugMode)
2203 "Ratings from 'Game notification:' %s %d, %s %d\n",
2204 player1Name, player1Rating,
2205 player2Name, player2Rating);
2210 /* Deal with automatic examine mode after a game,
2211 and with IcsObserving -> IcsExamining transition */
2212 if (looking_at(buf, &i, "Entering examine mode for game *") ||
2213 looking_at(buf, &i, "has made you an examiner of game *")) {
2215 int gamenum = atoi(star_match[0]);
2216 if ((gameMode == IcsIdle || gameMode == IcsObserving) &&
2217 gamenum == ics_gamenum) {
2218 /* We were already playing or observing this game;
2219 no need to refetch history */
2220 gameMode = IcsExamining;
2222 pauseExamForwardMostMove = forwardMostMove;
2223 } else if (currentMove < forwardMostMove) {
2224 ForwardInner(forwardMostMove);
2227 /* I don't think this case really can happen */
2228 SendToICS(ics_prefix);
2229 SendToICS("refresh\n");
2234 /* Error messages */
2235 if (ics_user_moved) {
2236 if (looking_at(buf, &i, "Illegal move") ||
2237 looking_at(buf, &i, "Not a legal move") ||
2238 looking_at(buf, &i, "Your king is in check") ||
2239 looking_at(buf, &i, "It isn't your turn") ||
2240 looking_at(buf, &i, "It is not your move")) {
2243 if (forwardMostMove > backwardMostMove) {
2244 currentMove = --forwardMostMove;
2245 DisplayMove(currentMove - 1); /* before DMError */
2246 DisplayMoveError("Illegal move (rejected by ICS)");
2247 DrawPosition(FALSE, boards[currentMove]);
2249 DisplayBothClocks();
2255 if (looking_at(buf, &i, "still have time") ||
2256 looking_at(buf, &i, "not out of time") ||
2257 looking_at(buf, &i, "either player is out of time") ||
2258 looking_at(buf, &i, "has timeseal; checking")) {
2259 /* We must have called his flag a little too soon */
2260 whiteFlag = blackFlag = FALSE;
2264 if (looking_at(buf, &i, "added * seconds to") ||
2265 looking_at(buf, &i, "seconds were added to")) {
2266 /* Update the clocks */
2267 SendToICS(ics_prefix);
2268 SendToICS("refresh\n");
2272 if (!ics_clock_paused && looking_at(buf, &i, "clock paused")) {
2273 ics_clock_paused = TRUE;
2278 if (ics_clock_paused && looking_at(buf, &i, "clock resumed")) {
2279 ics_clock_paused = FALSE;
2284 /* Grab player ratings from the Creating: message.
2285 Note we have to check for the special case when
2286 the ICS inserts things like [white] or [black]. */
2287 if (looking_at(buf, &i, "Creating: * (*)* * (*)") ||
2288 looking_at(buf, &i, "Creating: * (*) [*] * (*)")) {
2290 0 player 1 name (not necessarily white)
2292 2 empty, white, or black (IGNORED)
2293 3 player 2 name (not necessarily black)
2296 The names/ratings are sorted out when the game
2297 actually starts (below).
2299 strcpy(player1Name, StripHighlightAndTitle(star_match[0]));
2300 player1Rating = string_to_rating(star_match[1]);
2301 strcpy(player2Name, StripHighlightAndTitle(star_match[3]));
2302 player2Rating = string_to_rating(star_match[4]);
2304 if (appData.debugMode)
2306 "Ratings from 'Creating:' %s %d, %s %d\n",
2307 player1Name, player1Rating,
2308 player2Name, player2Rating);
2313 /* Improved generic start/end-of-game messages */
2314 if ((tkind=0, looking_at(buf, &i, "{Game * (* vs. *) *}*")) ||
2315 (tkind=1, looking_at(buf, &i, "{Game * (*(*) vs. *(*)) *}*"))){
2316 /* If tkind == 0: */
2317 /* star_match[0] is the game number */
2318 /* [1] is the white player's name */
2319 /* [2] is the black player's name */
2320 /* For end-of-game: */
2321 /* [3] is the reason for the game end */
2322 /* [4] is a PGN end game-token, preceded by " " */
2323 /* For start-of-game: */
2324 /* [3] begins with "Creating" or "Continuing" */
2325 /* [4] is " *" or empty (don't care). */
2326 int gamenum = atoi(star_match[0]);
2327 char *whitename, *blackname, *why, *endtoken;
2328 ChessMove endtype = (ChessMove) 0;
2331 whitename = star_match[1];
2332 blackname = star_match[2];
2333 why = star_match[3];
2334 endtoken = star_match[4];
2336 whitename = star_match[1];
2337 blackname = star_match[3];
2338 why = star_match[5];
2339 endtoken = star_match[6];
2342 /* Game start messages */
2343 if (strncmp(why, "Creating ", 9) == 0 ||
2344 strncmp(why, "Continuing ", 11) == 0) {
2345 gs_gamenum = gamenum;
2346 strcpy(gs_kind, strchr(why, ' ') + 1);
2348 if (appData.zippyPlay) {
2349 ZippyGameStart(whitename, blackname);
2355 /* Game end messages */
2356 if (gameMode == IcsIdle || gameMode == BeginningOfGame ||
2357 ics_gamenum != gamenum) {
2360 while (endtoken[0] == ' ') endtoken++;
2361 switch (endtoken[0]) {
2364 endtype = GameUnfinished;
2367 endtype = BlackWins;
2370 if (endtoken[1] == '/')
2371 endtype = GameIsDrawn;
2373 endtype = WhiteWins;
2376 GameEnds(endtype, why, GE_ICS);
2378 if (appData.zippyPlay && first.initDone) {
2379 ZippyGameEnd(endtype, why);
2380 if (first.pr == NULL) {
2381 /* Start the next process early so that we'll
2382 be ready for the next challenge */
2383 StartChessProgram(&first);
2385 /* Send "new" early, in case this command takes
2386 a long time to finish, so that we'll be ready
2387 for the next challenge. */
2394 if (looking_at(buf, &i, "Removing game * from observation") ||
2395 looking_at(buf, &i, "no longer observing game *") ||
2396 looking_at(buf, &i, "Game * (*) has no examiners")) {
2397 if (gameMode == IcsObserving &&
2398 atoi(star_match[0]) == ics_gamenum)
2403 ics_user_moved = FALSE;
2408 if (looking_at(buf, &i, "no longer examining game *")) {
2409 if (gameMode == IcsExamining &&
2410 atoi(star_match[0]) == ics_gamenum)
2414 ics_user_moved = FALSE;
2419 /* Advance leftover_start past any newlines we find,
2420 so only partial lines can get reparsed */
2421 if (looking_at(buf, &i, "\n")) {
2422 prevColor = curColor;
2423 if (curColor != ColorNormal) {
2424 if (oldi > next_out) {
2425 SendToPlayer(&buf[next_out], oldi - next_out);
2428 Colorize(ColorNormal, FALSE);
2429 curColor = ColorNormal;
2431 if (started == STARTED_BOARD) {
2432 started = STARTED_NONE;
2433 parse[parse_pos] = NULLCHAR;
2434 ParseBoard12(parse);
2437 /* Send premove here */
2438 if (appData.premove) {
2440 if (currentMove == 0 &&
2441 gameMode == IcsPlayingWhite &&
2442 appData.premoveWhite) {
2443 sprintf(str, "%s%s\n", ics_prefix,
2444 appData.premoveWhiteText);
2445 if (appData.debugMode)
2446 fprintf(debugFP, "Sending premove:\n");
2448 } else if (currentMove == 1 &&
2449 gameMode == IcsPlayingBlack &&
2450 appData.premoveBlack) {
2451 sprintf(str, "%s%s\n", ics_prefix,
2452 appData.premoveBlackText);
2453 if (appData.debugMode)
2454 fprintf(debugFP, "Sending premove:\n");
2456 } else if (gotPremove) {
2458 ClearPremoveHighlights();
2459 if (appData.debugMode)
2460 fprintf(debugFP, "Sending premove:\n");
2461 UserMoveEvent(premoveFromX, premoveFromY,
2462 premoveToX, premoveToY,
2467 /* Usually suppress following prompt */
2468 if (!(forwardMostMove == 0 && gameMode == IcsExamining)) {
2469 if (looking_at(buf, &i, "*% ")) {
2470 savingComment = FALSE;
2474 } else if (started == STARTED_HOLDINGS) {
2476 char new_piece[MSG_SIZ];
2477 started = STARTED_NONE;
2478 parse[parse_pos] = NULLCHAR;
2479 if (appData.debugMode)
2480 fprintf(debugFP, "Parsing holdings: %s\n", parse);
2481 if (sscanf(parse, " game %d", &gamenum) == 1 &&
2482 gamenum == ics_gamenum) {
2483 if (gameInfo.variant == VariantNormal) {
2484 gameInfo.variant = VariantCrazyhouse; /*temp guess*/
2485 /* Get a move list just to see the header, which
2486 will tell us whether this is really bug or zh */
2487 if (ics_getting_history == H_FALSE) {
2488 ics_getting_history = H_REQUESTED;
2489 sprintf(str, "%smoves %d\n", ics_prefix, gamenum);
2493 new_piece[0] = NULLCHAR;
2494 sscanf(parse, "game %d white [%s black [%s <- %s",
2495 &gamenum, white_holding, black_holding,
2497 white_holding[strlen(white_holding)-1] = NULLCHAR;
2498 black_holding[strlen(black_holding)-1] = NULLCHAR;
2500 if (appData.zippyPlay && first.initDone) {
2501 ZippyHoldings(white_holding, black_holding,
2505 if (tinyLayout || smallLayout) {
2506 char wh[16], bh[16];
2507 PackHolding(wh, white_holding);
2508 PackHolding(bh, black_holding);
2509 sprintf(str, "[%s-%s] %s-%s", wh, bh,
2510 gameInfo.white, gameInfo.black);
2512 sprintf(str, "%s [%s] vs. %s [%s]",
2513 gameInfo.white, white_holding,
2514 gameInfo.black, black_holding);
2516 DrawPosition(FALSE, NULL);
2519 /* Suppress following prompt */
2520 if (looking_at(buf, &i, "*% ")) {
2521 savingComment = FALSE;
2528 i++; /* skip unparsed character and loop back */
2531 if (started != STARTED_MOVES && started != STARTED_BOARD &&
2532 started != STARTED_HOLDINGS && i > next_out) {
2533 SendToPlayer(&buf[next_out], i - next_out);
2537 leftover_len = buf_len - leftover_start;
2538 /* if buffer ends with something we couldn't parse,
2539 reparse it after appending the next read */
2541 } else if (count == 0) {
2542 RemoveInputSource(isr);
2543 DisplayFatalError("Connection closed by ICS", 0, 0);
2545 DisplayFatalError("Error reading from ICS", error, 1);
2550 /* Board style 12 looks like this:
2552 <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
2554 * The "<12> " is stripped before it gets to this routine. The two
2555 * trailing 0's (flip state and clock ticking) are later addition, and
2556 * some chess servers may not have them, or may have only the first.
2557 * Additional trailing fields may be added in the future.
2560 #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"
2562 #define RELATION_OBSERVING_PLAYED 0
2563 #define RELATION_OBSERVING_STATIC -2 /* examined, oldmoves, or smoves */
2564 #define RELATION_PLAYING_MYMOVE 1
2565 #define RELATION_PLAYING_NOTMYMOVE -1
2566 #define RELATION_EXAMINING 2
2567 #define RELATION_ISOLATED_BOARD -3
2568 #define RELATION_STARTING_POSITION -4 /* FICS only */
2571 ParseBoard12(string)
2574 GameMode newGameMode;
2575 int gamenum, newGame, newMove, relation, basetime, increment, ics_flip = 0;
2576 int j, k, n, moveNum, white_stren, black_stren, white_time, black_time;
2577 int double_push, castle_ws, castle_wl, castle_bs, castle_bl, irrev_count;
2578 char to_play, board_chars[72];
2579 char move_str[500], str[500], elapsed_time[500];
2580 char black[32], white[32];
2582 int prevMove = currentMove;
2585 int fromX, fromY, toX, toY;
2588 fromX = fromY = toX = toY = -1;
2592 if (appData.debugMode)
2593 fprintf(debugFP, "Parsing board: %s\n", string);
2595 move_str[0] = NULLCHAR;
2596 elapsed_time[0] = NULLCHAR;
2597 n = sscanf(string, PATTERN, board_chars, &to_play, &double_push,
2598 &castle_ws, &castle_wl, &castle_bs, &castle_bl, &irrev_count,
2599 &gamenum, white, black, &relation, &basetime, &increment,
2600 &white_stren, &black_stren, &white_time, &black_time,
2601 &moveNum, str, elapsed_time, move_str, &ics_flip,
2605 sprintf(str, "Failed to parse board string:\n\"%s\"", string);
2606 DisplayError(str, 0);
2610 /* Convert the move number to internal form */
2611 moveNum = (moveNum - 1) * 2;
2612 if (to_play == 'B') moveNum++;
2613 if (moveNum >= MAX_MOVES) {
2614 DisplayFatalError("Game too long; increase MAX_MOVES and recompile",
2620 case RELATION_OBSERVING_PLAYED:
2621 case RELATION_OBSERVING_STATIC:
2622 if (gamenum == -1) {
2623 /* Old ICC buglet */
2624 relation = RELATION_OBSERVING_STATIC;
2626 newGameMode = IcsObserving;
2628 case RELATION_PLAYING_MYMOVE:
2629 case RELATION_PLAYING_NOTMYMOVE:
2631 ((relation == RELATION_PLAYING_MYMOVE) == (to_play == 'W')) ?
2632 IcsPlayingWhite : IcsPlayingBlack;
2634 case RELATION_EXAMINING:
2635 newGameMode = IcsExamining;
2637 case RELATION_ISOLATED_BOARD:
2639 /* Just display this board. If user was doing something else,
2640 we will forget about it until the next board comes. */
2641 newGameMode = IcsIdle;
2643 case RELATION_STARTING_POSITION:
2644 newGameMode = gameMode;
2648 /* Modify behavior for initial board display on move listing
2651 switch (ics_getting_history) {
2655 case H_GOT_REQ_HEADER:
2656 case H_GOT_UNREQ_HEADER:
2657 /* This is the initial position of the current game */
2658 gamenum = ics_gamenum;
2659 moveNum = 0; /* old ICS bug workaround */
2660 if (to_play == 'B') {
2661 startedFromSetupPosition = TRUE;
2662 blackPlaysFirst = TRUE;
2664 if (forwardMostMove == 0) forwardMostMove = 1;
2665 if (backwardMostMove == 0) backwardMostMove = 1;
2666 if (currentMove == 0) currentMove = 1;
2668 newGameMode = gameMode;
2669 relation = RELATION_STARTING_POSITION; /* ICC needs this */
2671 case H_GOT_UNWANTED_HEADER:
2672 /* This is an initial board that we don't want */
2674 case H_GETTING_MOVES:
2675 /* Should not happen */
2676 DisplayError("Error gathering move list: extra board", 0);
2677 ics_getting_history = H_FALSE;
2681 /* Take action if this is the first board of a new game, or of a
2682 different game than is currently being displayed. */
2683 if (gamenum != ics_gamenum || newGameMode != gameMode ||
2684 relation == RELATION_ISOLATED_BOARD) {
2686 /* Forget the old game and get the history (if any) of the new one */
2687 if (gameMode != BeginningOfGame) {
2691 if (appData.autoRaiseBoard) BoardToTop();
2693 if (gamenum == -1) {
2694 newGameMode = IcsIdle;
2695 } else if (moveNum > 0 && newGameMode != IcsIdle &&
2696 appData.getMoveList) {
2697 /* Need to get game history */
2698 ics_getting_history = H_REQUESTED;
2699 sprintf(str, "%smoves %d\n", ics_prefix, gamenum);
2703 /* Initially flip the board to have black on the bottom if playing
2704 black or if the ICS flip flag is set, but let the user change
2705 it with the Flip View button. */
2706 flipView = appData.autoFlipView ?
2707 (newGameMode == IcsPlayingBlack) || ics_flip :
2710 /* Done with values from previous mode; copy in new ones */
2711 gameMode = newGameMode;
2713 ics_gamenum = gamenum;
2714 if (gamenum == gs_gamenum) {
2715 int klen = strlen(gs_kind);
2716 if (gs_kind[klen - 1] == '.') gs_kind[klen - 1] = NULLCHAR;
2717 sprintf(str, "ICS %s", gs_kind);
2718 gameInfo.event = StrSave(str);
2720 gameInfo.event = StrSave("ICS game");
2722 gameInfo.site = StrSave(appData.icsHost);
2723 gameInfo.date = PGNDate();
2724 gameInfo.round = StrSave("-");
2725 gameInfo.white = StrSave(white);
2726 gameInfo.black = StrSave(black);
2727 timeControl = basetime * 60 * 1000;
2728 timeIncrement = increment * 1000;
2729 movesPerSession = 0;
2730 gameInfo.timeControl = TimeControlTagValue();
2731 gameInfo.variant = StringToVariant(gameInfo.event);
2733 /* Do we have the ratings? */
2734 if (strcmp(player1Name, white) == 0 &&
2735 strcmp(player2Name, black) == 0) {
2736 if (appData.debugMode)
2737 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
2738 player1Rating, player2Rating);
2739 gameInfo.whiteRating = player1Rating;
2740 gameInfo.blackRating = player2Rating;
2741 } else if (strcmp(player2Name, white) == 0 &&
2742 strcmp(player1Name, black) == 0) {
2743 if (appData.debugMode)
2744 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
2745 player2Rating, player1Rating);
2746 gameInfo.whiteRating = player2Rating;
2747 gameInfo.blackRating = player1Rating;
2749 player1Name[0] = player2Name[0] = NULLCHAR;
2751 /* Silence shouts if requested */
2752 if (appData.quietPlay &&
2753 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)) {
2754 SendToICS(ics_prefix);
2755 SendToICS("set shout 0\n");
2759 /* Deal with midgame name changes */
2761 if (!gameInfo.white || strcmp(gameInfo.white, white) != 0) {
2762 if (gameInfo.white) free(gameInfo.white);
2763 gameInfo.white = StrSave(white);
2765 if (!gameInfo.black || strcmp(gameInfo.black, black) != 0) {
2766 if (gameInfo.black) free(gameInfo.black);
2767 gameInfo.black = StrSave(black);
2771 /* Throw away game result if anything actually changes in examine mode */
2772 if (gameMode == IcsExamining && !newGame) {
2773 gameInfo.result = GameUnfinished;
2774 if (gameInfo.resultDetails != NULL) {
2775 free(gameInfo.resultDetails);
2776 gameInfo.resultDetails = NULL;
2780 /* In pausing && IcsExamining mode, we ignore boards coming
2781 in if they are in a different variation than we are. */
2782 if (pauseExamInvalid) return;
2783 if (pausing && gameMode == IcsExamining) {
2784 if (moveNum <= pauseExamForwardMostMove) {
2785 pauseExamInvalid = TRUE;
2786 forwardMostMove = pauseExamForwardMostMove;
2791 /* Parse the board */
2792 for (k = 0; k < 8; k++)
2793 for (j = 0; j < 8; j++)
2794 board[k][j] = CharToPiece(board_chars[(7-k)*9 + j]);
2795 CopyBoard(boards[moveNum], board);
2797 startedFromSetupPosition =
2798 !CompareBoards(board, initialPosition);
2801 if (ics_getting_history == H_GOT_REQ_HEADER ||
2802 ics_getting_history == H_GOT_UNREQ_HEADER) {
2803 /* This was an initial position from a move list, not
2804 the current position */
2808 /* Update currentMove and known move number limits */
2809 newMove = newGame || moveNum > forwardMostMove;
2811 forwardMostMove = backwardMostMove = currentMove = moveNum;
2812 if (gameMode == IcsExamining && moveNum == 0) {
2813 /* Workaround for ICS limitation: we are not told the wild
2814 type when starting to examine a game. But if we ask for
2815 the move list, the move list header will tell us */
2816 ics_getting_history = H_REQUESTED;
2817 sprintf(str, "%smoves %d\n", ics_prefix, gamenum);
2820 } else if (moveNum == forwardMostMove + 1 || moveNum == forwardMostMove
2821 || (moveNum < forwardMostMove && moveNum >= backwardMostMove)) {
2822 forwardMostMove = moveNum;
2823 if (!pausing || currentMove > forwardMostMove)
2824 currentMove = forwardMostMove;
2826 /* New part of history that is not contiguous with old part */
2827 if (pausing && gameMode == IcsExamining) {
2828 pauseExamInvalid = TRUE;
2829 forwardMostMove = pauseExamForwardMostMove;
2832 forwardMostMove = backwardMostMove = currentMove = moveNum;
2833 if (gameMode == IcsExamining && moveNum > 0 && appData.getMoveList) {
2834 ics_getting_history = H_REQUESTED;
2835 sprintf(str, "%smoves %d\n", ics_prefix, gamenum);
2840 /* Update the clocks */
2841 if (strchr(elapsed_time, '.')) {
2843 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time;
2844 timeRemaining[1][moveNum] = blackTimeRemaining = black_time;
2846 /* Time is in seconds */
2847 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time * 1000;
2848 timeRemaining[1][moveNum] = blackTimeRemaining = black_time * 1000;
2853 if (appData.zippyPlay && newGame &&
2854 gameMode != IcsObserving && gameMode != IcsIdle &&
2855 gameMode != IcsExamining)
2856 ZippyFirstBoard(moveNum, basetime, increment);
2859 /* Put the move on the move list, first converting
2860 to canonical algebraic form. */
2862 if (moveNum <= backwardMostMove) {
2863 /* We don't know what the board looked like before
2865 strcpy(parseList[moveNum - 1], move_str);
2866 strcat(parseList[moveNum - 1], " ");
2867 strcat(parseList[moveNum - 1], elapsed_time);
2868 moveList[moveNum - 1][0] = NULLCHAR;
2869 } else if (ParseOneMove(move_str, moveNum - 1, &moveType,
2870 &fromX, &fromY, &toX, &toY, &promoChar)) {
2871 (void) CoordsToAlgebraic(boards[moveNum - 1],
2872 PosFlags(moveNum - 1), EP_UNKNOWN,
2873 fromY, fromX, toY, toX, promoChar,
2874 parseList[moveNum-1]);
2875 switch (MateTest(boards[moveNum], PosFlags(moveNum), EP_UNKNOWN)){
2881 strcat(parseList[moveNum - 1], "+");
2884 strcat(parseList[moveNum - 1], "#");
2887 strcat(parseList[moveNum - 1], " ");
2888 strcat(parseList[moveNum - 1], elapsed_time);
2889 /* currentMoveString is set as a side-effect of ParseOneMove */
2890 strcpy(moveList[moveNum - 1], currentMoveString);
2891 strcat(moveList[moveNum - 1], "\n");
2892 } else if (strcmp(move_str, "none") == 0) {
2893 /* Again, we don't know what the board looked like;
2894 this is really the start of the game. */
2895 parseList[moveNum - 1][0] = NULLCHAR;
2896 moveList[moveNum - 1][0] = NULLCHAR;
2897 backwardMostMove = moveNum;
2898 startedFromSetupPosition = TRUE;
2899 fromX = fromY = toX = toY = -1;
2901 /* Move from ICS was illegal!? Punt. */
2903 if (appData.testLegality && appData.debugMode) {
2904 sprintf(str, "Illegal move \"%s\" from ICS", move_str);
2905 DisplayError(str, 0);
2908 strcpy(parseList[moveNum - 1], move_str);
2909 strcat(parseList[moveNum - 1], " ");
2910 strcat(parseList[moveNum - 1], elapsed_time);
2911 moveList[moveNum - 1][0] = NULLCHAR;
2912 fromX = fromY = toX = toY = -1;
2916 /* Send move to chess program (BEFORE animating it). */
2917 if (appData.zippyPlay && !newGame && newMove &&
2918 (!appData.getMoveList || backwardMostMove == 0) && first.initDone) {
2920 if ((gameMode == IcsPlayingWhite && WhiteOnMove(moveNum)) ||
2921 (gameMode == IcsPlayingBlack && !WhiteOnMove(moveNum))) {
2922 if (moveList[moveNum - 1][0] == NULLCHAR) {
2923 sprintf(str, "Couldn't parse move \"%s\" from ICS",
2925 DisplayError(str, 0);
2927 if (first.sendTime) {
2928 SendTimeRemaining(&first, gameMode == IcsPlayingWhite);
2930 SendMoveToProgram(moveNum - 1, &first);
2933 if (first.useColors) {
2934 SendToProgram(gameMode == IcsPlayingWhite ?
2936 "black\ngo\n", &first);
2938 SendToProgram("go\n", &first);
2940 first.maybeThinking = TRUE;
2943 } else if (gameMode == IcsObserving || gameMode == IcsExamining) {
2944 if (moveList[moveNum - 1][0] == NULLCHAR) {
2945 sprintf(str, "Couldn't parse move \"%s\" from ICS", move_str);
2946 DisplayError(str, 0);
2948 SendMoveToProgram(moveNum - 1, &first);
2955 if (moveNum > 0 && !gotPremove) {
2956 /* If move comes from a remote source, animate it. If it
2957 isn't remote, it will have already been animated. */
2958 if (!pausing && !ics_user_moved && prevMove == moveNum - 1) {
2959 AnimateMove(boards[moveNum - 1], fromX, fromY, toX, toY);
2961 if (!pausing && appData.highlightLastMove) {
2962 SetHighlights(fromX, fromY, toX, toY);
2966 /* Start the clocks */
2967 whiteFlag = blackFlag = FALSE;
2968 appData.clockMode = !(basetime == 0 && increment == 0);
2970 ics_clock_paused = TRUE;
2972 } else if (ticking == 1) {
2973 ics_clock_paused = FALSE;
2975 if (gameMode == IcsIdle ||
2976 relation == RELATION_OBSERVING_STATIC ||
2977 relation == RELATION_EXAMINING ||
2979 DisplayBothClocks();
2983 /* Display opponents and material strengths */
2984 if (gameInfo.variant != VariantBughouse &&
2985 gameInfo.variant != VariantCrazyhouse) {
2986 if (tinyLayout || smallLayout) {
2987 sprintf(str, "%s(%d) %s(%d) {%d %d}",
2988 gameInfo.white, white_stren, gameInfo.black, black_stren,
2989 basetime, increment);
2991 sprintf(str, "%s (%d) vs. %s (%d) {%d %d}",
2992 gameInfo.white, white_stren, gameInfo.black, black_stren,
2993 basetime, increment);
2999 /* Display the board */
3002 if (appData.premove)
3004 ((gameMode == IcsPlayingWhite) && (WhiteOnMove(currentMove))) ||
3005 ((gameMode == IcsPlayingBlack) && (!WhiteOnMove(currentMove))))
3006 ClearPremoveHighlights();
3008 DrawPosition(FALSE, boards[currentMove]);
3009 DisplayMove(moveNum - 1);
3010 if (appData.ringBellAfterMoves && !ics_user_moved)
3014 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
3021 if (appData.icsActive && gameMode != IcsIdle && ics_gamenum > 0) {
3022 ics_getting_history = H_REQUESTED;
3023 sprintf(buf, "%smoves %d\n", ics_prefix, ics_gamenum);
3029 AnalysisPeriodicEvent(force)
3032 if (((programStats.ok_to_send == 0 || programStats.line_is_book)
3033 && !force) || !appData.periodicUpdates)
3036 /* Send . command to Crafty to collect stats */
3037 SendToProgram(".\n", &first);
3039 /* Don't send another until we get a response (this makes
3040 us stop sending to old Crafty's which don't understand
3041 the "." command (sending illegal cmds resets node count & time,
3042 which looks bad)) */
3043 programStats.ok_to_send = 0;
3047 SendMoveToProgram(moveNum, cps)
3049 ChessProgramState *cps;
3052 if (cps->useUsermove) {
3053 SendToProgram("usermove ", cps);
3057 if ((space = strchr(parseList[moveNum], ' ')) != NULL) {
3058 int len = space - parseList[moveNum];
3059 memcpy(buf, parseList[moveNum], len);
3061 buf[len] = NULLCHAR;
3063 sprintf(buf, "%s\n", parseList[moveNum]);
3065 SendToProgram(buf, cps);
3067 SendToProgram(moveList[moveNum], cps);
3072 SendMoveToICS(moveType, fromX, fromY, toX, toY)
3074 int fromX, fromY, toX, toY;
3076 char user_move[MSG_SIZ];
3080 sprintf(user_move, "say Internal error; bad moveType %d (%d,%d-%d,%d)",
3081 (int)moveType, fromX, fromY, toX, toY);
3082 DisplayError(user_move + strlen("say "), 0);
3084 case WhiteKingSideCastle:
3085 case BlackKingSideCastle:
3086 case WhiteQueenSideCastleWild:
3087 case BlackQueenSideCastleWild:
3088 sprintf(user_move, "o-o\n");
3090 case WhiteQueenSideCastle:
3091 case BlackQueenSideCastle:
3092 case WhiteKingSideCastleWild:
3093 case BlackKingSideCastleWild:
3094 sprintf(user_move, "o-o-o\n");
3096 case WhitePromotionQueen:
3097 case BlackPromotionQueen:
3098 case WhitePromotionRook:
3099 case BlackPromotionRook:
3100 case WhitePromotionBishop:
3101 case BlackPromotionBishop:
3102 case WhitePromotionKnight:
3103 case BlackPromotionKnight:
3104 case WhitePromotionKing:
3105 case BlackPromotionKing:
3106 sprintf(user_move, "%c%c%c%c=%c\n",
3107 'a' + fromX, '1' + fromY, 'a' + toX, '1' + toY,
3108 PieceToChar(PromoPiece(moveType)));
3112 sprintf(user_move, "%c@%c%c\n",
3113 ToUpper(PieceToChar((ChessSquare) fromX)),
3114 'a' + toX, '1' + toY);
3117 case WhiteCapturesEnPassant:
3118 case BlackCapturesEnPassant:
3119 case IllegalMove: /* could be a variant we don't quite understand */
3120 sprintf(user_move, "%c%c%c%c\n",
3121 'a' + fromX, '1' + fromY, 'a' + toX, '1' + toY);
3124 SendToICS(user_move);
3128 CoordsToComputerAlgebraic(rf, ff, rt, ft, promoChar, move)
3133 if (rf == DROP_RANK) {
3134 sprintf(move, "%c@%c%c\n",
3135 ToUpper(PieceToChar((ChessSquare) ff)), 'a' + ft, '1' + rt);
3137 if (promoChar == 'x' || promoChar == NULLCHAR) {
3138 sprintf(move, "%c%c%c%c\n",
3139 'a' + ff, '1' + rf, 'a' + ft, '1' + rt);
3141 sprintf(move, "%c%c%c%c%c\n",
3142 'a' + ff, '1' + rf, 'a' + ft, '1' + rt, promoChar);
3148 ProcessICSInitScript(f)
3153 while (fgets(buf, MSG_SIZ, f)) {
3154 SendToICSDelayed(buf,(long)appData.msLoginDelay);
3161 /* Parser for moves from gnuchess, ICS, or user typein box */
3163 ParseOneMove(move, moveNum, moveType, fromX, fromY, toX, toY, promoChar)
3166 ChessMove *moveType;
3167 int *fromX, *fromY, *toX, *toY;
3170 *moveType = yylexstr(moveNum, move);
3171 switch (*moveType) {
3172 case WhitePromotionQueen:
3173 case BlackPromotionQueen:
3174 case WhitePromotionRook:
3175 case BlackPromotionRook:
3176 case WhitePromotionBishop:
3177 case BlackPromotionBishop:
3178 case WhitePromotionKnight:
3179 case BlackPromotionKnight:
3180 case WhitePromotionKing:
3181 case BlackPromotionKing:
3183 case WhiteCapturesEnPassant:
3184 case BlackCapturesEnPassant:
3185 case WhiteKingSideCastle:
3186 case WhiteQueenSideCastle:
3187 case BlackKingSideCastle:
3188 case BlackQueenSideCastle:
3189 case WhiteKingSideCastleWild:
3190 case WhiteQueenSideCastleWild:
3191 case BlackKingSideCastleWild:
3192 case BlackQueenSideCastleWild:
3193 case IllegalMove: /* bug or odd chess variant */
3194 *fromX = currentMoveString[0] - 'a';
3195 *fromY = currentMoveString[1] - '1';
3196 *toX = currentMoveString[2] - 'a';
3197 *toY = currentMoveString[3] - '1';
3198 *promoChar = currentMoveString[4];
3199 if (*fromX < 0 || *fromX > 7 || *fromY < 0 || *fromY > 7 ||
3200 *toX < 0 || *toX > 7 || *toY < 0 || *toY > 7) {
3201 *fromX = *fromY = *toX = *toY = 0;
3204 if (appData.testLegality) {
3205 return (*moveType != IllegalMove);
3207 return !(fromX == fromY && toX == toY);
3212 *fromX = *moveType == WhiteDrop ?
3213 (int) CharToPiece(ToUpper(currentMoveString[0])) :
3214 (int) CharToPiece(ToLower(currentMoveString[0]));
3216 *toX = currentMoveString[2] - 'a';
3217 *toY = currentMoveString[3] - '1';
3218 *promoChar = NULLCHAR;
3222 case ImpossibleMove:
3223 case (ChessMove) 0: /* end of file */
3233 *fromX = *fromY = *toX = *toY = 0;
3234 *promoChar = NULLCHAR;
3241 InitPosition(redraw)
3244 currentMove = forwardMostMove = backwardMostMove = 0;
3245 switch (gameInfo.variant) {
3247 CopyBoard(boards[0], initialPosition);
3249 case VariantTwoKings:
3250 CopyBoard(boards[0], twoKingsPosition);
3251 startedFromSetupPosition = TRUE;
3253 case VariantWildCastle:
3254 CopyBoard(boards[0], initialPosition);
3255 /* !!?shuffle with kings guaranteed to be on d or e file */
3257 case VariantNoCastle:
3258 CopyBoard(boards[0], initialPosition);
3259 /* !!?unconstrained back-rank shuffle */
3261 case VariantFischeRandom:
3262 CopyBoard(boards[0], initialPosition);
3263 /* !!shuffle according to FR rules */
3267 DrawPosition(FALSE, boards[currentMove]);
3271 SendBoard(cps, moveNum)
3272 ChessProgramState *cps;
3275 char message[MSG_SIZ];
3277 if (cps->useSetboard) {
3278 char* fen = PositionToFEN(moveNum);
3279 sprintf(message, "setboard %s\n", fen);
3280 SendToProgram(message, cps);
3286 /* Kludge to set black to move, avoiding the troublesome and now
3287 * deprecated "black" command.
3289 if (!WhiteOnMove(moveNum)) SendToProgram("a2a3\n", cps);
3291 SendToProgram("edit\n", cps);
3292 SendToProgram("#\n", cps);
3293 for (i = BOARD_SIZE - 1; i >= 0; i--) {
3294 bp = &boards[moveNum][i][0];
3295 for (j = 0; j < BOARD_SIZE; j++, bp++) {
3296 if ((int) *bp < (int) BlackPawn) {
3297 sprintf(message, "%c%c%c\n", PieceToChar(*bp),
3299 SendToProgram(message, cps);
3304 SendToProgram("c\n", cps);
3305 for (i = BOARD_SIZE - 1; i >= 0; i--) {
3306 bp = &boards[moveNum][i][0];
3307 for (j = 0; j < BOARD_SIZE; j++, bp++) {
3308 if (((int) *bp != (int) EmptySquare)
3309 && ((int) *bp >= (int) BlackPawn)) {
3310 sprintf(message, "%c%c%c\n", ToUpper(PieceToChar(*bp)),
3312 SendToProgram(message, cps);
3317 SendToProgram(".\n", cps);
3322 IsPromotion(fromX, fromY, toX, toY)
3323 int fromX, fromY, toX, toY;
3325 return gameMode != EditPosition &&
3326 fromX >=0 && fromY >= 0 && toX >= 0 && toY >= 0 &&
3327 ((boards[currentMove][fromY][fromX] == WhitePawn && toY == 7) ||
3328 (boards[currentMove][fromY][fromX] == BlackPawn && toY == 0));
3333 PieceForSquare (x, y)
3337 if (x < 0 || x >= BOARD_SIZE || y < 0 || y >= BOARD_SIZE)
3340 return boards[currentMove][y][x];
3344 OKToStartUserMove(x, y)
3347 ChessSquare from_piece;
3350 if (matchMode) return FALSE;
3351 if (gameMode == EditPosition) return TRUE;
3353 if (x >= 0 && y >= 0)
3354 from_piece = boards[currentMove][y][x];
3356 from_piece = EmptySquare;
3358 if (from_piece == EmptySquare) return FALSE;
3360 white_piece = (int)from_piece >= (int)WhitePawn &&
3361 (int)from_piece <= (int)WhiteKing;
3364 case PlayFromGameFile:
3366 case TwoMachinesPlay:
3374 case MachinePlaysWhite:
3375 case IcsPlayingBlack:
3376 if (appData.zippyPlay) return FALSE;
3378 DisplayMoveError("You are playing Black");
3383 case MachinePlaysBlack:
3384 case IcsPlayingWhite:
3385 if (appData.zippyPlay) return FALSE;
3387 DisplayMoveError("You are playing White");
3393 if (!white_piece && WhiteOnMove(currentMove)) {
3394 DisplayMoveError("It is White's turn");
3397 if (white_piece && !WhiteOnMove(currentMove)) {
3398 DisplayMoveError("It is Black's turn");
3401 if (cmailMsgLoaded && (currentMove < cmailOldMove)) {
3402 /* Editing correspondence game history */
3403 /* Could disallow this or prompt for confirmation */
3406 if (currentMove < forwardMostMove) {
3407 /* Discarding moves */
3408 /* Could prompt for confirmation here,
3409 but I don't think that's such a good idea */
3410 forwardMostMove = currentMove;
3414 case BeginningOfGame:
3415 if (appData.icsActive) return FALSE;
3416 if (!appData.noChessProgram) {
3418 DisplayMoveError("You are playing White");
3425 if (!white_piece && WhiteOnMove(currentMove)) {
3426 DisplayMoveError("It is White's turn");
3429 if (white_piece && !WhiteOnMove(currentMove)) {
3430 DisplayMoveError("It is Black's turn");
3439 if (currentMove != forwardMostMove && gameMode != AnalyzeMode
3440 && gameMode != AnalyzeFile && gameMode != Training) {
3441 DisplayMoveError("Displayed position is not current");
3447 FILE *lastLoadGameFP = NULL, *lastLoadPositionFP = NULL;
3448 int lastLoadGameNumber = 0, lastLoadPositionNumber = 0;
3449 int lastLoadGameUseList = FALSE;
3450 char lastLoadGameTitle[MSG_SIZ], lastLoadPositionTitle[MSG_SIZ];
3451 ChessMove lastLoadGameStart = (ChessMove) 0;
3455 UserMoveEvent(fromX, fromY, toX, toY, promoChar)
3456 int fromX, fromY, toX, toY;
3461 if (fromX < 0 || fromY < 0) return;
3462 if ((fromX == toX) && (fromY == toY)) {
3466 /* Check if the user is playing in turn. This is complicated because we
3467 let the user "pick up" a piece before it is his turn. So the piece he
3468 tried to pick up may have been captured by the time he puts it down!
3469 Therefore we use the color the user is supposed to be playing in this
3470 test, not the color of the piece that is currently on the starting
3471 square---except in EditGame mode, where the user is playing both
3472 sides; fortunately there the capture race can't happen. (It can
3473 now happen in IcsExamining mode, but that's just too bad. The user
3474 will get a somewhat confusing message in that case.)
3478 case PlayFromGameFile:
3480 case TwoMachinesPlay:
3484 /* We switched into a game mode where moves are not accepted,
3485 perhaps while the mouse button was down. */
3488 case MachinePlaysWhite:
3489 /* User is moving for Black */
3490 if (WhiteOnMove(currentMove)) {
3491 DisplayMoveError("It is White's turn");
3496 case MachinePlaysBlack:
3497 /* User is moving for White */
3498 if (!WhiteOnMove(currentMove)) {
3499 DisplayMoveError("It is Black's turn");
3506 case BeginningOfGame:
3509 if ((int) boards[currentMove][fromY][fromX] >= (int) BlackPawn &&
3510 (int) boards[currentMove][fromY][fromX] <= (int) BlackKing) {
3511 /* User is moving for Black */
3512 if (WhiteOnMove(currentMove)) {
3513 DisplayMoveError("It is White's turn");
3517 /* User is moving for White */
3518 if (!WhiteOnMove(currentMove)) {
3519 DisplayMoveError("It is Black's turn");
3525 case IcsPlayingBlack:
3526 /* User is moving for Black */
3527 if (WhiteOnMove(currentMove)) {
3528 if (!appData.premove) {
3529 DisplayMoveError("It is White's turn");
3530 } else if (toX >= 0 && toY >= 0) {
3533 premoveFromX = fromX;
3534 premoveFromY = fromY;
3535 premovePromoChar = promoChar;
3537 if (appData.debugMode)
3538 fprintf(debugFP, "Got premove: fromX %d,"
3539 "fromY %d, toX %d, toY %d\n",
3540 fromX, fromY, toX, toY);
3546 case IcsPlayingWhite:
3547 /* User is moving for White */
3548 if (!WhiteOnMove(currentMove)) {
3549 if (!appData.premove) {
3550 DisplayMoveError("It is Black's turn");
3551 } else if (toX >= 0 && toY >= 0) {
3554 premoveFromX = fromX;
3555 premoveFromY = fromY;
3556 premovePromoChar = promoChar;
3558 if (appData.debugMode)
3559 fprintf(debugFP, "Got premove: fromX %d,"
3560 "fromY %d, toX %d, toY %d\n",
3561 fromX, fromY, toX, toY);
3571 if (toX == -2 || toY == -2) {
3572 boards[0][fromY][fromX] = EmptySquare;
3573 DrawPosition(FALSE, boards[currentMove]);
3574 } else if (toX >= 0 && toY >= 0) {
3575 boards[0][toY][toX] = boards[0][fromY][fromX];
3576 boards[0][fromY][fromX] = EmptySquare;
3577 DrawPosition(FALSE, boards[currentMove]);
3582 if (toX < 0 || toY < 0) return;
3583 userOfferedDraw = FALSE;
3585 if (appData.testLegality) {
3586 moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
3587 EP_UNKNOWN, fromY, fromX, toY, toX, promoChar);
3588 if (moveType == IllegalMove || moveType == ImpossibleMove) {
3589 DisplayMoveError("Illegal move");
3593 moveType = PromoCharToMoveType(WhiteOnMove(currentMove), promoChar);
3596 if (gameMode == Training) {
3597 /* compare the move played on the board to the next move in the
3598 * game. If they match, display the move and the opponent's response.
3599 * If they don't match, display an error message.
3603 CopyBoard(testBoard, boards[currentMove]);
3604 ApplyMove(fromX, fromY, toX, toY, promoChar, testBoard);
3606 if (CompareBoards(testBoard, boards[currentMove+1])) {
3607 ForwardInner(currentMove+1);
3609 /* Autoplay the opponent's response.
3610 * if appData.animate was TRUE when Training mode was entered,
3611 * the response will be animated.
3613 saveAnimate = appData.animate;
3614 appData.animate = animateTraining;
3615 ForwardInner(currentMove+1);
3616 appData.animate = saveAnimate;
3618 /* check for the end of the game */
3619 if (currentMove >= forwardMostMove) {
3620 gameMode = PlayFromGameFile;
3622 SetTrainingModeOff();
3623 DisplayInformation("End of game");
3626 DisplayError("Incorrect move", 0);
3631 FinishMove(moveType, fromX, fromY, toX, toY, promoChar);
3634 /* Common tail of UserMoveEvent and DropMenuEvent */
3636 FinishMove(moveType, fromX, fromY, toX, toY, promoChar)
3638 int fromX, fromY, toX, toY;
3639 /*char*/int promoChar;
3641 /* Ok, now we know that the move is good, so we can kill
3642 the previous line in Analysis Mode */
3643 if (gameMode == AnalyzeMode && currentMove < forwardMostMove) {
3644 forwardMostMove = currentMove;
3647 /* If we need the chess program but it's dead, restart it */
3648 ResurrectChessProgram();
3650 /* A user move restarts a paused game*/
3654 thinkOutput[0] = NULLCHAR;
3656 MakeMove(fromX, fromY, toX, toY, promoChar); /*updates forwardMostMove*/
3658 if (gameMode == BeginningOfGame) {
3659 if (appData.noChessProgram) {
3660 gameMode = EditGame;
3664 gameMode = MachinePlaysBlack;
3666 sprintf(buf, "%s vs. %s", gameInfo.white, gameInfo.black);
3668 if (first.sendName) {
3669 sprintf(buf, "name %s\n", gameInfo.white);
3670 SendToProgram(buf, &first);
3676 /* Relay move to ICS or chess engine */
3677 if (appData.icsActive) {
3678 if (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
3679 gameMode == IcsExamining) {
3680 SendMoveToICS(moveType, fromX, fromY, toX, toY);
3684 if (first.sendTime && (gameMode == BeginningOfGame ||
3685 gameMode == MachinePlaysWhite ||
3686 gameMode == MachinePlaysBlack)) {
3687 SendTimeRemaining(&first, gameMode != MachinePlaysBlack);
3689 SendMoveToProgram(forwardMostMove-1, &first);
3690 if (gameMode != EditGame && gameMode != PlayFromGameFile) {
3691 first.maybeThinking = TRUE;
3693 if (currentMove == cmailOldMove + 1) {
3694 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
3698 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
3702 switch (MateTest(boards[currentMove], PosFlags(currentMove),
3708 if (WhiteOnMove(currentMove)) {
3709 GameEnds(BlackWins, "Black mates", GE_PLAYER);
3711 GameEnds(WhiteWins, "White mates", GE_PLAYER);
3715 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
3720 case MachinePlaysBlack:
3721 case MachinePlaysWhite:
3722 /* disable certain menu options while machine is thinking */
3723 SetMachineThinkingEnables();
3732 HandleMachineMove(message, cps)
3734 ChessProgramState *cps;
3736 char machineMove[MSG_SIZ], buf1[MSG_SIZ*10], buf2[MSG_SIZ];
3737 char realname[MSG_SIZ];
3738 int fromX, fromY, toX, toY;
3745 * Kludge to ignore BEL characters
3747 while (*message == '\007') message++;
3750 * Look for book output
3752 if (cps == &first && bookRequested) {
3753 if (message[0] == '\t' || message[0] == ' ') {
3754 /* Part of the book output is here; append it */
3755 strcat(bookOutput, message);
3756 strcat(bookOutput, " \n");
3758 } else if (bookOutput[0] != NULLCHAR) {
3759 /* All of book output has arrived; display it */
3760 char *p = bookOutput;
3761 while (*p != NULLCHAR) {
3762 if (*p == '\t') *p = ' ';
3765 DisplayInformation(bookOutput);
3766 bookRequested = FALSE;
3767 /* Fall through to parse the current output */
3772 * Look for machine move.
3774 if ((sscanf(message, "%s %s %s", buf1, buf2, machineMove) == 3 &&
3775 strcmp(buf2, "...") == 0) ||
3776 (sscanf(message, "%s %s", buf1, machineMove) == 2 &&
3777 strcmp(buf1, "move") == 0)) {
3779 /* This method is only useful on engines that support ping */
3780 if (cps->lastPing != cps->lastPong) {
3781 if (gameMode == BeginningOfGame) {
3782 /* Extra move from before last new; ignore */
3783 if (appData.debugMode) {
3784 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
3787 if (appData.debugMode) {
3788 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
3789 cps->which, gameMode);
3791 SendToProgram("undo\n", cps);
3797 case BeginningOfGame:
3798 /* Extra move from before last reset; ignore */
3799 if (appData.debugMode) {
3800 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
3807 /* Extra move after we tried to stop. The mode test is
3808 not a reliable way of detecting this problem, but it's
3809 the best we can do on engines that don't support ping.
3811 if (appData.debugMode) {
3812 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
3813 cps->which, gameMode);
3815 SendToProgram("undo\n", cps);
3818 case MachinePlaysWhite:
3819 case IcsPlayingWhite:
3820 machineWhite = TRUE;
3823 case MachinePlaysBlack:
3824 case IcsPlayingBlack:
3825 machineWhite = FALSE;
3828 case TwoMachinesPlay:
3829 machineWhite = (cps->twoMachinesColor[0] == 'w');
3832 if (WhiteOnMove(forwardMostMove) != machineWhite) {
3833 if (appData.debugMode) {
3835 "Ignoring move out of turn by %s, gameMode %d"
3836 ", forwardMost %d\n",
3837 cps->which, gameMode, forwardMostMove);
3842 if (!ParseOneMove(machineMove, forwardMostMove, &moveType,
3843 &fromX, &fromY, &toX, &toY, &promoChar)) {
3844 /* Machine move could not be parsed; ignore it. */
3845 sprintf(buf1, "Illegal move \"%s\" from %s machine",
3846 machineMove, cps->which);
3847 DisplayError(buf1, 0);
3848 if (gameMode == TwoMachinesPlay) {
3849 GameEnds(machineWhite ? BlackWins : WhiteWins,
3850 "Forfeit due to illegal move", GE_XBOARD);
3855 hintRequested = FALSE;
3856 lastHint[0] = NULLCHAR;
3857 bookRequested = FALSE;
3858 /* Program may be pondering now */
3859 cps->maybeThinking = TRUE;
3860 if (cps->sendTime == 2) cps->sendTime = 1;
3861 if (cps->offeredDraw) cps->offeredDraw--;
3864 if ((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack) &&
3866 SendMoveToICS(moveType, fromX, fromY, toX, toY);
3870 /* currentMoveString is set as a side-effect of ParseOneMove */
3871 strcpy(machineMove, currentMoveString);
3872 strcat(machineMove, "\n");
3873 strcpy(moveList[forwardMostMove], machineMove);
3875 MakeMove(fromX, fromY, toX, toY, promoChar);/*updates forwardMostMove*/
3877 if (gameMode == TwoMachinesPlay) {
3878 if (cps->other->sendTime) {
3879 SendTimeRemaining(cps->other,
3880 cps->other->twoMachinesColor[0] == 'w');
3882 SendMoveToProgram(forwardMostMove-1, cps->other);
3885 if (cps->other->useColors) {
3886 SendToProgram(cps->other->twoMachinesColor, cps->other);
3888 SendToProgram("go\n", cps->other);
3890 cps->other->maybeThinking = TRUE;
3893 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
3894 if (!pausing && appData.ringBellAfterMoves) {
3898 * Reenable menu items that were disabled while
3899 * machine was thinking
3901 if (gameMode != TwoMachinesPlay)
3902 SetUserThinkingEnables();
3906 /* Set special modes for chess engines. Later something general
3907 * could be added here; for now there is just one kludge feature,
3908 * needed because Crafty 15.10 and earlier don't ignore SIGINT
3909 * when "xboard" is given as an interactive command.
3911 if (strncmp(message, "kibitz Hello from Crafty", 24) == 0) {
3912 cps->useSigint = FALSE;
3913 cps->useSigterm = FALSE;
3917 * Look for communication commands
3919 if (!strncmp(message, "telluser ", 9)) {
3920 DisplayNote(message + 9);
3923 if (!strncmp(message, "tellusererror ", 14)) {
3924 DisplayError(message + 14, 0);
3927 if (!strncmp(message, "tellopponent ", 13)) {
3928 if (appData.icsActive) {
3930 sprintf(buf1, "%ssay %s\n", ics_prefix, message + 13);
3934 DisplayNote(message + 13);
3938 if (!strncmp(message, "tellothers ", 11)) {
3939 if (appData.icsActive) {
3941 sprintf(buf1, "%swhisper %s\n", ics_prefix, message + 11);
3947 if (!strncmp(message, "tellall ", 8)) {
3948 if (appData.icsActive) {
3950 sprintf(buf1, "%skibitz %s\n", ics_prefix, message + 8);
3954 DisplayNote(message + 8);
3958 if (strncmp(message, "warning", 7) == 0) {
3959 /* Undocumented feature, use tellusererror in new code */
3960 DisplayError(message, 0);
3963 if (sscanf(message, "askuser %s %[^\n]", buf1, buf2) == 2) {
3964 strcpy(realname, cps->tidy);
3965 strcat(realname, " query");
3966 AskQuestion(realname, buf2, buf1, cps->pr);
3969 /* Commands from the engine directly to ICS. We don't allow these to be
3970 * sent until we are logged on. Crafty kibitzes have been known to
3971 * interfere with the login process.
3974 if (!strncmp(message, "tellics ", 8)) {
3975 SendToICS(message + 8);
3979 if (!strncmp(message, "tellicsnoalias ", 15)) {
3980 SendToICS(ics_prefix);
3981 SendToICS(message + 15);
3985 /* The following are for backward compatibility only */
3986 if (!strncmp(message,"whisper",7) || !strncmp(message,"kibitz",6) ||
3987 !strncmp(message,"draw",4) || !strncmp(message,"tell",3)) {
3988 SendToICS(ics_prefix);
3994 if (strncmp(message, "feature ", 8) == 0) {
3995 ParseFeatures(message+8, cps);
3997 if (sscanf(message, "pong %d", &cps->lastPong) == 1) {
4001 * If the move is illegal, cancel it and redraw the board.
4002 * Also deal with other error cases. Matching is rather loose
4003 * here to accommodate engines written before the spec.
4005 if (strncmp(message + 1, "llegal move", 11) == 0 ||
4006 strncmp(message, "Error", 5) == 0) {
4007 if (StrStr(message, "name") ||
4008 StrStr(message, "rating") || StrStr(message, "?") ||
4009 StrStr(message, "result") || StrStr(message, "board") ||
4010 StrStr(message, "bk") || StrStr(message, "computer") ||
4011 StrStr(message, "variant") || StrStr(message, "hint") ||
4012 StrStr(message, "random") || StrStr(message, "depth") ||
4013 StrStr(message, "accepted")) {
4016 if (StrStr(message, "protover")) {
4017 /* Program is responding to input, so it's apparently done
4018 initializing, and this error message indicates it is
4019 protocol version 1. So we don't need to wait any longer
4020 for it to initialize and send feature commands. */
4021 FeatureDone(cps, 1);
4022 cps->protocolVersion = 1;
4025 cps->maybeThinking = FALSE;
4027 if (StrStr(message, "draw")) {
4028 /* Program doesn't have "draw" command */
4029 cps->sendDrawOffers = 0;
4032 if (cps->sendTime != 1 &&
4033 (StrStr(message, "time") || StrStr(message, "otim"))) {
4034 /* Program apparently doesn't have "time" or "otim" command */
4038 if (StrStr(message, "analyze")) {
4039 cps->analysisSupport = FALSE;
4040 cps->analyzing = FALSE;
4042 sprintf(buf2, "%s does not support analysis", cps->tidy);
4043 DisplayError(buf2, 0);
4046 if (StrStr(message, "(no matching move)st")) {
4047 /* Special kludge for GNU Chess 4 only */
4048 cps->stKludge = TRUE;
4049 SendTimeControl(cps, movesPerSession, timeControl,
4050 timeIncrement, appData.searchDepth,
4054 if (StrStr(message, "(no matching move)sd")) {
4055 /* Special kludge for GNU Chess 4 only */
4056 cps->sdKludge = TRUE;
4057 SendTimeControl(cps, movesPerSession, timeControl,
4058 timeIncrement, appData.searchDepth,
4062 if (!StrStr(message, "llegal")) return;
4063 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
4064 gameMode == IcsIdle) return;
4065 if (forwardMostMove <= backwardMostMove) return;
4067 /* Following removed: it caused a bug where a real illegal move
4068 message in analyze mored would be ignored. */
4069 if (cps == &first && programStats.ok_to_send == 0) {
4070 /* Bogus message from Crafty responding to "." This filtering
4071 can miss some of the bad messages, but fortunately the bug
4072 is fixed in current Crafty versions, so it doesn't matter. */
4076 if (pausing) PauseEvent();
4077 if (gameMode == PlayFromGameFile) {
4078 /* Stop reading this game file */
4079 gameMode = EditGame;
4082 currentMove = --forwardMostMove;
4083 DisplayMove(currentMove-1); /* before DisplayMoveError */
4085 DisplayBothClocks();
4086 sprintf(buf1, "Illegal move \"%s\" (rejected by %s chess program)",
4087 parseList[currentMove], cps->which);
4088 DisplayMoveError(buf1);
4089 DrawPosition(FALSE, boards[currentMove]);
4092 if (strncmp(message, "time", 4) == 0 && StrStr(message, "Illegal")) {
4093 /* Program has a broken "time" command that
4094 outputs a string not ending in newline.
4100 * If chess program startup fails, exit with an error message.
4101 * Attempts to recover here are futile.
4103 if ((StrStr(message, "unknown host") != NULL)
4104 || (StrStr(message, "No remote directory") != NULL)
4105 || (StrStr(message, "not found") != NULL)
4106 || (StrStr(message, "No such file") != NULL)
4107 || (StrStr(message, "can't alloc") != NULL)
4108 || (StrStr(message, "Permission denied") != NULL)) {
4110 cps->maybeThinking = FALSE;
4111 sprintf(buf1, "Failed to start %s chess program %s on %s: %s\n",
4112 cps->which, cps->program, cps->host, message);
4113 RemoveInputSource(cps->isr);
4114 DisplayFatalError(buf1, 0, 1);
4119 * Look for hint output
4121 if (sscanf(message, "Hint: %s", buf1) == 1) {
4122 if (cps == &first && hintRequested) {
4123 hintRequested = FALSE;
4124 if (ParseOneMove(buf1, forwardMostMove, &moveType,
4125 &fromX, &fromY, &toX, &toY, &promoChar)) {
4126 (void) CoordsToAlgebraic(boards[forwardMostMove],
4127 PosFlags(forwardMostMove), EP_UNKNOWN,
4128 fromY, fromX, toY, toX, promoChar, buf1);
4129 sprintf(buf2, "Hint: %s", buf1);
4130 DisplayInformation(buf2);
4132 /* Hint move could not be parsed!? */
4134 "Illegal hint move \"%s\"\nfrom %s chess program",
4136 DisplayError(buf2, 0);
4139 strcpy(lastHint, buf1);
4145 * Ignore other messages if game is not in progress
4147 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
4148 gameMode == IcsIdle || cps->lastPing != cps->lastPong) return;
4151 * look for win, lose, draw, or draw offer
4153 if (strncmp(message, "1-0", 3) == 0) {
4154 char *p, *q, *r = "";
4155 p = strchr(message, '{');
4163 GameEnds(WhiteWins, r, GE_ENGINE);
4165 } else if (strncmp(message, "0-1", 3) == 0) {
4166 char *p, *q, *r = "";
4167 p = strchr(message, '{');
4175 /* Kludge for Arasan 4.1 bug */
4176 if (strcmp(r, "Black resigns") == 0) {
4177 GameEnds(WhiteWins, r, GE_ENGINE);
4180 GameEnds(BlackWins, r, GE_ENGINE);
4182 } else if (strncmp(message, "1/2", 3) == 0) {
4183 char *p, *q, *r = "";
4184 p = strchr(message, '{');
4192 GameEnds(GameIsDrawn, r, GE_ENGINE);
4195 } else if (strncmp(message, "White resign", 12) == 0) {
4196 GameEnds(BlackWins, "White resigns", GE_ENGINE);
4198 } else if (strncmp(message, "Black resign", 12) == 0) {
4199 GameEnds(WhiteWins, "Black resigns", GE_ENGINE);
4201 } else if (strncmp(message, "White", 5) == 0 &&
4202 message[5] != '(' &&
4203 StrStr(message, "Black") == NULL) {
4204 GameEnds(WhiteWins, "White mates", GE_ENGINE);
4206 } else if (strncmp(message, "Black", 5) == 0 &&
4207 message[5] != '(') {
4208 GameEnds(BlackWins, "Black mates", GE_ENGINE);
4210 } else if (strcmp(message, "resign") == 0 ||
4211 strcmp(message, "computer resigns") == 0) {
4213 case MachinePlaysBlack:
4214 case IcsPlayingBlack:
4215 GameEnds(WhiteWins, "Black resigns", GE_ENGINE);
4217 case MachinePlaysWhite:
4218 case IcsPlayingWhite:
4219 GameEnds(BlackWins, "White resigns", GE_ENGINE);
4221 case TwoMachinesPlay:
4222 if (cps->twoMachinesColor[0] == 'w')
4223 GameEnds(BlackWins, "White resigns", GE_ENGINE);
4225 GameEnds(WhiteWins, "Black resigns", GE_ENGINE);
4232 } else if (strncmp(message, "opponent mates", 14) == 0) {
4234 case MachinePlaysBlack:
4235 case IcsPlayingBlack:
4236 GameEnds(WhiteWins, "White mates", GE_ENGINE);
4238 case MachinePlaysWhite:
4239 case IcsPlayingWhite:
4240 GameEnds(BlackWins, "Black mates", GE_ENGINE);
4242 case TwoMachinesPlay:
4243 if (cps->twoMachinesColor[0] == 'w')
4244 GameEnds(BlackWins, "Black mates", GE_ENGINE);
4246 GameEnds(WhiteWins, "White mates", GE_ENGINE);
4253 } else if (strncmp(message, "computer mates", 14) == 0) {
4255 case MachinePlaysBlack:
4256 case IcsPlayingBlack:
4257 GameEnds(BlackWins, "Black mates", GE_ENGINE);
4259 case MachinePlaysWhite:
4260 case IcsPlayingWhite:
4261 GameEnds(WhiteWins, "White mates", GE_ENGINE);
4263 case TwoMachinesPlay:
4264 if (cps->twoMachinesColor[0] == 'w')
4265 GameEnds(WhiteWins, "White mates", GE_ENGINE);
4267 GameEnds(BlackWins, "Black mates", GE_ENGINE);
4274 } else if (strncmp(message, "checkmate", 9) == 0) {
4275 if (WhiteOnMove(forwardMostMove)) {
4276 GameEnds(BlackWins, "Black mates", GE_ENGINE);
4278 GameEnds(WhiteWins, "White mates", GE_ENGINE);
4281 } else if (strstr(message, "Draw") != NULL ||
4282 strstr(message, "game is a draw") != NULL) {
4283 GameEnds(GameIsDrawn, "Draw", GE_ENGINE);
4285 } else if (strstr(message, "offer") != NULL &&
4286 strstr(message, "draw") != NULL) {
4288 if (appData.zippyPlay && first.initDone) {
4289 /* Relay offer to ICS */
4290 SendToICS(ics_prefix);
4291 SendToICS("draw\n");
4294 cps->offeredDraw = 2; /* valid until this engine moves twice */
4295 if (gameMode == TwoMachinesPlay) {
4296 if (cps->other->offeredDraw) {
4297 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
4299 if (cps->other->sendDrawOffers) {
4300 SendToProgram("draw\n", cps->other);
4303 } else if (gameMode == MachinePlaysWhite ||
4304 gameMode == MachinePlaysBlack) {
4305 if (userOfferedDraw) {
4306 DisplayInformation("Machine accepts your draw offer");
4307 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
4309 DisplayInformation("Machine offers a draw\nSelect Action / Draw to agree");
4316 * Look for thinking output
4318 if (appData.showThinking) {
4319 int plylev, mvleft, mvtot, curscore, time;
4320 char mvname[MOVE_LEN];
4321 unsigned long nodes;
4324 int prefixHint = FALSE;
4325 mvname[0] = NULLCHAR;
4328 case MachinePlaysBlack:
4329 case IcsPlayingBlack:
4330 if (WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
4332 case MachinePlaysWhite:
4333 case IcsPlayingWhite:
4334 if (!WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
4339 case TwoMachinesPlay:
4340 if ((cps->twoMachinesColor[0] == 'w') !=
4341 WhiteOnMove(forwardMostMove)) {
4352 if (sscanf(message, "%d%c %d %d %lu %[^\n]\n",
4353 &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5) {
4355 if (plyext != ' ' && plyext != '\t') {
4358 programStats.depth = plylev;
4359 programStats.nodes = nodes;
4360 programStats.time = time;
4361 programStats.score = curscore;
4362 programStats.got_only_move = 0;
4364 /* Buffer overflow protection */
4365 if (buf1[0] != NULLCHAR) {
4366 if (strlen(buf1) >= sizeof(programStats.movelist)
4367 && appData.debugMode) {
4369 "PV is too long; using the first %d bytes.\n",
4370 sizeof(programStats.movelist) - 1);
4372 strncpy(programStats.movelist, buf1,
4373 sizeof(programStats.movelist));
4374 programStats.movelist[sizeof(programStats.movelist) - 1]
4377 sprintf(programStats.movelist, " no PV\n");
4380 if (programStats.seen_stat) {
4381 programStats.ok_to_send = 1;
4384 if (strchr(programStats.movelist, '(') != NULL) {
4385 programStats.line_is_book = 1;
4386 programStats.nr_moves = 0;
4387 programStats.moves_left = 0;
4389 programStats.line_is_book = 0;
4392 sprintf(thinkOutput, "[%d]%c%+.2f %s%s%s",
4394 (gameMode == TwoMachinesPlay ?
4395 ToUpper(cps->twoMachinesColor[0]) : ' '),
4396 ((double) curscore) / 100.0,
4397 prefixHint ? lastHint : "",
4398 prefixHint ? " " : "", buf1);
4400 if (currentMove == forwardMostMove ||
4401 gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
4402 DisplayMove(currentMove - 1);
4407 } else if ((p=StrStr(message, "(only move)")) != NULL) {
4408 /* crafty (9.25+) says "(only move) <move>"
4409 * if there is only 1 legal move
4411 sscanf(p, "(only move) %s", buf1);
4412 sprintf(thinkOutput, "%s (only move)", buf1);
4413 sprintf(programStats.movelist, "%s (only move)", buf1);
4414 programStats.depth = 1;
4415 programStats.nr_moves = 1;
4416 programStats.moves_left = 1;
4417 programStats.nodes = 1;
4418 programStats.time = 1;
4419 programStats.got_only_move = 1;
4421 /* Not really, but we also use this member to
4422 mean "line isn't going to change" (Crafty
4423 isn't searching, so stats won't change) */
4424 programStats.line_is_book = 1;
4426 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
4427 gameMode == AnalyzeFile) {
4428 DisplayMove(currentMove - 1);
4432 } else if (sscanf(message,"stat01: %d %lu %d %d %d %s",
4433 &time, &nodes, &plylev, &mvleft,
4434 &mvtot, mvname) >= 5) {
4435 /* The stat01: line is from Crafty (9.29+) in response
4436 to the "." command */
4437 programStats.seen_stat = 1;
4438 cps->maybeThinking = TRUE;
4440 if (programStats.got_only_move || !appData.periodicUpdates)
4443 programStats.depth = plylev;
4444 programStats.time = time;
4445 programStats.nodes = nodes;
4446 programStats.moves_left = mvleft;
4447 programStats.nr_moves = mvtot;
4448 strcpy(programStats.move_name, mvname);
4449 programStats.ok_to_send = 1;
4453 } else if (strncmp(message,"++",2) == 0) {
4454 /* Crafty 9.29+ outputs this */
4455 programStats.got_fail = 2;
4458 } else if (strncmp(message,"--",2) == 0) {
4459 /* Crafty 9.29+ outputs this */
4460 programStats.got_fail = 1;
4463 } else if (thinkOutput[0] != NULLCHAR &&
4464 strncmp(message, " ", 4) == 0) {
4466 while (*p && *p == ' ') p++;
4467 strcat(thinkOutput, " ");
4468 strcat(thinkOutput, p);
4469 strcat(programStats.movelist, " ");
4470 strcat(programStats.movelist, p);
4471 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
4472 gameMode == AnalyzeFile) {
4473 DisplayMove(currentMove - 1);
4483 /* Parse a game score from the character string "game", and
4484 record it as the history of the current game. The game
4485 score is NOT assumed to start from the standard position.
4486 The display is not updated in any way.
4489 ParseGameHistory(game)
4493 int fromX, fromY, toX, toY, boardIndex;
4498 if (appData.debugMode)
4499 fprintf(debugFP, "Parsing game history: %s\n", game);
4501 if (gameInfo.event == NULL) gameInfo.event = StrSave("ICS game");
4502 gameInfo.site = StrSave(appData.icsHost);
4503 gameInfo.date = PGNDate();
4504 gameInfo.round = StrSave("-");
4506 /* Parse out names of players */
4507 while (*game == ' ') game++;
4509 while (*game != ' ') *p++ = *game++;
4511 gameInfo.white = StrSave(buf);
4512 while (*game == ' ') game++;
4514 while (*game != ' ' && *game != '\n') *p++ = *game++;
4516 gameInfo.black = StrSave(buf);
4519 boardIndex = blackPlaysFirst ? 1 : 0;
4522 yyboardindex = boardIndex;
4523 moveType = (ChessMove) yylex();
4525 case WhitePromotionQueen:
4526 case BlackPromotionQueen:
4527 case WhitePromotionRook:
4528 case BlackPromotionRook:
4529 case WhitePromotionBishop:
4530 case BlackPromotionBishop:
4531 case WhitePromotionKnight:
4532 case BlackPromotionKnight:
4533 case WhitePromotionKing:
4534 case BlackPromotionKing:
4536 case WhiteCapturesEnPassant:
4537 case BlackCapturesEnPassant:
4538 case WhiteKingSideCastle:
4539 case WhiteQueenSideCastle:
4540 case BlackKingSideCastle:
4541 case BlackQueenSideCastle:
4542 case WhiteKingSideCastleWild:
4543 case WhiteQueenSideCastleWild:
4544 case BlackKingSideCastleWild:
4545 case BlackQueenSideCastleWild:
4546 case IllegalMove: /* maybe suicide chess, etc. */
4547 fromX = currentMoveString[0] - 'a';
4548 fromY = currentMoveString[1] - '1';
4549 toX = currentMoveString[2] - 'a';
4550 toY = currentMoveString[3] - '1';
4551 promoChar = currentMoveString[4];
4555 fromX = moveType == WhiteDrop ?
4556 (int) CharToPiece(ToUpper(currentMoveString[0])) :
4557 (int) CharToPiece(ToLower(currentMoveString[0]));
4559 toX = currentMoveString[2] - 'a';
4560 toY = currentMoveString[3] - '1';
4561 promoChar = NULLCHAR;
4565 sprintf(buf, "Ambiguous move in ICS output: \"%s\"", yy_text);
4566 DisplayError(buf, 0);
4568 case ImpossibleMove:
4570 sprintf(buf, "Illegal move in ICS output: \"%s\"", yy_text);
4571 DisplayError(buf, 0);
4573 case (ChessMove) 0: /* end of file */
4574 if (boardIndex < backwardMostMove) {
4575 /* Oops, gap. How did that happen? */
4576 DisplayError("Gap in move list", 0);
4579 backwardMostMove = blackPlaysFirst ? 1 : 0;
4580 if (boardIndex > forwardMostMove) {
4581 forwardMostMove = boardIndex;
4585 if (boardIndex > (blackPlaysFirst ? 1 : 0)) {
4586 strcat(parseList[boardIndex-1], " ");
4587 strcat(parseList[boardIndex-1], yy_text);
4599 case GameUnfinished:
4600 if (gameMode == IcsExamining) {
4601 if (boardIndex < backwardMostMove) {
4602 /* Oops, gap. How did that happen? */
4605 backwardMostMove = blackPlaysFirst ? 1 : 0;
4608 gameInfo.result = moveType;
4609 p = strchr(yy_text, '{');
4610 if (p == NULL) p = strchr(yy_text, '(');
4613 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
4615 q = strchr(p, *p == '{' ? '}' : ')');
4616 if (q != NULL) *q = NULLCHAR;
4619 gameInfo.resultDetails = StrSave(p);
4622 if (boardIndex >= forwardMostMove &&
4623 !(gameMode == IcsObserving && ics_gamenum == -1)) {
4624 backwardMostMove = blackPlaysFirst ? 1 : 0;
4627 (void) CoordsToAlgebraic(boards[boardIndex], PosFlags(boardIndex),
4628 EP_UNKNOWN, fromY, fromX, toY, toX, promoChar,
4629 parseList[boardIndex]);
4630 CopyBoard(boards[boardIndex + 1], boards[boardIndex]);
4631 /* currentMoveString is set as a side-effect of yylex */
4632 strcpy(moveList[boardIndex], currentMoveString);
4633 strcat(moveList[boardIndex], "\n");
4635 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[boardIndex]);
4636 switch (MateTest(boards[boardIndex],
4637 PosFlags(boardIndex), EP_UNKNOWN)) {
4643 strcat(parseList[boardIndex - 1], "+");
4646 strcat(parseList[boardIndex - 1], "#");
4653 /* Apply a move to the given board */
4655 ApplyMove(fromX, fromY, toX, toY, promoChar, board)
4656 int fromX, fromY, toX, toY;
4660 ChessSquare captured = board[toY][toX];
4661 if (fromY == DROP_RANK) {
4663 board[toY][toX] = (ChessSquare) fromX;
4664 } else if (fromX == toX && fromY == toY) {
4666 } else if (fromY == 0 && fromX == 4
4667 && board[fromY][fromX] == WhiteKing
4668 && toY == 0 && toX == 6) {
4669 board[fromY][fromX] = EmptySquare;
4670 board[toY][toX] = WhiteKing;
4671 board[fromY][7] = EmptySquare;
4672 board[toY][5] = WhiteRook;
4673 } else if (fromY == 0 && fromX == 4
4674 && board[fromY][fromX] == WhiteKing
4675 && toY == 0 && toX == 2) {
4676 board[fromY][fromX] = EmptySquare;
4677 board[toY][toX] = WhiteKing;
4678 board[fromY][0] = EmptySquare;
4679 board[toY][3] = WhiteRook;
4680 } else if (fromY == 0 && fromX == 3
4681 && board[fromY][fromX] == WhiteKing
4682 && toY == 0 && toX == 5) {
4683 board[fromY][fromX] = EmptySquare;
4684 board[toY][toX] = WhiteKing;
4685 board[fromY][7] = EmptySquare;
4686 board[toY][4] = WhiteRook;
4687 } else if (fromY == 0 && fromX == 3
4688 && board[fromY][fromX] == WhiteKing
4689 && toY == 0 && toX == 1) {
4690 board[fromY][fromX] = EmptySquare;
4691 board[toY][toX] = WhiteKing;
4692 board[fromY][0] = EmptySquare;
4693 board[toY][2] = WhiteRook;
4694 } else if (board[fromY][fromX] == WhitePawn
4696 /* white pawn promotion */
4697 board[7][toX] = CharToPiece(ToUpper(promoChar));
4698 if (board[7][toX] == EmptySquare) {
4699 board[7][toX] = WhiteQueen;
4701 board[fromY][fromX] = EmptySquare;
4702 } else if ((fromY == 4)
4704 && (board[fromY][fromX] == WhitePawn)
4705 && (board[toY][toX] == EmptySquare)) {
4706 board[fromY][fromX] = EmptySquare;
4707 board[toY][toX] = WhitePawn;
4708 captured = board[toY - 1][toX];
4709 board[toY - 1][toX] = EmptySquare;
4710 } else if (fromY == 7 && fromX == 4
4711 && board[fromY][fromX] == BlackKing
4712 && toY == 7 && toX == 6) {
4713 board[fromY][fromX] = EmptySquare;
4714 board[toY][toX] = BlackKing;
4715 board[fromY][7] = EmptySquare;
4716 board[toY][5] = BlackRook;
4717 } else if (fromY == 7 && fromX == 4
4718 && board[fromY][fromX] == BlackKing
4719 && toY == 7 && toX == 2) {
4720 board[fromY][fromX] = EmptySquare;
4721 board[toY][toX] = BlackKing;
4722 board[fromY][0] = EmptySquare;
4723 board[toY][3] = BlackRook;
4724 } else if (fromY == 7 && fromX == 3
4725 && board[fromY][fromX] == BlackKing
4726 && toY == 7 && toX == 5) {
4727 board[fromY][fromX] = EmptySquare;
4728 board[toY][toX] = BlackKing;
4729 board[fromY][7] = EmptySquare;
4730 board[toY][4] = BlackRook;
4731 } else if (fromY == 7 && fromX == 3
4732 && board[fromY][fromX] == BlackKing
4733 && toY == 7 && toX == 1) {
4734 board[fromY][fromX] = EmptySquare;
4735 board[toY][toX] = BlackKing;
4736 board[fromY][0] = EmptySquare;
4737 board[toY][2] = BlackRook;
4738 } else if (board[fromY][fromX] == BlackPawn
4740 /* black pawn promotion */
4741 board[0][toX] = CharToPiece(ToLower(promoChar));
4742 if (board[0][toX] == EmptySquare) {
4743 board[0][toX] = BlackQueen;
4745 board[fromY][fromX] = EmptySquare;
4746 } else if ((fromY == 3)
4748 && (board[fromY][fromX] == BlackPawn)
4749 && (board[toY][toX] == EmptySquare)) {
4750 board[fromY][fromX] = EmptySquare;
4751 board[toY][toX] = BlackPawn;
4752 captured = board[toY + 1][toX];
4753 board[toY + 1][toX] = EmptySquare;
4755 board[toY][toX] = board[fromY][fromX];
4756 board[fromY][fromX] = EmptySquare;
4758 if (gameInfo.variant == VariantCrazyhouse) {
4760 /* !!A lot more code needs to be written to support holdings */
4761 if (fromY == DROP_RANK) {
4762 /* Delete from holdings */
4763 if (holdings[(int) fromX] > 0) holdings[(int) fromX]--;
4765 if (captured != EmptySquare) {
4766 /* Add to holdings */
4767 if (captured < BlackPawn) {
4768 holdings[(int)captured - (int)BlackPawn + (int)WhitePawn]++;
4770 holdings[(int)captured - (int)WhitePawn + (int)BlackPawn]++;
4774 } else if (gameInfo.variant == VariantAtomic) {
4775 if (captured != EmptySquare) {
4777 for (y = toY-1; y <= toY+1; y++) {
4778 for (x = toX-1; x <= toX+1; x++) {
4779 if (y >= 0 && y <= 7 && x >= 0 && x <= 7 &&
4780 board[y][x] != WhitePawn && board[y][x] != BlackPawn) {
4781 board[y][x] = EmptySquare;
4785 board[toY][toX] = EmptySquare;
4790 /* Updates forwardMostMove */
4792 MakeMove(fromX, fromY, toX, toY, promoChar)
4793 int fromX, fromY, toX, toY;
4797 if (forwardMostMove >= MAX_MOVES) {
4798 DisplayFatalError("Game too long; increase MAX_MOVES and recompile",
4803 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
4804 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
4805 if (commentList[forwardMostMove] != NULL) {
4806 free(commentList[forwardMostMove]);
4807 commentList[forwardMostMove] = NULL;
4809 CopyBoard(boards[forwardMostMove], boards[forwardMostMove - 1]);
4810 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[forwardMostMove]);
4811 gameInfo.result = GameUnfinished;
4812 if (gameInfo.resultDetails != NULL) {
4813 free(gameInfo.resultDetails);
4814 gameInfo.resultDetails = NULL;
4816 CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar,
4817 moveList[forwardMostMove - 1]);
4818 (void) CoordsToAlgebraic(boards[forwardMostMove - 1],
4819 PosFlags(forwardMostMove - 1), EP_UNKNOWN,
4820 fromY, fromX, toY, toX, promoChar,
4821 parseList[forwardMostMove - 1]);
4822 switch (MateTest(boards[forwardMostMove],
4823 PosFlags(forwardMostMove), EP_UNKNOWN)){
4829 strcat(parseList[forwardMostMove - 1], "+");
4832 strcat(parseList[forwardMostMove - 1], "#");
4837 /* Updates currentMove if not pausing */
4839 ShowMove(fromX, fromY, toX, toY)
4841 int instant = (gameMode == PlayFromGameFile) ?
4842 (matchMode || (appData.timeDelay == 0 && !pausing)) : pausing;
4843 if (!pausing || gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
4845 if (forwardMostMove == currentMove + 1) {
4846 AnimateMove(boards[forwardMostMove - 1],
4847 fromX, fromY, toX, toY);
4849 if (appData.highlightLastMove) {
4850 SetHighlights(fromX, fromY, toX, toY);
4853 currentMove = forwardMostMove;
4856 if (instant) return;
4857 DisplayMove(currentMove - 1);
4858 DrawPosition(FALSE, boards[currentMove]);
4859 DisplayBothClocks();
4860 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
4865 InitChessProgram(cps)
4866 ChessProgramState *cps;
4869 if (appData.noChessProgram) return;
4870 hintRequested = FALSE;
4871 bookRequested = FALSE;
4872 SendToProgram(cps->initString, cps);
4873 if (gameInfo.variant != VariantNormal &&
4874 gameInfo.variant != VariantLoadable) {
4875 char *v = VariantName(gameInfo.variant);
4876 if (StrStr(cps->variants, v) == NULL) {
4877 sprintf(buf, "Variant %s not supported by %s", v, cps->tidy);
4878 DisplayFatalError(buf, 0, 1);
4881 sprintf(buf, "variant %s\n", VariantName(gameInfo.variant));
4882 SendToProgram(buf, cps);
4885 sprintf(buf, "ics %s\n", appData.icsActive ? appData.icsHost : "-");
4886 SendToProgram(buf, cps);
4888 cps->maybeThinking = FALSE;
4889 cps->offeredDraw = 0;
4890 if (!appData.icsActive) {
4891 SendTimeControl(cps, movesPerSession, timeControl,
4892 timeIncrement, appData.searchDepth,
4895 if (appData.showThinking) {
4896 SendToProgram("post\n", cps);
4898 SendToProgram("hard\n", cps);
4899 if (!appData.ponderNextMove) {
4900 /* Warning: "easy" is a toggle in GNU Chess, so don't send
4901 it without being sure what state we are in first. "hard"
4902 is not a toggle, so that one is OK.
4904 SendToProgram("easy\n", cps);
4907 sprintf(buf, "ping %d\n", ++cps->lastPing);
4908 SendToProgram(buf, cps);
4910 cps->initDone = TRUE;
4915 StartChessProgram(cps)
4916 ChessProgramState *cps;
4921 if (appData.noChessProgram) return;
4922 cps->initDone = FALSE;
4924 if (strcmp(cps->host, "localhost") == 0) {
4925 err = StartChildProcess(cps->program, cps->dir, &cps->pr);
4926 } else if (*appData.remoteShell == NULLCHAR) {
4927 err = OpenRcmd(cps->host, appData.remoteUser, cps->program, &cps->pr);
4929 if (*appData.remoteUser == NULLCHAR) {
4930 sprintf(buf, "%s %s %s", appData.remoteShell, cps->host,
4933 sprintf(buf, "%s %s -l %s %s", appData.remoteShell,
4934 cps->host, appData.remoteUser, cps->program);
4936 err = StartChildProcess(buf, "", &cps->pr);
4940 sprintf(buf, "Startup failure on '%s'", cps->program);
4941 DisplayFatalError(buf, err, 1);
4947 cps->isr = AddInputSource(cps->pr, TRUE, ReceiveFromProgram, cps);
4948 if (cps->protocolVersion > 1) {
4949 sprintf(buf, "xboard\nprotover %d\n", cps->protocolVersion);
4950 SendToProgram(buf, cps);
4952 SendToProgram("xboard\n", cps);
4958 TwoMachinesEventIfReady P((void))
4960 if (first.lastPing != first.lastPong) {
4961 DisplayMessage("", "Waiting for first chess program");
4962 ScheduleDelayedEvent(TwoMachinesEventIfReady, 1000);
4965 if (second.lastPing != second.lastPong) {
4966 DisplayMessage("", "Waiting for second chess program");
4967 ScheduleDelayedEvent(TwoMachinesEventIfReady, 1000);
4975 NextMatchGame P((void))
4978 if (*appData.loadGameFile != NULLCHAR) {
4979 LoadGameFromFile(appData.loadGameFile,
4980 appData.loadGameIndex,
4981 appData.loadGameFile, FALSE);
4982 } else if (*appData.loadPositionFile != NULLCHAR) {
4983 LoadPositionFromFile(appData.loadPositionFile,
4984 appData.loadPositionIndex,
4985 appData.loadPositionFile);
4987 TwoMachinesEventIfReady();
4991 GameEnds(result, resultDetails, whosays)
4993 char *resultDetails;
4996 GameMode nextGameMode;
4999 if (appData.debugMode) {
5000 fprintf(debugFP, "GameEnds(%d, %s, %d)\n",
5001 result, resultDetails ? resultDetails : "(null)", whosays);
5004 if (appData.icsActive && whosays == GE_ENGINE) {
5005 /* If we are playing on ICS, the server decides when the
5006 game is over, but the engine can offer to draw, claim
5010 if (appData.zippyPlay && first.initDone) {
5011 if (result == GameIsDrawn) {
5012 /* In case draw still needs to be claimed */
5013 SendToICS(ics_prefix);
5014 SendToICS("draw\n");
5015 } else if (StrCaseStr(resultDetails, "resign")) {
5016 SendToICS(ics_prefix);
5017 SendToICS("resign\n");
5024 /* If we're loading the game from a file, stop */
5025 if (whosays == GE_FILE) {
5026 (void) StopLoadGameTimer();
5030 /* Cancel draw offers */
5031 first.offeredDraw = second.offeredDraw = 0;
5033 /* If this is an ICS game, only ICS can really say it's done;
5034 if not, anyone can. */
5035 isIcsGame = (gameMode == IcsPlayingWhite ||
5036 gameMode == IcsPlayingBlack ||
5037 gameMode == IcsObserving ||
5038 gameMode == IcsExamining);
5040 if (!isIcsGame || whosays == GE_ICS) {
5041 /* OK -- not an ICS game, or ICS said it was done */
5043 if (!isIcsGame && !appData.noChessProgram)
5044 SetUserThinkingEnables();
5046 if (resultDetails != NULL) {
5047 gameInfo.result = result;
5048 gameInfo.resultDetails = StrSave(resultDetails);
5050 /* Tell program how game ended in case it is learning */
5051 if (gameMode == MachinePlaysWhite ||
5052 gameMode == MachinePlaysBlack ||
5053 gameMode == TwoMachinesPlay ||
5054 gameMode == IcsPlayingWhite ||
5055 gameMode == IcsPlayingBlack ||
5056 gameMode == BeginningOfGame) {
5058 sprintf(buf, "result %s {%s}\n", PGNResult(result),
5060 if (first.pr != NoProc) {
5061 SendToProgram(buf, &first);
5063 if (second.pr != NoProc &&
5064 gameMode == TwoMachinesPlay) {
5065 SendToProgram(buf, &second);
5069 /* display last move only if game was not loaded from file */
5070 if ((whosays != GE_FILE) && (currentMove == forwardMostMove))
5071 DisplayMove(currentMove - 1);
5073 if (forwardMostMove != 0) {
5074 if (gameMode != PlayFromGameFile && gameMode != EditGame) {
5075 if (*appData.saveGameFile != NULLCHAR) {
5076 SaveGameToFile(appData.saveGameFile, TRUE);
5077 } else if (appData.autoSaveGames) {
5080 if (*appData.savePositionFile != NULLCHAR) {
5081 SavePositionToFile(appData.savePositionFile);
5087 if (appData.icsActive) {
5088 if (appData.quietPlay &&
5089 (gameMode == IcsPlayingWhite ||
5090 gameMode == IcsPlayingBlack)) {
5091 SendToICS(ics_prefix);
5092 SendToICS("set shout 1\n");
5094 nextGameMode = IcsIdle;
5095 ics_user_moved = FALSE;
5096 /* clean up premove. It's ugly when the game has ended and the
5097 * premove highlights are still on the board.
5101 ClearPremoveHighlights();
5102 DrawPosition(FALSE, boards[currentMove]);
5104 if (whosays == GE_ICS) {
5107 if (gameMode == IcsPlayingWhite)
5109 else if(gameMode == IcsPlayingBlack)
5113 if (gameMode == IcsPlayingBlack)
5115 else if(gameMode == IcsPlayingWhite)
5122 PlayIcsUnfinishedSound();
5125 } else if (gameMode == EditGame ||
5126 gameMode == PlayFromGameFile ||
5127 gameMode == AnalyzeMode ||
5128 gameMode == AnalyzeFile) {
5129 nextGameMode = gameMode;
5131 nextGameMode = EndOfGame;
5136 nextGameMode = gameMode;
5139 if (appData.noChessProgram) {
5140 gameMode = nextGameMode;
5146 /* Put first chess program into idle state */
5147 if (first.pr != NoProc &&
5148 (gameMode == MachinePlaysWhite ||
5149 gameMode == MachinePlaysBlack ||
5150 gameMode == TwoMachinesPlay ||
5151 gameMode == IcsPlayingWhite ||
5152 gameMode == IcsPlayingBlack ||
5153 gameMode == BeginningOfGame)) {
5154 SendToProgram("force\n", &first);
5155 if (first.usePing) {
5157 sprintf(buf, "ping %d\n", ++first.lastPing);
5158 SendToProgram(buf, &first);
5161 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
5162 /* Kill off first chess program */
5163 if (first.isr != NULL)
5164 RemoveInputSource(first.isr);
5167 if (first.pr != NoProc) {
5169 SendToProgram("quit\n", &first);
5170 DestroyChildProcess(first.pr, first.useSigterm);
5175 /* Put second chess program into idle state */
5176 if (second.pr != NoProc &&
5177 gameMode == TwoMachinesPlay) {
5178 SendToProgram("force\n", &second);
5179 if (second.usePing) {
5181 sprintf(buf, "ping %d\n", ++second.lastPing);
5182 SendToProgram(buf, &second);
5185 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
5186 /* Kill off second chess program */
5187 if (second.isr != NULL)
5188 RemoveInputSource(second.isr);
5191 if (second.pr != NoProc) {
5192 SendToProgram("quit\n", &second);
5193 DestroyChildProcess(second.pr, second.useSigterm);
5198 if (matchMode && gameMode == TwoMachinesPlay) {
5201 if (first.twoMachinesColor[0] == 'w') {
5208 if (first.twoMachinesColor[0] == 'b') {
5217 if (matchGame < appData.matchGames) {
5219 tmp = first.twoMachinesColor;
5220 first.twoMachinesColor = second.twoMachinesColor;
5221 second.twoMachinesColor = tmp;
5222 gameMode = nextGameMode;
5224 ScheduleDelayedEvent(NextMatchGame, 10000);
5228 gameMode = nextGameMode;
5229 sprintf(buf, "Match %s vs. %s: final score %d-%d-%d",
5230 first.tidy, second.tidy,
5231 first.matchWins, second.matchWins,
5232 appData.matchGames - (first.matchWins + second.matchWins));
5233 DisplayFatalError(buf, 0, 0);
5236 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile) &&
5237 !(nextGameMode == AnalyzeMode || nextGameMode == AnalyzeFile))
5239 gameMode = nextGameMode;
5243 /* Assumes program was just initialized (initString sent).
5244 Leaves program in force mode. */
5246 FeedMovesToProgram(cps, upto)
5247 ChessProgramState *cps;
5252 if (appData.debugMode)
5253 fprintf(debugFP, "Feeding %smoves %d through %d to %s chess program\n",
5254 startedFromSetupPosition ? "position and " : "",
5255 backwardMostMove, upto, cps->which);
5256 SendToProgram("force\n", cps);
5257 if (startedFromSetupPosition) {
5258 SendBoard(cps, backwardMostMove);
5260 for (i = backwardMostMove; i < upto; i++) {
5261 SendMoveToProgram(i, cps);
5267 ResurrectChessProgram()
5269 /* The chess program may have exited.
5270 If so, restart it and feed it all the moves made so far. */
5272 if (appData.noChessProgram || first.pr != NoProc) return;
5274 StartChessProgram(&first);
5275 InitChessProgram(&first);
5276 FeedMovesToProgram(&first, currentMove);
5278 if (!first.sendTime) {
5279 /* can't tell gnuchess what its clock should read,
5280 so we bow to its notion. */
5282 timeRemaining[0][currentMove] = whiteTimeRemaining;
5283 timeRemaining[1][currentMove] = blackTimeRemaining;
5286 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile) &&
5287 first.analysisSupport) {
5288 SendToProgram("analyze\n", &first);
5289 first.analyzing = TRUE;
5302 if (appData.debugMode) {
5303 fprintf(debugFP, "Reset(%d, %d) from gameMode %d\n",
5304 redraw, init, gameMode);
5307 pausing = pauseExamInvalid = FALSE;
5308 startedFromSetupPosition = blackPlaysFirst = FALSE;
5310 whiteFlag = blackFlag = FALSE;
5311 userOfferedDraw = FALSE;
5312 hintRequested = bookRequested = FALSE;
5313 first.maybeThinking = FALSE;
5314 second.maybeThinking = FALSE;
5315 thinkOutput[0] = NULLCHAR;
5316 lastHint[0] = NULLCHAR;
5317 ClearGameInfo(&gameInfo);
5318 gameInfo.variant = StringToVariant(appData.variant);
5319 ics_user_moved = ics_clock_paused = FALSE;
5320 ics_getting_history = H_FALSE;
5322 white_holding[0] = black_holding[0] = NULLCHAR;
5323 ClearProgramStats();
5327 flipView = appData.flipView;
5328 ClearPremoveHighlights();
5330 alarmSounded = FALSE;
5332 GameEnds((ChessMove) 0, NULL, GE_PLAYER);
5334 gameMode = BeginningOfGame;
5336 InitPosition(redraw);
5337 for (i = 0; i < MAX_MOVES; i++) {
5338 if (commentList[i] != NULL) {
5339 free(commentList[i]);
5340 commentList[i] = NULL;
5344 timeRemaining[0][0] = whiteTimeRemaining;
5345 timeRemaining[1][0] = blackTimeRemaining;
5346 if (first.pr == NULL) {
5347 StartChessProgram(&first);
5349 if (init) InitChessProgram(&first);
5351 DisplayMessage("", "");
5352 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
5359 if (!AutoPlayOneMove())
5361 if (matchMode || appData.timeDelay == 0)
5363 if (appData.timeDelay < 0 || gameMode == AnalyzeFile)
5365 StartLoadGameTimer((long)(1000.0 * appData.timeDelay));
5374 int fromX, fromY, toX, toY;
5376 if (appData.debugMode) {
5377 fprintf(debugFP, "AutoPlayOneMove(): current %d\n", currentMove);
5380 if (gameMode != PlayFromGameFile)
5383 if (currentMove >= forwardMostMove) {
5384 gameMode = EditGame;
5389 toX = moveList[currentMove][2] - 'a';
5390 toY = moveList[currentMove][3] - '1';
5392 if (moveList[currentMove][1] == '@') {
5393 if (appData.highlightLastMove) {
5394 SetHighlights(-1, -1, toX, toY);
5397 fromX = moveList[currentMove][0] - 'a';
5398 fromY = moveList[currentMove][1] - '1';
5399 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
5401 if (appData.highlightLastMove) {
5402 SetHighlights(fromX, fromY, toX, toY);
5405 DisplayMove(currentMove);
5406 SendMoveToProgram(currentMove++, &first);
5407 DisplayBothClocks();
5408 DrawPosition(FALSE, boards[currentMove]);
5409 if (commentList[currentMove] != NULL) {
5410 DisplayComment(currentMove - 1, commentList[currentMove]);
5417 LoadGameOneMove(readAhead)
5418 ChessMove readAhead;
5420 int fromX = 0, fromY = 0, toX = 0, toY = 0, done;
5421 char promoChar = NULLCHAR;
5426 if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile &&
5427 gameMode != AnalyzeMode && gameMode != Training) {
5432 yyboardindex = forwardMostMove;
5433 if (readAhead != (ChessMove)0) {
5434 moveType = readAhead;
5436 if (gameFileFP == NULL)
5438 moveType = (ChessMove) yylex();
5444 if (appData.debugMode)
5445 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
5447 if (*p == '{' || *p == '[' || *p == '(') {
5448 p[strlen(p) - 1] = NULLCHAR;
5452 /* append the comment but don't display it */
5453 while (*p == '\n') p++;
5454 AppendComment(currentMove, p);
5457 case WhiteCapturesEnPassant:
5458 case BlackCapturesEnPassant:
5459 case WhitePromotionQueen:
5460 case BlackPromotionQueen:
5461 case WhitePromotionRook:
5462 case BlackPromotionRook:
5463 case WhitePromotionBishop:
5464 case BlackPromotionBishop:
5465 case WhitePromotionKnight:
5466 case BlackPromotionKnight:
5467 case WhitePromotionKing:
5468 case BlackPromotionKing:
5470 case WhiteKingSideCastle:
5471 case WhiteQueenSideCastle:
5472 case BlackKingSideCastle:
5473 case BlackQueenSideCastle:
5474 case WhiteKingSideCastleWild:
5475 case WhiteQueenSideCastleWild:
5476 case BlackKingSideCastleWild:
5477 case BlackQueenSideCastleWild:
5478 if (appData.debugMode)
5479 fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
5480 fromX = currentMoveString[0] - 'a';
5481 fromY = currentMoveString[1] - '1';
5482 toX = currentMoveString[2] - 'a';
5483 toY = currentMoveString[3] - '1';
5484 promoChar = currentMoveString[4];
5489 if (appData.debugMode)
5490 fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
5491 fromX = moveType == WhiteDrop ?
5492 (int) CharToPiece(ToUpper(currentMoveString[0])) :
5493 (int) CharToPiece(ToLower(currentMoveString[0]));
5495 toX = currentMoveString[2] - 'a';
5496 toY = currentMoveString[3] - '1';
5502 case GameUnfinished:
5503 if (appData.debugMode)
5504 fprintf(debugFP, "Parsed game end: %s\n", yy_text);
5505 p = strchr(yy_text, '{');
5506 if (p == NULL) p = strchr(yy_text, '(');
5509 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
5511 q = strchr(p, *p == '{' ? '}' : ')');
5512 if (q != NULL) *q = NULLCHAR;
5515 GameEnds(moveType, p, GE_FILE);
5517 if (cmailMsgLoaded) {
5519 flipView = WhiteOnMove(currentMove);
5520 if (moveType == GameUnfinished) flipView = !flipView;
5521 if (appData.debugMode)
5522 fprintf(debugFP, "Setting flipView to %d\n", flipView) ;
5526 case (ChessMove) 0: /* end of file */
5527 if (appData.debugMode)
5528 fprintf(debugFP, "Parser hit end of file\n");
5529 switch (MateTest(boards[currentMove], PosFlags(currentMove),
5535 if (WhiteOnMove(currentMove)) {
5536 GameEnds(BlackWins, "Black mates", GE_FILE);
5538 GameEnds(WhiteWins, "White mates", GE_FILE);
5542 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
5549 if (lastLoadGameStart == GNUChessGame) {
5550 /* GNUChessGames have numbers, but they aren't move numbers */
5551 if (appData.debugMode)
5552 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
5553 yy_text, (int) moveType);
5554 return LoadGameOneMove((ChessMove)0); /* tail recursion */
5556 /* else fall thru */
5561 /* Reached start of next game in file */
5562 if (appData.debugMode)
5563 fprintf(debugFP, "Parsed start of next game: %s\n", yy_text);
5564 switch (MateTest(boards[currentMove], PosFlags(currentMove),
5570 if (WhiteOnMove(currentMove)) {
5571 GameEnds(BlackWins, "Black mates", GE_FILE);
5573 GameEnds(WhiteWins, "White mates", GE_FILE);
5577 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
5583 case PositionDiagram: /* should not happen; ignore */
5584 case ElapsedTime: /* ignore */
5585 case NAG: /* ignore */
5586 if (appData.debugMode)
5587 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
5588 yy_text, (int) moveType);
5589 return LoadGameOneMove((ChessMove)0); /* tail recursion */
5592 if (appData.testLegality) {
5593 if (appData.debugMode)
5594 fprintf(debugFP, "Parsed IllegalMove: %s\n", yy_text);
5595 sprintf(move, "Illegal move: %d.%s%s",
5596 (forwardMostMove / 2) + 1,
5597 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
5598 DisplayError(move, 0);
5601 if (appData.debugMode)
5602 fprintf(debugFP, "Parsed %s into IllegalMove %s\n",
5603 yy_text, currentMoveString);
5604 fromX = currentMoveString[0] - 'a';
5605 fromY = currentMoveString[1] - '1';
5606 toX = currentMoveString[2] - 'a';
5607 toY = currentMoveString[3] - '1';
5608 promoChar = currentMoveString[4];
5613 if (appData.debugMode)
5614 fprintf(debugFP, "Parsed AmbiguousMove: %s\n", yy_text);
5615 sprintf(move, "Ambiguous move: %d.%s%s",
5616 (forwardMostMove / 2) + 1,
5617 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
5618 DisplayError(move, 0);
5623 case ImpossibleMove:
5624 if (appData.debugMode)
5625 fprintf(debugFP, "Parsed ImpossibleMove: %s\n", yy_text);
5626 sprintf(move, "Illegal move: %d.%s%s",
5627 (forwardMostMove / 2) + 1,
5628 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
5629 DisplayError(move, 0);
5635 if (appData.matchMode || (appData.timeDelay == 0 && !pausing)) {
5636 DrawPosition(FALSE, boards[currentMove]);
5637 DisplayBothClocks();
5638 if (!appData.matchMode && commentList[currentMove] != NULL)
5639 DisplayComment(currentMove - 1, commentList[currentMove]);
5641 (void) StopLoadGameTimer();
5643 cmailOldMove = forwardMostMove;
5646 /* currentMoveString is set as a side-effect of yylex */
5647 strcat(currentMoveString, "\n");
5648 strcpy(moveList[forwardMostMove], currentMoveString);
5650 thinkOutput[0] = NULLCHAR;
5651 MakeMove(fromX, fromY, toX, toY, promoChar);
5652 currentMove = forwardMostMove;
5657 /* Load the nth game from the given file */
5659 LoadGameFromFile(filename, n, title, useList)
5663 /*Boolean*/ int useList;
5668 if (strcmp(filename, "-") == 0) {
5672 f = fopen(filename, "rb");
5674 sprintf(buf, "Can't open \"%s\"", filename);
5675 DisplayError(buf, errno);
5679 if (fseek(f, 0, 0) == -1) {
5680 /* f is not seekable; probably a pipe */
5683 if (useList && n == 0) {
5684 int error = GameListBuild(f);
5686 DisplayError("Cannot build game list", error);
5687 } else if (!ListEmpty(&gameList) &&
5688 ((ListGame *) gameList.tailPred)->number > 1) {
5689 GameListPopUp(f, title);
5696 return LoadGame(f, n, title, FALSE);
5701 MakeRegisteredMove()
5703 int fromX, fromY, toX, toY;
5705 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
5706 switch (cmailMoveType[lastLoadGameNumber - 1]) {
5709 if (appData.debugMode)
5710 fprintf(debugFP, "Restoring %s for game %d\n",
5711 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
5713 thinkOutput[0] = NULLCHAR;
5714 strcpy(moveList[currentMove], cmailMove[lastLoadGameNumber - 1]);
5715 fromX = cmailMove[lastLoadGameNumber - 1][0] - 'a';
5716 fromY = cmailMove[lastLoadGameNumber - 1][1] - '1';
5717 toX = cmailMove[lastLoadGameNumber - 1][2] - 'a';
5718 toY = cmailMove[lastLoadGameNumber - 1][3] - '1';
5719 promoChar = cmailMove[lastLoadGameNumber - 1][4];
5720 MakeMove(fromX, fromY, toX, toY, promoChar);
5721 ShowMove(fromX, fromY, toX, toY);
5723 switch (MateTest(boards[currentMove], PosFlags(currentMove),
5730 if (WhiteOnMove(currentMove)) {
5731 GameEnds(BlackWins, "Black mates", GE_PLAYER);
5733 GameEnds(WhiteWins, "White mates", GE_PLAYER);
5738 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
5745 if (WhiteOnMove(currentMove)) {
5746 GameEnds(BlackWins, "White resigns", GE_PLAYER);
5748 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
5753 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
5764 /* Wrapper around LoadGame for use when a Cmail message is loaded */
5766 CmailLoadGame(f, gameNumber, title, useList)
5774 if (gameNumber > nCmailGames) {
5775 DisplayError("No more games in this message", 0);
5778 if (f == lastLoadGameFP) {
5779 int offset = gameNumber - lastLoadGameNumber;
5781 cmailMsg[0] = NULLCHAR;
5782 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
5783 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
5784 nCmailMovesRegistered--;
5786 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
5787 if (cmailResult[lastLoadGameNumber - 1] == CMAIL_NEW_RESULT) {
5788 cmailResult[lastLoadGameNumber - 1] = CMAIL_NOT_RESULT;
5791 if (! RegisterMove()) return FALSE;
5795 retVal = LoadGame(f, gameNumber, title, useList);
5797 /* Make move registered during previous look at this game, if any */
5798 MakeRegisteredMove();
5800 if (cmailCommentList[lastLoadGameNumber - 1] != NULL) {
5801 commentList[currentMove]
5802 = StrSave(cmailCommentList[lastLoadGameNumber - 1]);
5803 DisplayComment(currentMove - 1, commentList[currentMove]);
5809 /* Support for LoadNextGame, LoadPreviousGame, ReloadSameGame */
5814 int gameNumber = lastLoadGameNumber + offset;
5815 if (lastLoadGameFP == NULL) {
5816 DisplayError("No game has been loaded yet", 0);
5819 if (gameNumber <= 0) {
5820 DisplayError("Can't back up any further", 0);
5823 if (cmailMsgLoaded) {
5824 return CmailLoadGame(lastLoadGameFP, gameNumber,
5825 lastLoadGameTitle, lastLoadGameUseList);
5827 return LoadGame(lastLoadGameFP, gameNumber,
5828 lastLoadGameTitle, lastLoadGameUseList);
5834 /* Load the nth game from open file f */
5836 LoadGame(f, gameNumber, title, useList)
5844 int gn = gameNumber;
5845 ListGame *lg = NULL;
5848 GameMode oldGameMode;
5850 if (appData.debugMode)
5851 fprintf(debugFP, "LoadGame(): on entry, gameMode %d\n", gameMode);
5853 if (gameMode == Training )
5854 SetTrainingModeOff();
5856 oldGameMode = gameMode;
5857 if (gameMode != BeginningOfGame) {
5862 if (lastLoadGameFP != NULL && lastLoadGameFP != f) {
5863 fclose(lastLoadGameFP);
5867 lg = (ListGame *) ListElem(&gameList, gameNumber-1);
5870 fseek(f, lg->offset, 0);
5871 GameListHighlight(gameNumber);
5875 DisplayError("Game number out of range", 0);
5880 if (fseek(f, 0, 0) == -1) {
5881 if (f == lastLoadGameFP ?
5882 gameNumber == lastLoadGameNumber + 1 :
5886 DisplayError("Can't seek on game file", 0);
5892 lastLoadGameNumber = gameNumber;
5893 strcpy(lastLoadGameTitle, title);
5894 lastLoadGameUseList = useList;
5899 if (lg && lg->gameInfo.white && lg->gameInfo.black) {
5900 sprintf(buf, "%s vs. %s", lg->gameInfo.white,
5901 lg->gameInfo.black);
5903 } else if (*title != NULLCHAR) {
5904 if (gameNumber > 1) {
5905 sprintf(buf, "%s %d", title, gameNumber);
5908 DisplayTitle(title);
5912 if (gameMode != AnalyzeFile && gameMode != AnalyzeMode) {
5913 gameMode = PlayFromGameFile;
5917 currentMove = forwardMostMove = backwardMostMove = 0;
5918 CopyBoard(boards[0], initialPosition);
5922 * Skip the first gn-1 games in the file.
5923 * Also skip over anything that precedes an identifiable
5924 * start of game marker, to avoid being confused by
5925 * garbage at the start of the file. Currently
5926 * recognized start of game markers are the move number "1",
5927 * the pattern "gnuchess .* game", the pattern
5928 * "^[#;%] [^ ]* game file", and a PGN tag block.
5929 * A game that starts with one of the latter two patterns
5930 * will also have a move number 1, possibly
5931 * following a position diagram.
5932 * 5-4-02: Let's try being more lenient and allowing a game to
5933 * start with an unnumbered move. Does that break anything?
5935 cm = lastLoadGameStart = (ChessMove) 0;
5937 yyboardindex = forwardMostMove;
5938 cm = (ChessMove) yylex();
5941 if (cmailMsgLoaded) {
5942 nCmailGames = CMAIL_MAX_GAMES - gn;
5945 DisplayError("Game not found in file", 0);
5952 lastLoadGameStart = cm;
5956 switch (lastLoadGameStart) {
5963 gn--; /* count this game */
5964 lastLoadGameStart = cm;
5973 switch (lastLoadGameStart) {
5978 gn--; /* count this game */
5979 lastLoadGameStart = cm;
5982 lastLoadGameStart = cm; /* game counted already */
5990 yyboardindex = forwardMostMove;
5991 cm = (ChessMove) yylex();
5992 } while (cm == PGNTag || cm == Comment);
5999 if (cmailMsgLoaded && (CMAIL_MAX_GAMES == lastLoadGameNumber)) {
6000 if ( cmailResult[CMAIL_MAX_GAMES - gn - 1]
6001 != CMAIL_OLD_RESULT) {
6003 cmailResult[ CMAIL_MAX_GAMES
6004 - gn - 1] = CMAIL_OLD_RESULT;
6010 /* Only a NormalMove can be at the start of a game
6011 * without a position diagram. */
6012 if (lastLoadGameStart == (ChessMove) 0) {
6014 lastLoadGameStart = MoveNumberOne;
6023 if (appData.debugMode)
6024 fprintf(debugFP, "Parsed game start '%s' (%d)\n", yy_text, (int) cm);
6026 if (cm == XBoardGame) {
6027 /* Skip any header junk before position diagram and/or move 1 */
6029 yyboardindex = forwardMostMove;
6030 cm = (ChessMove) yylex();
6032 if (cm == (ChessMove) 0 ||
6033 cm == GNUChessGame || cm == XBoardGame) {
6034 /* Empty game; pretend end-of-file and handle later */
6039 if (cm == MoveNumberOne || cm == PositionDiagram ||
6040 cm == PGNTag || cm == Comment)
6043 } else if (cm == GNUChessGame) {
6044 if (gameInfo.event != NULL) {
6045 free(gameInfo.event);
6047 gameInfo.event = StrSave(yy_text);
6050 startedFromSetupPosition = FALSE;
6051 while (cm == PGNTag) {
6052 if (appData.debugMode)
6053 fprintf(debugFP, "Parsed PGNTag: %s\n", yy_text);
6054 err = ParsePGNTag(yy_text, &gameInfo);
6055 if (!err) numPGNTags++;
6057 if (gameInfo.fen != NULL) {
6058 Board initial_position;
6059 startedFromSetupPosition = TRUE;
6060 if (!ParseFEN(initial_position, &blackPlaysFirst, gameInfo.fen)) {
6062 DisplayError("Bad FEN position in file", 0);
6065 CopyBoard(boards[0], initial_position);
6066 if (blackPlaysFirst) {
6067 currentMove = forwardMostMove = backwardMostMove = 1;
6068 CopyBoard(boards[1], initial_position);
6069 strcpy(moveList[0], "");
6070 strcpy(parseList[0], "");
6071 timeRemaining[0][1] = whiteTimeRemaining;
6072 timeRemaining[1][1] = blackTimeRemaining;
6073 if (commentList[0] != NULL) {
6074 commentList[1] = commentList[0];
6075 commentList[0] = NULL;
6078 currentMove = forwardMostMove = backwardMostMove = 0;
6080 yyboardindex = forwardMostMove;
6082 gameInfo.fen = NULL;
6085 yyboardindex = forwardMostMove;
6086 cm = (ChessMove) yylex();
6088 /* Handle comments interspersed among the tags */
6089 while (cm == Comment) {
6091 if (appData.debugMode)
6092 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
6094 if (*p == '{' || *p == '[' || *p == '(') {
6095 p[strlen(p) - 1] = NULLCHAR;
6098 while (*p == '\n') p++;
6099 AppendComment(currentMove, p);
6100 yyboardindex = forwardMostMove;
6101 cm = (ChessMove) yylex();
6105 /* don't rely on existence of Event tag since if game was
6106 * pasted from clipboard the Event tag may not exist
6108 if (numPGNTags > 0){
6110 if (gameInfo.variant == VariantNormal) {
6111 gameInfo.variant = StringToVariant(gameInfo.event);
6114 tags = PGNTags(&gameInfo);
6115 TagsPopUp(tags, CmailMsg());
6119 /* Make something up, but don't display it now */
6124 if (cm == PositionDiagram) {
6127 Board initial_position;
6129 if (appData.debugMode)
6130 fprintf(debugFP, "Parsed PositionDiagram: %s\n", yy_text);
6132 if (!startedFromSetupPosition) {
6134 for (i = BOARD_SIZE - 1; i >= 0; i--)
6135 for (j = 0; j < BOARD_SIZE; p++)
6145 initial_position[i][j++] = CharToPiece(*p);
6148 while (*p == ' ' || *p == '\t' ||
6149 *p == '\n' || *p == '\r') p++;
6151 if (strncmp(p, "black", strlen("black"))==0)
6152 blackPlaysFirst = TRUE;
6154 blackPlaysFirst = FALSE;
6155 startedFromSetupPosition = TRUE;
6157 CopyBoard(boards[0], initial_position);
6158 if (blackPlaysFirst) {
6159 currentMove = forwardMostMove = backwardMostMove = 1;
6160 CopyBoard(boards[1], initial_position);
6161 strcpy(moveList[0], "");
6162 strcpy(parseList[0], "");
6163 timeRemaining[0][1] = whiteTimeRemaining;
6164 timeRemaining[1][1] = blackTimeRemaining;
6165 if (commentList[0] != NULL) {
6166 commentList[1] = commentList[0];
6167 commentList[0] = NULL;
6170 currentMove = forwardMostMove = backwardMostMove = 0;
6173 yyboardindex = forwardMostMove;
6174 cm = (ChessMove) yylex();
6177 if (first.pr == NoProc) {
6178 StartChessProgram(&first);
6180 InitChessProgram(&first);
6181 SendToProgram("force\n", &first);
6182 if (startedFromSetupPosition) {
6183 SendBoard(&first, forwardMostMove);
6184 DisplayBothClocks();
6187 while (cm == Comment) {
6189 if (appData.debugMode)
6190 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
6192 if (*p == '{' || *p == '[' || *p == '(') {
6193 p[strlen(p) - 1] = NULLCHAR;
6196 while (*p == '\n') p++;
6197 AppendComment(currentMove, p);
6198 yyboardindex = forwardMostMove;
6199 cm = (ChessMove) yylex();
6202 if ((cm == (ChessMove) 0 && lastLoadGameStart != (ChessMove) 0) ||
6203 cm == WhiteWins || cm == BlackWins ||
6204 cm == GameIsDrawn || cm == GameUnfinished) {
6205 DisplayMessage("", "No moves in game");
6206 if (cmailMsgLoaded) {
6207 if (appData.debugMode)
6208 fprintf(debugFP, "Setting flipView to %d.\n", FALSE);
6212 DrawPosition(FALSE, boards[currentMove]);
6213 DisplayBothClocks();
6214 gameMode = EditGame;
6221 if (commentList[currentMove] != NULL) {
6222 if (!matchMode && (pausing || appData.timeDelay != 0)) {
6223 DisplayComment(currentMove - 1, commentList[currentMove]);
6226 if (!matchMode && appData.timeDelay != 0)
6227 DrawPosition(FALSE, boards[currentMove]);
6229 if (gameMode == AnalyzeFile || gameMode == AnalyzeMode) {
6230 programStats.ok_to_send = 1;
6233 /* if the first token after the PGN tags is a move
6234 * and not move number 1, retrieve it from the parser
6236 if (cm != MoveNumberOne)
6237 LoadGameOneMove(cm);
6239 /* load the remaining moves from the file */
6240 while (LoadGameOneMove((ChessMove)0)) {
6241 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
6242 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
6245 /* rewind to the start of the game */
6246 currentMove = backwardMostMove;
6248 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
6250 if (oldGameMode == AnalyzeFile ||
6251 oldGameMode == AnalyzeMode) {
6255 if (matchMode || appData.timeDelay == 0) {
6257 gameMode = EditGame;
6259 } else if (appData.timeDelay > 0) {
6263 if (appData.debugMode)
6264 fprintf(debugFP, "LoadGame(): on exit, gameMode %d\n", gameMode);
6268 /* Support for LoadNextPosition, LoadPreviousPosition, ReloadSamePosition */
6270 ReloadPosition(offset)
6273 int positionNumber = lastLoadPositionNumber + offset;
6274 if (lastLoadPositionFP == NULL) {
6275 DisplayError("No position has been loaded yet", 0);
6278 if (positionNumber <= 0) {
6279 DisplayError("Can't back up any further", 0);
6282 return LoadPosition(lastLoadPositionFP, positionNumber,
6283 lastLoadPositionTitle);
6286 /* Load the nth position from the given file */
6288 LoadPositionFromFile(filename, n, title)
6296 if (strcmp(filename, "-") == 0) {
6297 return LoadPosition(stdin, n, "stdin");
6299 f = fopen(filename, "rb");
6301 sprintf(buf, "Can't open \"%s\"", filename);
6302 DisplayError(buf, errno);
6305 return LoadPosition(f, n, title);
6310 /* Load the nth position from the given open file, and close it */
6312 LoadPosition(f, positionNumber, title)
6317 char *p, line[MSG_SIZ];
6318 Board initial_position;
6319 int i, j, fenMode, pn;
6321 if (gameMode == Training )
6322 SetTrainingModeOff();
6324 if (gameMode != BeginningOfGame) {
6327 if (lastLoadPositionFP != NULL && lastLoadPositionFP != f) {
6328 fclose(lastLoadPositionFP);
6330 if (positionNumber == 0) positionNumber = 1;
6331 lastLoadPositionFP = f;
6332 lastLoadPositionNumber = positionNumber;
6333 strcpy(lastLoadPositionTitle, title);
6334 if (first.pr == NoProc) {
6335 StartChessProgram(&first);
6336 InitChessProgram(&first);
6338 pn = positionNumber;
6339 if (positionNumber < 0) {
6340 /* Negative position number means to seek to that byte offset */
6341 if (fseek(f, -positionNumber, 0) == -1) {
6342 DisplayError("Can't seek on position file", 0);
6347 if (fseek(f, 0, 0) == -1) {
6348 if (f == lastLoadPositionFP ?
6349 positionNumber == lastLoadPositionNumber + 1 :
6350 positionNumber == 1) {
6353 DisplayError("Can't seek on position file", 0);
6358 /* See if this file is FEN or old-style xboard */
6359 if (fgets(line, MSG_SIZ, f) == NULL) {
6360 DisplayError("Position not found in file", 0);
6368 case 'p': case 'n': case 'b': case 'r': case 'q': case 'k':
6369 case 'P': case 'N': case 'B': case 'R': case 'Q': case 'K':
6370 case '1': case '2': case '3': case '4': case '5': case '6':
6377 if (fenMode || line[0] == '#') pn--;
6379 /* skip postions before number pn */
6380 if (fgets(line, MSG_SIZ, f) == NULL) {
6382 DisplayError("Position not found in file", 0);
6385 if (fenMode || line[0] == '#') pn--;
6390 if (!ParseFEN(initial_position, &blackPlaysFirst, line)) {
6391 DisplayError("Bad FEN position in file", 0);
6395 (void) fgets(line, MSG_SIZ, f);
6396 (void) fgets(line, MSG_SIZ, f);
6398 for (i = BOARD_SIZE - 1; i >= 0; i--) {
6399 (void) fgets(line, MSG_SIZ, f);
6400 for (p = line, j = 0; j < BOARD_SIZE; p++) {
6403 initial_position[i][j++] = CharToPiece(*p);
6407 blackPlaysFirst = FALSE;
6409 (void) fgets(line, MSG_SIZ, f);
6410 if (strncmp(line, "black", strlen("black"))==0)
6411 blackPlaysFirst = TRUE;
6414 startedFromSetupPosition = TRUE;
6416 SendToProgram("force\n", &first);
6417 CopyBoard(boards[0], initial_position);
6418 if (blackPlaysFirst) {
6419 currentMove = forwardMostMove = backwardMostMove = 1;
6420 strcpy(moveList[0], "");
6421 strcpy(parseList[0], "");
6422 CopyBoard(boards[1], initial_position);
6423 DisplayMessage("", "Black to play");
6425 currentMove = forwardMostMove = backwardMostMove = 0;
6426 DisplayMessage("", "White to play");
6428 SendBoard(&first, forwardMostMove);
6430 if (positionNumber > 1) {
6431 sprintf(line, "%s %d", title, positionNumber);
6434 DisplayTitle(title);
6436 gameMode = EditGame;
6439 timeRemaining[0][1] = whiteTimeRemaining;
6440 timeRemaining[1][1] = blackTimeRemaining;
6441 DrawPosition(FALSE, boards[currentMove]);
6448 CopyPlayerNameIntoFileName(dest, src)
6451 while (*src != NULLCHAR && *src != ',') {
6456 *(*dest)++ = *src++;
6461 char *DefaultFileName(ext)
6464 static char def[MSG_SIZ];
6467 if (gameInfo.white != NULL && gameInfo.white[0] != '-') {
6469 CopyPlayerNameIntoFileName(&p, gameInfo.white);
6471 CopyPlayerNameIntoFileName(&p, gameInfo.black);
6480 /* Save the current game to the given file */
6482 SaveGameToFile(filename, append)
6489 if (strcmp(filename, "-") == 0) {
6490 return SaveGame(stdout, 0, NULL);
6492 f = fopen(filename, append ? "a" : "w");
6494 sprintf(buf, "Can't open \"%s\"", filename);
6495 DisplayError(buf, errno);
6498 return SaveGame(f, 0, NULL);
6507 static char buf[MSG_SIZ];
6510 p = strchr(str, ' ');
6511 if (p == NULL) return str;
6512 strncpy(buf, str, p - str);
6513 buf[p - str] = NULLCHAR;
6517 #define PGN_MAX_LINE 75
6519 /* Save game in PGN style and close the file */
6524 int i, offset, linelen, newblock;
6528 int movelen, numlen, blank;
6530 tm = time((time_t *) NULL);
6532 PrintPGNTags(f, &gameInfo);
6534 if (backwardMostMove > 0 || startedFromSetupPosition) {
6535 char *fen = PositionToFEN(backwardMostMove);
6536 fprintf(f, "[FEN \"%s\"]\n[SetUp \"1\"]\n", fen);
6537 fprintf(f, "\n{--------------\n");
6538 PrintPosition(f, backwardMostMove);
6539 fprintf(f, "--------------}\n");
6545 i = backwardMostMove;
6546 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
6550 while (i < forwardMostMove) {
6551 /* Print comments preceding this move */
6552 if (commentList[i] != NULL) {
6553 if (linelen > 0) fprintf(f, "\n");
6554 fprintf(f, "{\n%s}\n", commentList[i]);
6559 /* Format move number */
6561 sprintf(numtext, "%d.", (i - offset)/2 + 1);
6564 sprintf(numtext, "%d...", (i - offset)/2 + 1);
6566 numtext[0] = NULLCHAR;
6569 numlen = strlen(numtext);
6572 /* Print move number */
6573 blank = linelen > 0 && numlen > 0;
6574 if (linelen + (blank ? 1 : 0) + numlen > PGN_MAX_LINE) {
6583 fprintf(f, numtext);
6587 movetext = SavePart(parseList[i]);
6588 movelen = strlen(movetext);
6591 blank = linelen > 0 && movelen > 0;
6592 if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
6601 fprintf(f, movetext);
6607 /* Start a new line */
6608 if (linelen > 0) fprintf(f, "\n");
6610 /* Print comments after last move */
6611 if (commentList[i] != NULL) {
6612 fprintf(f, "{\n%s}\n", commentList[i]);
6616 if (gameInfo.resultDetails != NULL &&
6617 gameInfo.resultDetails[0] != NULLCHAR) {
6618 fprintf(f, "{%s} %s\n\n", gameInfo.resultDetails,
6619 PGNResult(gameInfo.result));
6621 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
6628 /* Save game in old style and close the file */
6636 tm = time((time_t *) NULL);
6638 fprintf(f, "# %s game file -- %s", programName, ctime(&tm));
6641 if (backwardMostMove > 0 || startedFromSetupPosition) {
6642 fprintf(f, "\n[--------------\n");
6643 PrintPosition(f, backwardMostMove);
6644 fprintf(f, "--------------]\n");
6649 i = backwardMostMove;
6650 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
6652 while (i < forwardMostMove) {
6653 if (commentList[i] != NULL) {
6654 fprintf(f, "[%s]\n", commentList[i]);
6658 fprintf(f, "%d. ... %s\n", (i - offset)/2 + 1, parseList[i]);
6661 fprintf(f, "%d. %s ", (i - offset)/2 + 1, parseList[i]);
6663 if (commentList[i] != NULL) {
6667 if (i >= forwardMostMove) {
6671 fprintf(f, "%s\n", parseList[i]);
6676 if (commentList[i] != NULL) {
6677 fprintf(f, "[%s]\n", commentList[i]);
6680 /* This isn't really the old style, but it's close enough */
6681 if (gameInfo.resultDetails != NULL &&
6682 gameInfo.resultDetails[0] != NULLCHAR) {
6683 fprintf(f, "%s (%s)\n\n", PGNResult(gameInfo.result),
6684 gameInfo.resultDetails);
6686 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
6693 /* Save the current game to open file f and close the file */
6695 SaveGame(f, dummy, dummy2)
6700 if (gameMode == EditPosition) EditPositionDone();
6701 if (appData.oldSaveStyle)
6702 return SaveGameOldStyle(f);
6704 return SaveGamePGN(f);
6707 /* Save the current position to the given file */
6709 SavePositionToFile(filename)
6715 if (strcmp(filename, "-") == 0) {
6716 return SavePosition(stdout, 0, NULL);
6718 f = fopen(filename, "a");
6720 sprintf(buf, "Can't open \"%s\"", filename);
6721 DisplayError(buf, errno);
6724 SavePosition(f, 0, NULL);
6730 /* Save the current position to the given open file and close the file */
6732 SavePosition(f, dummy, dummy2)
6740 if (appData.oldSaveStyle) {
6741 tm = time((time_t *) NULL);
6743 fprintf(f, "# %s position file -- %s", programName, ctime(&tm));
6745 fprintf(f, "[--------------\n");
6746 PrintPosition(f, currentMove);
6747 fprintf(f, "--------------]\n");
6749 fen = PositionToFEN(currentMove);
6750 fprintf(f, "%s\n", fen);
6758 ReloadCmailMsgEvent(unregister)
6762 static char *inFilename = NULL;
6763 static char *outFilename;
6765 struct stat inbuf, outbuf;
6768 /* Any registered moves are unregistered if unregister is set, */
6769 /* i.e. invoked by the signal handler */
6771 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
6772 cmailMoveRegistered[i] = FALSE;
6773 if (cmailCommentList[i] != NULL) {
6774 free(cmailCommentList[i]);
6775 cmailCommentList[i] = NULL;
6778 nCmailMovesRegistered = 0;
6781 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
6782 cmailResult[i] = CMAIL_NOT_RESULT;
6786 if (inFilename == NULL) {
6787 /* Because the filenames are static they only get malloced once */
6788 /* and they never get freed */
6789 inFilename = (char *) malloc(strlen(appData.cmailGameName) + 9);
6790 sprintf(inFilename, "%s.game.in", appData.cmailGameName);
6792 outFilename = (char *) malloc(strlen(appData.cmailGameName) + 5);
6793 sprintf(outFilename, "%s.out", appData.cmailGameName);
6796 status = stat(outFilename, &outbuf);
6798 cmailMailedMove = FALSE;
6800 status = stat(inFilename, &inbuf);
6801 cmailMailedMove = (inbuf.st_mtime < outbuf.st_mtime);
6804 /* LoadGameFromFile(CMAIL_MAX_GAMES) with cmailMsgLoaded == TRUE
6805 counts the games, notes how each one terminated, etc.
6807 It would be nice to remove this kludge and instead gather all
6808 the information while building the game list. (And to keep it
6809 in the game list nodes instead of having a bunch of fixed-size
6810 parallel arrays.) Note this will require getting each game's
6811 termination from the PGN tags, as the game list builder does
6812 not process the game moves. --mann
6814 cmailMsgLoaded = TRUE;
6815 LoadGameFromFile(inFilename, CMAIL_MAX_GAMES, "", FALSE);
6817 /* Load first game in the file or popup game menu */
6818 LoadGameFromFile(inFilename, 0, appData.cmailGameName, TRUE);
6828 char string[MSG_SIZ];
6830 if ( cmailMailedMove
6831 || (cmailResult[lastLoadGameNumber - 1] == CMAIL_OLD_RESULT)) {
6832 return TRUE; /* Allow free viewing */
6835 /* Unregister move to ensure that we don't leave RegisterMove */
6836 /* with the move registered when the conditions for registering no */
6838 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
6839 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
6840 nCmailMovesRegistered --;
6842 if (cmailCommentList[lastLoadGameNumber - 1] != NULL)
6844 free(cmailCommentList[lastLoadGameNumber - 1]);
6845 cmailCommentList[lastLoadGameNumber - 1] = NULL;
6849 if (cmailOldMove == -1) {
6850 DisplayError("You have edited the game history.\nUse Reload Same Game and make your move again.", 0);
6854 if (currentMove > cmailOldMove + 1) {
6855 DisplayError("You have entered too many moves.\nBack up to the correct position and try again.", 0);
6859 if (currentMove < cmailOldMove) {
6860 DisplayError("Displayed position is not current.\nStep forward to the correct position and try again.", 0);
6864 if (forwardMostMove > currentMove) {
6865 /* Silently truncate extra moves */
6869 if ( (currentMove == cmailOldMove + 1)
6870 || ( (currentMove == cmailOldMove)
6871 && ( (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_ACCEPT)
6872 || (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_RESIGN)))) {
6873 if (gameInfo.result != GameUnfinished) {
6874 cmailResult[lastLoadGameNumber - 1] = CMAIL_NEW_RESULT;
6877 if (commentList[currentMove] != NULL) {
6878 cmailCommentList[lastLoadGameNumber - 1]
6879 = StrSave(commentList[currentMove]);
6881 strcpy(cmailMove[lastLoadGameNumber - 1], moveList[currentMove - 1]);
6883 if (appData.debugMode)
6884 fprintf(debugFP, "Saving %s for game %d\n",
6885 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
6888 "%s.game.out.%d", appData.cmailGameName, lastLoadGameNumber);
6890 f = fopen(string, "w");
6891 if (appData.oldSaveStyle) {
6892 SaveGameOldStyle(f); /* also closes the file */
6894 sprintf(string, "%s.pos.out", appData.cmailGameName);
6895 f = fopen(string, "w");
6896 SavePosition(f, 0, NULL); /* also closes the file */
6898 fprintf(f, "{--------------\n");
6899 PrintPosition(f, currentMove);
6900 fprintf(f, "--------------}\n\n");
6902 SaveGame(f, 0, NULL); /* also closes the file*/
6905 cmailMoveRegistered[lastLoadGameNumber - 1] = TRUE;
6906 nCmailMovesRegistered ++;
6907 } else if (nCmailGames == 1) {
6908 DisplayError("You have not made a move yet", 0);
6919 static char *partCommandString = "cmail -xv%s -remail -game %s 2>&1";
6920 FILE *commandOutput;
6921 char buffer[MSG_SIZ], msg[MSG_SIZ], string[MSG_SIZ];
6922 int nBytes = 0; /* Suppress warnings on uninitialized variables */
6928 if (! cmailMsgLoaded) {
6929 DisplayError("The cmail message is not loaded.\nUse Reload CMail Message and make your move again.", 0);
6933 if (nCmailGames == nCmailResults) {
6934 DisplayError("No unfinished games", 0);
6938 #if CMAIL_PROHIBIT_REMAIL
6939 if (cmailMailedMove) {
6940 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);
6941 DisplayError(msg, 0);
6946 if (! (cmailMailedMove || RegisterMove())) return;
6948 if ( cmailMailedMove
6949 || (nCmailMovesRegistered + nCmailResults == nCmailGames)) {
6950 sprintf(string, partCommandString,
6951 appData.debugMode ? " -v" : "", appData.cmailGameName);
6952 commandOutput = popen(string, "rb");
6954 if (commandOutput == NULL) {
6955 DisplayError("Failed to invoke cmail", 0);
6957 for (nBuffers = 0; (! feof(commandOutput)); nBuffers ++) {
6958 nBytes = fread(buffer, 1, MSG_SIZ - 1, commandOutput);
6961 (void) memcpy(msg, buffer + nBytes, MSG_SIZ - nBytes - 1);
6962 (void) memcpy(msg + MSG_SIZ - nBytes - 1, buffer, nBytes);
6963 nBytes = MSG_SIZ - 1;
6965 (void) memcpy(msg, buffer, nBytes);
6967 *(msg + nBytes) = '\0'; /* \0 for end-of-string*/
6969 if(StrStr(msg, "Mailed cmail message to ") != NULL) {
6970 cmailMailedMove = TRUE; /* Prevent >1 moves */
6973 for (i = 0; i < nCmailGames; i ++) {
6974 if (cmailResult[i] == CMAIL_NOT_RESULT) {
6979 && ( (arcDir = (char *) getenv("CMAIL_ARCDIR"))
6981 sprintf(buffer, "%s/%s.%s.archive",
6983 appData.cmailGameName,
6985 LoadGameFromFile(buffer, 1, buffer, FALSE);
6986 cmailMsgLoaded = FALSE;
6990 DisplayInformation(msg);
6991 pclose(commandOutput);
6994 if ((*cmailMsg) != '\0') {
6995 DisplayInformation(cmailMsg);
7009 int prependComma = 0;
7011 char string[MSG_SIZ]; /* Space for game-list */
7014 if (!cmailMsgLoaded) return "";
7016 if (cmailMailedMove) {
7017 sprintf(cmailMsg, "Waiting for reply from opponent\n");
7019 /* Create a list of games left */
7020 sprintf(string, "[");
7021 for (i = 0; i < nCmailGames; i ++) {
7022 if (! ( cmailMoveRegistered[i]
7023 || (cmailResult[i] == CMAIL_OLD_RESULT))) {
7025 sprintf(number, ",%d", i + 1);
7027 sprintf(number, "%d", i + 1);
7031 strcat(string, number);
7034 strcat(string, "]");
7036 if (nCmailMovesRegistered + nCmailResults == 0) {
7037 switch (nCmailGames) {
7040 "Still need to make move for game\n");
7045 "Still need to make moves for both games\n");
7050 "Still need to make moves for all %d games\n",
7055 switch (nCmailGames - nCmailMovesRegistered - nCmailResults) {
7058 "Still need to make a move for game %s\n",
7063 if (nCmailResults == nCmailGames) {
7064 sprintf(cmailMsg, "No unfinished games\n");
7066 sprintf(cmailMsg, "Ready to send mail\n");
7072 "Still need to make moves for games %s\n",
7084 if (gameMode == Training)
7085 SetTrainingModeOff();
7088 cmailMsgLoaded = FALSE;
7089 if (appData.icsActive) {
7090 SendToICS(ics_prefix);
7091 SendToICS("refresh\n");
7095 static int exiting = 0;
7103 /* Give up on clean exit */
7107 /* Keep trying for clean exit */
7111 if (appData.icsActive && appData.colorize) Colorize(ColorNone, FALSE);
7113 if (telnetISR != NULL) {
7114 RemoveInputSource(telnetISR);
7116 if (icsPR != NoProc) {
7117 DestroyChildProcess(icsPR, TRUE);
7119 /* Save game if resource set and not already saved by GameEnds() */
7120 if (gameInfo.resultDetails == NULL && forwardMostMove > 0) {
7121 if (*appData.saveGameFile != NULLCHAR) {
7122 SaveGameToFile(appData.saveGameFile, TRUE);
7123 } else if (appData.autoSaveGames) {
7126 if (*appData.savePositionFile != NULLCHAR) {
7127 SavePositionToFile(appData.savePositionFile);
7130 GameEnds((ChessMove) 0, NULL, GE_PLAYER);
7132 /* Kill off chess programs */
7133 if (first.pr != NoProc) {
7135 SendToProgram("quit\n", &first);
7136 DestroyChildProcess(first.pr, first.useSigterm);
7138 if (second.pr != NoProc) {
7139 SendToProgram("quit\n", &second);
7140 DestroyChildProcess(second.pr, second.useSigterm);
7142 if (first.isr != NULL) {
7143 RemoveInputSource(first.isr);
7145 if (second.isr != NULL) {
7146 RemoveInputSource(second.isr);
7156 if (appData.debugMode)
7157 fprintf(debugFP, "PauseEvent(): pausing %d\n", pausing);
7161 if (gameMode == MachinePlaysWhite ||
7162 gameMode == MachinePlaysBlack) {
7165 DisplayBothClocks();
7167 if (gameMode == PlayFromGameFile) {
7168 if (appData.timeDelay >= 0)
7170 } else if (gameMode == IcsExamining && pauseExamInvalid) {
7172 SendToICS(ics_prefix);
7173 SendToICS("refresh\n");
7174 } else if (currentMove < forwardMostMove) {
7175 ForwardInner(forwardMostMove);
7177 pauseExamInvalid = FALSE;
7183 pauseExamForwardMostMove = forwardMostMove;
7184 pauseExamInvalid = FALSE;
7187 case IcsPlayingWhite:
7188 case IcsPlayingBlack:
7192 case PlayFromGameFile:
7193 (void) StopLoadGameTimer();
7197 case BeginningOfGame:
7198 if (appData.icsActive) return;
7199 /* else fall through */
7200 case MachinePlaysWhite:
7201 case MachinePlaysBlack:
7202 case TwoMachinesPlay:
7203 if (forwardMostMove == 0)
7204 return; /* don't pause if no one has moved */
7205 if ((gameMode == MachinePlaysWhite &&
7206 !WhiteOnMove(forwardMostMove)) ||
7207 (gameMode == MachinePlaysBlack &&
7208 WhiteOnMove(forwardMostMove))) {
7221 char title[MSG_SIZ];
7223 if (currentMove < 1 || parseList[currentMove - 1][0] == NULLCHAR) {
7224 strcpy(title, "Edit comment");
7226 sprintf(title, "Edit comment on %d.%s%s", (currentMove - 1) / 2 + 1,
7227 WhiteOnMove(currentMove - 1) ? " " : ".. ",
7228 parseList[currentMove - 1]);
7231 EditCommentPopUp(currentMove, title, commentList[currentMove]);
7238 char *tags = PGNTags(&gameInfo);
7239 EditTagsPopUp(tags);
7246 if (appData.noChessProgram || gameMode == AnalyzeMode)
7249 if (gameMode != AnalyzeFile) {
7251 if (gameMode != EditGame) return;
7252 ResurrectChessProgram();
7253 SendToProgram("analyze\n", &first);
7254 first.analyzing = TRUE;
7255 /*first.maybeThinking = TRUE;*/
7256 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
7257 AnalysisPopUp("Analysis",
7258 "Starting analysis mode...\nIf this message stays up, your chess program does not support analysis.");
7260 gameMode = AnalyzeMode;
7265 StartAnalysisClock();
7266 GetTimeMark(&lastNodeCountTime);
7273 if (appData.noChessProgram || gameMode == AnalyzeFile)
7276 if (gameMode != AnalyzeMode) {
7278 if (gameMode != EditGame) return;
7279 ResurrectChessProgram();
7280 SendToProgram("analyze\n", &first);
7281 first.analyzing = TRUE;
7282 /*first.maybeThinking = TRUE;*/
7283 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
7284 AnalysisPopUp("Analysis",
7285 "Starting analysis mode...\nIf this message stays up, your chess program does not support analysis.");
7287 gameMode = AnalyzeFile;
7292 StartAnalysisClock();
7293 GetTimeMark(&lastNodeCountTime);
7302 if (appData.noChessProgram || (gameMode == MachinePlaysWhite))
7306 if (gameMode == PlayFromGameFile ||
7307 gameMode == TwoMachinesPlay ||
7308 gameMode == Training ||
7309 gameMode == AnalyzeMode ||
7310 gameMode == EndOfGame)
7313 if (gameMode == EditPosition)
7316 if (!WhiteOnMove(currentMove)) {
7317 DisplayError("It is not White's turn", 0);
7321 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
7324 if (gameMode == EditGame || gameMode == AnalyzeMode ||
7325 gameMode == AnalyzeFile)
7328 ResurrectChessProgram(); /* in case it isn't running */
7329 gameMode = MachinePlaysWhite;
7333 sprintf(buf, "%s vs. %s", gameInfo.white, gameInfo.black);
7335 if (first.sendName) {
7336 sprintf(buf, "name %s\n", gameInfo.black);
7337 SendToProgram(buf, &first);
7339 if (first.sendTime) {
7340 if (first.useColors) {
7341 SendToProgram("black\n", &first); /*gnu kludge*/
7343 SendTimeRemaining(&first, TRUE);
7345 if (first.useColors) {
7346 SendToProgram("white\ngo\n", &first);
7348 SendToProgram("go\n", &first);
7350 SetMachineThinkingEnables();
7351 first.maybeThinking = TRUE;
7354 if (appData.autoFlipView && !flipView) {
7355 flipView = !flipView;
7356 DrawPosition(FALSE, NULL);
7365 if (appData.noChessProgram || (gameMode == MachinePlaysBlack))
7369 if (gameMode == PlayFromGameFile ||
7370 gameMode == TwoMachinesPlay ||
7371 gameMode == Training ||
7372 gameMode == AnalyzeMode ||
7373 gameMode == EndOfGame)
7376 if (gameMode == EditPosition)
7379 if (WhiteOnMove(currentMove)) {
7380 DisplayError("It is not Black's turn", 0);
7384 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
7387 if (gameMode == EditGame || gameMode == AnalyzeMode ||
7388 gameMode == AnalyzeFile)
7391 ResurrectChessProgram(); /* in case it isn't running */
7392 gameMode = MachinePlaysBlack;
7396 sprintf(buf, "%s vs. %s", gameInfo.white, gameInfo.black);
7398 if (first.sendName) {
7399 sprintf(buf, "name %s\n", gameInfo.white);
7400 SendToProgram(buf, &first);
7402 if (first.sendTime) {
7403 if (first.useColors) {
7404 SendToProgram("white\n", &first); /*gnu kludge*/
7406 SendTimeRemaining(&first, FALSE);
7408 if (first.useColors) {
7409 SendToProgram("black\ngo\n", &first);
7411 SendToProgram("go\n", &first);
7413 SetMachineThinkingEnables();
7414 first.maybeThinking = TRUE;
7417 if (appData.autoFlipView && flipView) {
7418 flipView = !flipView;
7419 DrawPosition(FALSE, NULL);
7425 DisplayTwoMachinesTitle()
7428 if (appData.matchGames > 0) {
7429 if (first.twoMachinesColor[0] == 'w') {
7430 sprintf(buf, "%s vs. %s (%d-%d-%d)",
7431 gameInfo.white, gameInfo.black,
7432 first.matchWins, second.matchWins,
7433 matchGame - 1 - (first.matchWins + second.matchWins));
7435 sprintf(buf, "%s vs. %s (%d-%d-%d)",
7436 gameInfo.white, gameInfo.black,
7437 second.matchWins, first.matchWins,
7438 matchGame - 1 - (first.matchWins + second.matchWins));
7441 sprintf(buf, "%s vs. %s", gameInfo.white, gameInfo.black);
7447 TwoMachinesEvent P((void))
7451 ChessProgramState *onmove;
7453 if (appData.noChessProgram) return;
7456 case TwoMachinesPlay:
7458 case MachinePlaysWhite:
7459 case MachinePlaysBlack:
7460 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
7461 DisplayError("Wait until your turn,\nor select Move Now", 0);
7465 case BeginningOfGame:
7466 case PlayFromGameFile:
7469 if (gameMode != EditGame) return;
7483 forwardMostMove = currentMove;
7484 ResurrectChessProgram(); /* in case first program isn't running */
7486 if (second.pr == NULL) {
7487 StartChessProgram(&second);
7488 if (second.protocolVersion == 1) {
7489 TwoMachinesEventIfReady();
7491 /* kludge: allow timeout for initial "feature" command */
7493 DisplayMessage("", "Starting second chess program");
7494 ScheduleDelayedEvent(TwoMachinesEventIfReady, FEATURE_TIMEOUT);
7498 DisplayMessage("", "");
7499 InitChessProgram(&second);
7500 SendToProgram("force\n", &second);
7501 if (startedFromSetupPosition) {
7502 SendBoard(&second, backwardMostMove);
7504 for (i = backwardMostMove; i < forwardMostMove; i++) {
7505 SendMoveToProgram(i, &second);
7508 gameMode = TwoMachinesPlay;
7512 DisplayTwoMachinesTitle();
7514 if ((first.twoMachinesColor[0] == 'w') == WhiteOnMove(forwardMostMove)) {
7520 SendToProgram(first.computerString, &first);
7521 if (first.sendName) {
7522 sprintf(buf, "name %s\n", second.tidy);
7523 SendToProgram(buf, &first);
7525 SendToProgram(second.computerString, &second);
7526 if (second.sendName) {
7527 sprintf(buf, "name %s\n", first.tidy);
7528 SendToProgram(buf, &second);
7531 if (!first.sendTime || !second.sendTime) {
7533 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
7534 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
7536 if (onmove->sendTime) {
7537 if (onmove->useColors) {
7538 SendToProgram(onmove->other->twoMachinesColor, onmove); /*gnu kludge*/
7540 SendTimeRemaining(onmove, WhiteOnMove(forwardMostMove));
7542 if (onmove->useColors) {
7543 SendToProgram(onmove->twoMachinesColor, onmove);
7545 SendToProgram("go\n", onmove);
7546 onmove->maybeThinking = TRUE;
7547 SetMachineThinkingEnables();
7555 if (gameMode == Training) {
7556 SetTrainingModeOff();
7557 gameMode = PlayFromGameFile;
7558 DisplayMessage("", "Training mode off");
7560 gameMode = Training;
7561 animateTraining = appData.animate;
7563 /* make sure we are not already at the end of the game */
7564 if (currentMove < forwardMostMove) {
7565 SetTrainingModeOn();
7566 DisplayMessage("", "Training mode on");
7568 gameMode = PlayFromGameFile;
7569 DisplayError("Already at end of game", 0);
7578 if (!appData.icsActive) return;
7580 case IcsPlayingWhite:
7581 case IcsPlayingBlack:
7584 case BeginningOfGame:
7618 SetTrainingModeOff();
7620 case MachinePlaysWhite:
7621 case MachinePlaysBlack:
7622 case BeginningOfGame:
7623 SendToProgram("force\n", &first);
7624 SetUserThinkingEnables();
7626 case PlayFromGameFile:
7627 (void) StopLoadGameTimer();
7628 if (gameFileFP != NULL) {
7638 SendToProgram("force\n", &first);
7640 case TwoMachinesPlay:
7641 GameEnds((ChessMove) 0, NULL, GE_PLAYER);
7642 ResurrectChessProgram();
7643 SetUserThinkingEnables();
7646 ResurrectChessProgram();
7648 case IcsPlayingBlack:
7649 case IcsPlayingWhite:
7650 DisplayError("Warning: You are still playing a game", 0);
7653 DisplayError("Warning: You are still observing a game", 0);
7656 DisplayError("Warning: You are still examining a game", 0);
7667 first.offeredDraw = second.offeredDraw = 0;
7669 if (gameMode == PlayFromGameFile) {
7670 whiteTimeRemaining = timeRemaining[0][currentMove];
7671 blackTimeRemaining = timeRemaining[1][currentMove];
7675 if (gameMode == MachinePlaysWhite ||
7676 gameMode == MachinePlaysBlack ||
7677 gameMode == TwoMachinesPlay ||
7678 gameMode == EndOfGame) {
7679 i = forwardMostMove;
7680 while (i > currentMove) {
7681 SendToProgram("undo\n", &first);
7684 whiteTimeRemaining = timeRemaining[0][currentMove];
7685 blackTimeRemaining = timeRemaining[1][currentMove];
7686 DisplayBothClocks();
7687 if (whiteFlag || blackFlag) {
7688 whiteFlag = blackFlag = 0;
7693 gameMode = EditGame;
7702 if (gameMode == EditPosition) {
7708 if (gameMode != EditGame) return;
7710 gameMode = EditPosition;
7713 if (currentMove > 0)
7714 CopyBoard(boards[0], boards[currentMove]);
7716 blackPlaysFirst = !WhiteOnMove(currentMove);
7718 currentMove = forwardMostMove = backwardMostMove = 0;
7719 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
7726 if (first.analysisSupport && first.analyzing) {
7727 SendToProgram("exit\n", &first);
7728 first.analyzing = FALSE;
7731 thinkOutput[0] = NULLCHAR;
7737 startedFromSetupPosition = TRUE;
7738 InitChessProgram(&first);
7739 SendToProgram("force\n", &first);
7740 if (blackPlaysFirst) {
7741 strcpy(moveList[0], "");
7742 strcpy(parseList[0], "");
7743 currentMove = forwardMostMove = backwardMostMove = 1;
7744 CopyBoard(boards[1], boards[0]);
7746 currentMove = forwardMostMove = backwardMostMove = 0;
7748 SendBoard(&first, forwardMostMove);
7750 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
7751 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
7752 gameMode = EditGame;
7754 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
7757 /* Pause for `ms' milliseconds */
7758 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
7768 } while (SubtractTimeMarks(&m2, &m1) < ms);
7771 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
7773 SendMultiLineToICS(buf)
7776 char temp[MSG_SIZ+1], *p;
7783 strncpy(temp, buf, len);
7788 if (*p == '\n' || *p == '\r')
7795 SendToPlayer(temp, strlen(temp));
7799 SetWhiteToPlayEvent()
7801 if (gameMode == EditPosition) {
7802 blackPlaysFirst = FALSE;
7803 DisplayBothClocks(); /* works because currentMove is 0 */
7804 } else if (gameMode == IcsExamining) {
7805 SendToICS(ics_prefix);
7806 SendToICS("tomove white\n");
7811 SetBlackToPlayEvent()
7813 if (gameMode == EditPosition) {
7814 blackPlaysFirst = TRUE;
7815 currentMove = 1; /* kludge */
7816 DisplayBothClocks();
7818 } else if (gameMode == IcsExamining) {
7819 SendToICS(ics_prefix);
7820 SendToICS("tomove black\n");
7825 EditPositionMenuEvent(selection, x, y)
7826 ChessSquare selection;
7831 if (gameMode != EditPosition && gameMode != IcsExamining) return;
7833 switch (selection) {
7835 if (gameMode == IcsExamining && ics_type == ICS_FICS) {
7836 SendToICS(ics_prefix);
7837 SendToICS("bsetup clear\n");
7838 } else if (gameMode == IcsExamining && ics_type == ICS_ICC) {
7839 SendToICS(ics_prefix);
7840 SendToICS("clearboard\n");
7842 for (x = 0; x < BOARD_SIZE; x++) {
7843 for (y = 0; y < BOARD_SIZE; y++) {
7844 if (gameMode == IcsExamining) {
7845 if (boards[currentMove][y][x] != EmptySquare) {
7846 sprintf(buf, "%sx@%c%c\n", ics_prefix,
7851 boards[0][y][x] = EmptySquare;
7856 if (gameMode == EditPosition) {
7857 DrawPosition(FALSE, boards[0]);
7862 SetWhiteToPlayEvent();
7866 SetBlackToPlayEvent();
7870 if (gameMode == IcsExamining) {
7871 sprintf(buf, "%sx@%c%c\n", ics_prefix, 'a' + x, '1' + y);
7874 boards[0][y][x] = EmptySquare;
7875 DrawPosition(FALSE, boards[0]);
7880 if (gameMode == IcsExamining) {
7881 sprintf(buf, "%s%c@%c%c\n", ics_prefix,
7882 PieceToChar(selection), 'a' + x, '1' + y);
7885 boards[0][y][x] = selection;
7886 DrawPosition(FALSE, boards[0]);
7894 DropMenuEvent(selection, x, y)
7895 ChessSquare selection;
7901 case IcsPlayingWhite:
7902 case MachinePlaysBlack:
7903 if (!WhiteOnMove(currentMove)) {
7904 DisplayMoveError("It is Black's turn");
7907 moveType = WhiteDrop;
7909 case IcsPlayingBlack:
7910 case MachinePlaysWhite:
7911 if (WhiteOnMove(currentMove)) {
7912 DisplayMoveError("It is White's turn");
7915 moveType = BlackDrop;
7918 moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
7924 if (moveType == BlackDrop && selection < BlackPawn) {
7925 selection = (ChessSquare) ((int) selection
7926 + (int) BlackPawn - (int) WhitePawn);
7928 if (boards[currentMove][y][x] != EmptySquare) {
7929 DisplayMoveError("That square is occupied");
7933 FinishMove(moveType, (int) selection, DROP_RANK, x, y, NULLCHAR);
7939 /* Accept a pending offer of any kind from opponent */
7941 if (appData.icsActive) {
7942 SendToICS(ics_prefix);
7943 SendToICS("accept\n");
7944 } else if (cmailMsgLoaded) {
7945 if (currentMove == cmailOldMove &&
7946 commentList[cmailOldMove] != NULL &&
7947 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
7948 "Black offers a draw" : "White offers a draw")) {
7950 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
7951 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
7953 DisplayError("There is no pending offer on this move", 0);
7954 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
7957 /* Not used for offers from chess program */
7964 /* Decline a pending offer of any kind from opponent */
7966 if (appData.icsActive) {
7967 SendToICS(ics_prefix);
7968 SendToICS("decline\n");
7969 } else if (cmailMsgLoaded) {
7970 if (currentMove == cmailOldMove &&
7971 commentList[cmailOldMove] != NULL &&
7972 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
7973 "Black offers a draw" : "White offers a draw")) {
7975 AppendComment(cmailOldMove, "Draw declined");
7976 DisplayComment(cmailOldMove - 1, "Draw declined");
7979 DisplayError("There is no pending offer on this move", 0);
7982 /* Not used for offers from chess program */
7989 /* Issue ICS rematch command */
7990 if (appData.icsActive) {
7991 SendToICS(ics_prefix);
7992 SendToICS("rematch\n");
7999 /* Call your opponent's flag (claim a win on time) */
8000 if (appData.icsActive) {
8001 SendToICS(ics_prefix);
8002 SendToICS("flag\n");
8007 case MachinePlaysWhite:
8010 GameEnds(GameIsDrawn, "Both players ran out of time",
8013 GameEnds(BlackWins, "Black wins on time", GE_PLAYER);
8015 DisplayError("Your opponent is not out of time", 0);
8018 case MachinePlaysBlack:
8021 GameEnds(GameIsDrawn, "Both players ran out of time",
8024 GameEnds(WhiteWins, "White wins on time", GE_PLAYER);
8026 DisplayError("Your opponent is not out of time", 0);
8036 /* Offer draw or accept pending draw offer from opponent */
8038 if (appData.icsActive) {
8039 /* Note: tournament rules require draw offers to be
8040 made after you make your move but before you punch
8041 your clock. Currently ICS doesn't let you do that;
8042 instead, you immediately punch your clock after making
8043 a move, but you can offer a draw at any time. */
8045 SendToICS(ics_prefix);
8046 SendToICS("draw\n");
8047 } else if (cmailMsgLoaded) {
8048 if (currentMove == cmailOldMove &&
8049 commentList[cmailOldMove] != NULL &&
8050 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
8051 "Black offers a draw" : "White offers a draw")) {
8052 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
8053 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
8054 } else if (currentMove == cmailOldMove + 1) {
8055 char *offer = WhiteOnMove(cmailOldMove) ?
8056 "White offers a draw" : "Black offers a draw";
8057 AppendComment(currentMove, offer);
8058 DisplayComment(currentMove - 1, offer);
8059 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_DRAW;
8061 DisplayError("You must make your move before offering a draw", 0);
8062 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
8064 } else if (first.offeredDraw) {
8065 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
8067 if (first.sendDrawOffers) {
8068 SendToProgram("draw\n", &first);
8069 userOfferedDraw = TRUE;
8077 /* Offer Adjourn or accept pending Adjourn offer from opponent */
8079 if (appData.icsActive) {
8080 SendToICS(ics_prefix);
8081 SendToICS("adjourn\n");
8083 /* Currently GNU Chess doesn't offer or accept Adjourns */
8091 /* Offer Abort or accept pending Abort offer from opponent */
8093 if (appData.icsActive) {
8094 SendToICS(ics_prefix);
8095 SendToICS("abort\n");
8097 GameEnds(GameUnfinished, "Game aborted", GE_PLAYER);
8104 /* Resign. You can do this even if it's not your turn. */
8106 if (appData.icsActive) {
8107 SendToICS(ics_prefix);
8108 SendToICS("resign\n");
8111 case MachinePlaysWhite:
8112 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
8114 case MachinePlaysBlack:
8115 GameEnds(BlackWins, "White resigns", GE_PLAYER);
8118 if (cmailMsgLoaded) {
8120 if (WhiteOnMove(cmailOldMove)) {
8121 GameEnds(BlackWins, "White resigns", GE_PLAYER);
8123 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
8125 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_RESIGN;
8136 StopObservingEvent()
8138 /* Stop observing current games */
8139 SendToICS(ics_prefix);
8140 SendToICS("unobserve\n");
8144 StopExaminingEvent()
8146 /* Stop observing current game */
8147 SendToICS(ics_prefix);
8148 SendToICS("unexamine\n");
8152 ForwardInner(target)
8157 if (appData.debugMode)
8158 fprintf(debugFP, "ForwardInner(%d), current %d, forward %d\n",
8159 target, currentMove, forwardMostMove);
8161 if (gameMode == EditPosition)
8164 if (gameMode == PlayFromGameFile && !pausing)
8167 if (gameMode == IcsExamining && pausing)
8168 limit = pauseExamForwardMostMove;
8170 limit = forwardMostMove;
8172 if (target > limit) target = limit;
8174 if (target > 0 && moveList[target - 1][0]) {
8175 int fromX, fromY, toX, toY;
8176 toX = moveList[target - 1][2] - 'a';
8177 toY = moveList[target - 1][3] - '1';
8178 if (moveList[target - 1][1] == '@') {
8179 if (appData.highlightLastMove) {
8180 SetHighlights(-1, -1, toX, toY);
8183 fromX = moveList[target - 1][0] - 'a';
8184 fromY = moveList[target - 1][1] - '1';
8185 if (target == currentMove + 1) {
8186 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
8188 if (appData.highlightLastMove) {
8189 SetHighlights(fromX, fromY, toX, toY);
8193 if (gameMode == EditGame || gameMode == AnalyzeMode ||
8194 gameMode == Training || gameMode == PlayFromGameFile ||
8195 gameMode == AnalyzeFile) {
8196 while (currentMove < target) {
8197 SendMoveToProgram(currentMove++, &first);
8200 currentMove = target;
8203 if (gameMode == EditGame || gameMode == EndOfGame) {
8204 whiteTimeRemaining = timeRemaining[0][currentMove];
8205 blackTimeRemaining = timeRemaining[1][currentMove];
8207 DisplayBothClocks();
8208 DisplayMove(currentMove - 1);
8209 DrawPosition(FALSE, boards[currentMove]);
8210 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
8211 if (commentList[currentMove] && !matchMode && gameMode != Training) {
8212 DisplayComment(currentMove - 1, commentList[currentMove]);
8220 if (gameMode == IcsExamining && !pausing) {
8221 SendToICS(ics_prefix);
8222 SendToICS("forward\n");
8224 ForwardInner(currentMove + 1);
8231 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
8232 /* to optimze, we temporarily turn off analysis mode while we feed
8233 * the remaining moves to the engine. Otherwise we get analysis output
8236 if (first.analysisSupport) {
8237 SendToProgram("exit\nforce\n", &first);
8238 first.analyzing = FALSE;
8242 if (gameMode == IcsExamining && !pausing) {
8243 SendToICS(ics_prefix);
8244 SendToICS("forward 999999\n");
8246 ForwardInner(forwardMostMove);
8249 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
8250 /* we have fed all the moves, so reactivate analysis mode */
8251 SendToProgram("analyze\n", &first);
8252 first.analyzing = TRUE;
8253 /*first.maybeThinking = TRUE;*/
8254 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
8259 BackwardInner(target)
8262 if (appData.debugMode)
8263 fprintf(debugFP, "BackwardInner(%d), current %d, forward %d\n",
8264 target, currentMove, forwardMostMove);
8266 if (gameMode == EditPosition) return;
8267 if (currentMove <= backwardMostMove) {
8269 DrawPosition(FALSE, boards[currentMove]);
8272 if (gameMode == PlayFromGameFile && !pausing)
8275 if (moveList[target][0]) {
8276 int fromX, fromY, toX, toY;
8277 toX = moveList[target][2] - 'a';
8278 toY = moveList[target][3] - '1';
8279 if (moveList[target][1] == '@') {
8280 if (appData.highlightLastMove) {
8281 SetHighlights(-1, -1, toX, toY);
8284 fromX = moveList[target][0] - 'a';
8285 fromY = moveList[target][1] - '1';
8286 if (target == currentMove - 1) {
8287 AnimateMove(boards[currentMove], toX, toY, fromX, fromY);
8289 if (appData.highlightLastMove) {
8290 SetHighlights(fromX, fromY, toX, toY);
8294 if (gameMode == EditGame || gameMode==AnalyzeMode ||
8295 gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
8296 while (currentMove > target) {
8297 SendToProgram("undo\n", &first);
8301 currentMove = target;
8304 if (gameMode == EditGame || gameMode == EndOfGame) {
8305 whiteTimeRemaining = timeRemaining[0][currentMove];
8306 blackTimeRemaining = timeRemaining[1][currentMove];
8308 DisplayBothClocks();
8309 DisplayMove(currentMove - 1);
8310 DrawPosition(FALSE, boards[currentMove]);
8311 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
8312 if (commentList[currentMove] != NULL) {
8313 DisplayComment(currentMove - 1, commentList[currentMove]);
8320 if (gameMode == IcsExamining && !pausing) {
8321 SendToICS(ics_prefix);
8322 SendToICS("backward\n");
8324 BackwardInner(currentMove - 1);
8331 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
8332 /* to optimze, we temporarily turn off analysis mode while we undo
8333 * all the moves. Otherwise we get analysis output after each undo.
8335 if (first.analysisSupport) {
8336 SendToProgram("exit\nforce\n", &first);
8337 first.analyzing = FALSE;
8341 if (gameMode == IcsExamining && !pausing) {
8342 SendToICS(ics_prefix);
8343 SendToICS("backward 999999\n");
8345 BackwardInner(backwardMostMove);
8348 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
8349 /* we have fed all the moves, so reactivate analysis mode */
8350 SendToProgram("analyze\n", &first);
8351 first.analyzing = TRUE;
8352 /*first.maybeThinking = TRUE;*/
8353 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
8360 if (gameMode == PlayFromGameFile && !pausing) PauseEvent();
8361 if (to >= forwardMostMove) to = forwardMostMove;
8362 if (to <= backwardMostMove) to = backwardMostMove;
8363 if (to < currentMove) {
8373 if (gameMode != IcsExamining) {
8374 DisplayError("You are not examining a game", 0);
8378 DisplayError("You can't revert while pausing", 0);
8381 SendToICS(ics_prefix);
8382 SendToICS("revert\n");
8389 case MachinePlaysWhite:
8390 case MachinePlaysBlack:
8391 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
8392 DisplayError("Wait until your turn,\nor select Move Now", 0);
8395 if (forwardMostMove < 2) return;
8396 currentMove = forwardMostMove = forwardMostMove - 2;
8397 whiteTimeRemaining = timeRemaining[0][currentMove];
8398 blackTimeRemaining = timeRemaining[1][currentMove];
8399 DisplayBothClocks();
8400 DisplayMove(currentMove - 1);
8401 ClearHighlights();/*!! could figure this out*/
8402 DrawPosition(FALSE, boards[currentMove]);
8403 SendToProgram("remove\n", &first);
8404 /*first.maybeThinking = TRUE;*/ /* GNU Chess does not ponder here */
8407 case BeginningOfGame:
8411 case IcsPlayingWhite:
8412 case IcsPlayingBlack:
8413 if (WhiteOnMove(forwardMostMove) == (gameMode == IcsPlayingWhite)) {
8414 SendToICS(ics_prefix);
8415 SendToICS("takeback 2\n");
8417 SendToICS(ics_prefix);
8418 SendToICS("takeback 1\n");
8427 ChessProgramState *cps;
8430 case MachinePlaysWhite:
8431 if (!WhiteOnMove(forwardMostMove)) {
8432 DisplayError("It is your turn", 0);
8437 case MachinePlaysBlack:
8438 if (WhiteOnMove(forwardMostMove)) {
8439 DisplayError("It is your turn", 0);
8444 case TwoMachinesPlay:
8445 if (WhiteOnMove(forwardMostMove) ==
8446 (first.twoMachinesColor[0] == 'w')) {
8452 case BeginningOfGame:
8456 SendToProgram("?\n", cps);
8463 if (gameMode != EditGame) return;
8470 if (forwardMostMove > currentMove) {
8471 if (gameInfo.resultDetails != NULL) {
8472 free(gameInfo.resultDetails);
8473 gameInfo.resultDetails = NULL;
8474 gameInfo.result = GameUnfinished;
8476 forwardMostMove = currentMove;
8477 HistorySet(parseList, backwardMostMove, forwardMostMove,
8485 if (appData.noChessProgram) return;
8487 case MachinePlaysWhite:
8488 if (WhiteOnMove(forwardMostMove)) {
8489 DisplayError("Wait until your turn", 0);
8493 case BeginningOfGame:
8494 case MachinePlaysBlack:
8495 if (!WhiteOnMove(forwardMostMove)) {
8496 DisplayError("Wait until your turn", 0);
8501 DisplayError("No hint available", 0);
8504 SendToProgram("hint\n", &first);
8505 hintRequested = TRUE;
8511 if (appData.noChessProgram) return;
8513 case MachinePlaysWhite:
8514 if (WhiteOnMove(forwardMostMove)) {
8515 DisplayError("Wait until your turn", 0);
8519 case BeginningOfGame:
8520 case MachinePlaysBlack:
8521 if (!WhiteOnMove(forwardMostMove)) {
8522 DisplayError("Wait until your turn", 0);
8529 case TwoMachinesPlay:
8534 SendToProgram("bk\n", &first);
8535 bookOutput[0] = NULLCHAR;
8536 bookRequested = TRUE;
8542 char *tags = PGNTags(&gameInfo);
8543 TagsPopUp(tags, CmailMsg());
8547 /* end button procedures */
8550 PrintPosition(fp, move)
8556 for (i = BOARD_SIZE - 1; i >= 0; i--) {
8557 for (j = 0; j < BOARD_SIZE; j++) {
8558 char c = PieceToChar(boards[move][i][j]);
8559 fputc(c == 'x' ? '.' : c, fp);
8560 fputc(j == BOARD_SIZE - 1 ? '\n' : ' ', fp);
8563 if ((gameMode == EditPosition) ? !blackPlaysFirst : (move % 2 == 0))
8564 fprintf(fp, "white to play\n");
8566 fprintf(fp, "black to play\n");
8573 if (gameInfo.white != NULL) {
8574 fprintf(fp, "\t%s vs. %s\n", gameInfo.white, gameInfo.black);
8580 /* Find last component of program's own name, using some heuristics */
8582 TidyProgramName(prog, host, buf)
8583 char *prog, *host, buf[MSG_SIZ];
8586 int local = (strcmp(host, "localhost") == 0);
8587 while (!local && (p = strchr(prog, ';')) != NULL) {
8589 while (*p == ' ') p++;
8592 if (*prog == '"' || *prog == '\'') {
8593 q = strchr(prog + 1, *prog);
8595 q = strchr(prog, ' ');
8597 if (q == NULL) q = prog + strlen(prog);
8599 while (p >= prog && *p != '/' && *p != '\\') p--;
8601 if (q - p >= 4 && StrCaseCmp(q - 4, ".exe") == 0) q -= 4;
8602 memcpy(buf, p, q - p);
8603 buf[q - p] = NULLCHAR;
8611 TimeControlTagValue()
8614 if (!appData.clockMode) {
8616 } else if (movesPerSession > 0) {
8617 sprintf(buf, "%d/%ld", movesPerSession, timeControl/1000);
8618 } else if (timeIncrement == 0) {
8619 sprintf(buf, "%ld", timeControl/1000);
8621 sprintf(buf, "%ld+%ld", timeControl/1000, timeIncrement/1000);
8623 return StrSave(buf);
8629 /* This routine is used only for certain modes */
8630 VariantClass v = gameInfo.variant;
8631 ClearGameInfo(&gameInfo);
8632 gameInfo.variant = v;
8635 case MachinePlaysWhite:
8636 gameInfo.event = StrSave("Computer chess game");
8637 gameInfo.site = StrSave(HostName());
8638 gameInfo.date = PGNDate();
8639 gameInfo.round = StrSave("-");
8640 gameInfo.white = StrSave(first.tidy);
8641 gameInfo.black = StrSave(UserName());
8642 gameInfo.timeControl = TimeControlTagValue();
8645 case MachinePlaysBlack:
8646 gameInfo.event = StrSave("Computer chess game");
8647 gameInfo.site = StrSave(HostName());
8648 gameInfo.date = PGNDate();
8649 gameInfo.round = StrSave("-");
8650 gameInfo.white = StrSave(UserName());
8651 gameInfo.black = StrSave(first.tidy);
8652 gameInfo.timeControl = TimeControlTagValue();
8655 case TwoMachinesPlay:
8656 gameInfo.event = StrSave("Computer chess game");
8657 gameInfo.site = StrSave(HostName());
8658 gameInfo.date = PGNDate();
8659 if (matchGame > 0) {
8661 sprintf(buf, "%d", matchGame);
8662 gameInfo.round = StrSave(buf);
8664 gameInfo.round = StrSave("-");
8666 if (first.twoMachinesColor[0] == 'w') {
8667 gameInfo.white = StrSave(first.tidy);
8668 gameInfo.black = StrSave(second.tidy);
8670 gameInfo.white = StrSave(second.tidy);
8671 gameInfo.black = StrSave(first.tidy);
8673 gameInfo.timeControl = TimeControlTagValue();
8677 gameInfo.event = StrSave("Edited game");
8678 gameInfo.site = StrSave(HostName());
8679 gameInfo.date = PGNDate();
8680 gameInfo.round = StrSave("-");
8681 gameInfo.white = StrSave("-");
8682 gameInfo.black = StrSave("-");
8686 gameInfo.event = StrSave("Edited position");
8687 gameInfo.site = StrSave(HostName());
8688 gameInfo.date = PGNDate();
8689 gameInfo.round = StrSave("-");
8690 gameInfo.white = StrSave("-");
8691 gameInfo.black = StrSave("-");
8694 case IcsPlayingWhite:
8695 case IcsPlayingBlack:
8700 case PlayFromGameFile:
8701 gameInfo.event = StrSave("Game from non-PGN file");
8702 gameInfo.site = StrSave(HostName());
8703 gameInfo.date = PGNDate();
8704 gameInfo.round = StrSave("-");
8705 gameInfo.white = StrSave("?");
8706 gameInfo.black = StrSave("?");
8715 ReplaceComment(index, text)
8721 while (*text == '\n') text++;
8723 while (len > 0 && text[len - 1] == '\n') len--;
8725 if (commentList[index] != NULL)
8726 free(commentList[index]);
8729 commentList[index] = NULL;
8732 commentList[index] = (char *) malloc(len + 2);
8733 strncpy(commentList[index], text, len);
8734 commentList[index][len] = '\n';
8735 commentList[index][len + 1] = NULLCHAR;
8748 if (ch == '\r') continue;
8750 } while (ch != '\0');
8754 AppendComment(index, text)
8762 while (*text == '\n') text++;
8764 while (len > 0 && text[len - 1] == '\n') len--;
8766 if (len == 0) return;
8768 if (commentList[index] != NULL) {
8769 old = commentList[index];
8770 oldlen = strlen(old);
8771 commentList[index] = (char *) malloc(oldlen + len + 2);
8772 strcpy(commentList[index], old);
8774 strncpy(&commentList[index][oldlen], text, len);
8775 commentList[index][oldlen + len] = '\n';
8776 commentList[index][oldlen + len + 1] = NULLCHAR;
8778 commentList[index] = (char *) malloc(len + 2);
8779 strncpy(commentList[index], text, len);
8780 commentList[index][len] = '\n';
8781 commentList[index][len + 1] = NULLCHAR;
8786 SendToProgram(message, cps)
8788 ChessProgramState *cps;
8790 int count, outCount, error;
8793 if (cps->pr == NULL) return;
8796 if (appData.debugMode) {
8799 fprintf(debugFP, "%ld >%-6s: %s",
8800 SubtractTimeMarks(&now, &programStartTime),
8801 cps->which, message);
8804 count = strlen(message);
8805 outCount = OutputToProcess(cps->pr, message, count, &error);
8806 if (outCount < count && !exiting) {
8807 sprintf(buf, "Error writing to %s chess program", cps->which);
8808 DisplayFatalError(buf, error, 1);
8813 ReceiveFromProgram(isr, closure, message, count, error)
8822 ChessProgramState *cps = (ChessProgramState *)closure;
8824 if (isr != cps->isr) return; /* Killed intentionally */
8828 "Error: %s chess program (%s) exited unexpectedly",
8829 cps->which, cps->program);
8830 RemoveInputSource(cps->isr);
8831 DisplayFatalError(buf, 0, 1);
8834 "Error reading from %s chess program (%s)",
8835 cps->which, cps->program);
8836 RemoveInputSource(cps->isr);
8837 DisplayFatalError(buf, error, 1);
8839 GameEnds((ChessMove) 0, NULL, GE_PLAYER);
8843 if ((end_str = strchr(message, '\r')) != NULL)
8844 *end_str = NULLCHAR;
8845 if ((end_str = strchr(message, '\n')) != NULL)
8846 *end_str = NULLCHAR;
8848 if (appData.debugMode) {
8851 fprintf(debugFP, "%ld <%-6s: %s\n",
8852 SubtractTimeMarks(&now, &programStartTime),
8853 cps->which, message);
8855 HandleMachineMove(message, cps);
8860 SendTimeControl(cps, mps, tc, inc, sd, st)
8861 ChessProgramState *cps;
8862 int mps, inc, sd, st;
8866 int seconds = (tc / 1000) % 60;
8869 /* Set exact time per move, normally using st command */
8870 if (cps->stKludge) {
8871 /* GNU Chess 4 has no st command; uses level in a nonstandard way */
8874 sprintf(buf, "level 1 %d\n", st/60);
8876 sprintf(buf, "level 1 %d:%02d\n", st/60, seconds);
8879 sprintf(buf, "st %d\n", st);
8882 /* Set conventional or incremental time control, using level command */
8884 /* Note old gnuchess bug -- minutes:seconds used to not work.
8885 Fixed in later versions, but still avoid :seconds
8886 when seconds is 0. */
8887 sprintf(buf, "level %d %ld %d\n", mps, tc/60000, inc/1000);
8889 sprintf(buf, "level %d %ld:%02d %d\n", mps, tc/60000,
8893 SendToProgram(buf, cps);
8895 /* Orthoganally (except for GNU Chess 4), limit time to st seconds */
8896 /* Orthogonally, limit search to given depth */
8898 if (cps->sdKludge) {
8899 sprintf(buf, "depth\n%d\n", sd);
8901 sprintf(buf, "sd %d\n", sd);
8903 SendToProgram(buf, cps);
8908 SendTimeRemaining(cps, machineWhite)
8909 ChessProgramState *cps;
8910 int /*boolean*/ machineWhite;
8912 char message[MSG_SIZ];
8915 /* Note: this routine must be called when the clocks are stopped
8916 or when they have *just* been set or switched; otherwise
8917 it will be off by the time since the current tick started.
8920 time = whiteTimeRemaining / 10;
8921 otime = blackTimeRemaining / 10;
8923 time = blackTimeRemaining / 10;
8924 otime = whiteTimeRemaining / 10;
8926 if (time <= 0) time = 1;
8927 if (otime <= 0) otime = 1;
8929 sprintf(message, "time %ld\notim %ld\n", time, otime);
8930 SendToProgram(message, cps);
8934 BoolFeature(p, name, loc, cps)
8938 ChessProgramState *cps;
8941 int len = strlen(name);
8943 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
8945 sscanf(*p, "%d", &val);
8947 while (**p && **p != ' ') (*p)++;
8948 sprintf(buf, "accepted %s\n", name);
8949 SendToProgram(buf, cps);
8956 IntFeature(p, name, loc, cps)
8960 ChessProgramState *cps;
8963 int len = strlen(name);
8964 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
8966 sscanf(*p, "%d", loc);
8967 while (**p && **p != ' ') (*p)++;
8968 sprintf(buf, "accepted %s\n", name);
8969 SendToProgram(buf, cps);
8976 StringFeature(p, name, loc, cps)
8980 ChessProgramState *cps;
8983 int len = strlen(name);
8984 if (strncmp((*p), name, len) == 0
8985 && (*p)[len] == '=' && (*p)[len+1] == '\"') {
8987 sscanf(*p, "%[^\"]", loc);
8988 while (**p && **p != '\"') (*p)++;
8989 if (**p == '\"') (*p)++;
8990 sprintf(buf, "accepted %s\n", name);
8991 SendToProgram(buf, cps);
8998 FeatureDone(cps, val)
8999 ChessProgramState* cps;
9002 DelayedEventCallback cb = GetDelayedEvent();
9003 if ((cb == InitBackEnd3 && cps == &first) ||
9004 (cb == TwoMachinesEventIfReady && cps == &second)) {
9005 CancelDelayedEvent();
9006 ScheduleDelayedEvent(cb, val ? 1 : 3600000);
9008 cps->initDone = val;
9011 /* Parse feature command from engine */
9013 ParseFeatures(args, cps)
9015 ChessProgramState *cps;
9023 while (*p == ' ') p++;
9024 if (*p == NULLCHAR) return;
9026 if (BoolFeature(&p, "setboard", &cps->useSetboard, cps)) continue;
9027 if (BoolFeature(&p, "time", &cps->sendTime, cps)) continue;
9028 if (BoolFeature(&p, "draw", &cps->sendDrawOffers, cps)) continue;
9029 if (BoolFeature(&p, "sigint", &cps->useSigint, cps)) continue;
9030 if (BoolFeature(&p, "sigterm", &cps->useSigterm, cps)) continue;
9031 if (BoolFeature(&p, "reuse", &val, cps)) {
9032 /* Engine can disable reuse, but can't enable it if user said no */
9033 if (!val) cps->reuse = FALSE;
9036 if (BoolFeature(&p, "analyze", &cps->analysisSupport, cps)) continue;
9037 if (StringFeature(&p, "myname", &cps->tidy, cps)) {
9038 if (gameMode == TwoMachinesPlay) {
9039 DisplayTwoMachinesTitle();
9045 if (StringFeature(&p, "variants", &cps->variants, cps)) continue;
9046 if (BoolFeature(&p, "san", &cps->useSAN, cps)) continue;
9047 if (BoolFeature(&p, "ping", &cps->usePing, cps)) continue;
9048 if (BoolFeature(&p, "playother", &cps->usePlayother, cps)) continue;
9049 if (BoolFeature(&p, "colors", &cps->useColors, cps)) continue;
9050 if (BoolFeature(&p, "usermove", &cps->useUsermove, cps)) continue;
9051 if (BoolFeature(&p, "ics", &cps->sendICS, cps)) continue;
9052 if (BoolFeature(&p, "name", &cps->sendName, cps)) continue;
9053 if (BoolFeature(&p, "pause", &val, cps)) continue; /* unused at present */
9054 if (IntFeature(&p, "done", &val, cps)) {
9055 FeatureDone(cps, val);
9059 /* unknown feature: complain and skip */
9061 while (*q && *q != '=') q++;
9062 sprintf(buf, "rejected %.*s\n", q-p, p);
9063 SendToProgram(buf, cps);
9069 while (*p && *p != '\"') p++;
9070 if (*p == '\"') p++;
9072 while (*p && *p != ' ') p++;
9080 PeriodicUpdatesEvent(newState)
9083 if (newState == appData.periodicUpdates)
9086 appData.periodicUpdates=newState;
9088 /* Display type changes, so update it now */
9091 /* Get the ball rolling again... */
9093 AnalysisPeriodicEvent(1);
9094 StartAnalysisClock();
9099 PonderNextMoveEvent(newState)
9102 if (newState == appData.ponderNextMove) return;
9103 if (gameMode == EditPosition) EditPositionDone();
9105 SendToProgram("hard\n", &first);
9106 if (gameMode == TwoMachinesPlay) {
9107 SendToProgram("hard\n", &second);
9110 SendToProgram("easy\n", &first);
9111 thinkOutput[0] = NULLCHAR;
9112 if (gameMode == TwoMachinesPlay) {
9113 SendToProgram("easy\n", &second);
9116 appData.ponderNextMove = newState;
9120 ShowThinkingEvent(newState)
9123 if (newState == appData.showThinking) return;
9124 if (gameMode == EditPosition) EditPositionDone();
9126 SendToProgram("post\n", &first);
9127 if (gameMode == TwoMachinesPlay) {
9128 SendToProgram("post\n", &second);
9131 SendToProgram("nopost\n", &first);
9132 thinkOutput[0] = NULLCHAR;
9133 if (gameMode == TwoMachinesPlay) {
9134 SendToProgram("nopost\n", &second);
9137 appData.showThinking = newState;
9141 AskQuestionEvent(title, question, replyPrefix, which)
9142 char *title; char *question; char *replyPrefix; char *which;
9144 ProcRef pr = (which[0] == '1') ? first.pr : second.pr;
9145 if (pr == NoProc) return;
9146 AskQuestion(title, question, replyPrefix, pr);
9150 DisplayMove(moveNumber)
9153 char message[MSG_SIZ];
9155 char cpThinkOutput[MSG_SIZ];
9157 if (moveNumber == forwardMostMove - 1 ||
9158 gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
9160 strcpy(cpThinkOutput, thinkOutput);
9161 if (strchr(cpThinkOutput, '\n'))
9162 *strchr(cpThinkOutput, '\n') = NULLCHAR;
9164 *cpThinkOutput = NULLCHAR;
9167 if (moveNumber == forwardMostMove - 1 &&
9168 gameInfo.resultDetails != NULL) {
9169 if (gameInfo.resultDetails[0] == NULLCHAR) {
9170 sprintf(res, " %s", PGNResult(gameInfo.result));
9172 sprintf(res, " {%s} %s",
9173 gameInfo.resultDetails, PGNResult(gameInfo.result));
9179 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
9180 DisplayMessage(res, cpThinkOutput);
9182 sprintf(message, "%d.%s%s%s", moveNumber / 2 + 1,
9183 WhiteOnMove(moveNumber) ? " " : ".. ",
9184 parseList[moveNumber], res);
9185 DisplayMessage(message, cpThinkOutput);
9190 DisplayAnalysisText(text)
9195 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
9196 sprintf(buf, "Analysis (%s)", first.tidy);
9197 AnalysisPopUp(buf, text);
9205 while (*str && isspace(*str)) ++str;
9206 while (*str && !isspace(*str)) ++str;
9207 if (!*str) return 1;
9208 while (*str && isspace(*str)) ++str;
9209 if (!*str) return 1;
9218 static char *xtra[] = { "", " (--)", " (++)" };
9221 if (programStats.time == 0) {
9222 programStats.time = 1;
9225 if (programStats.got_only_move) {
9226 strcpy(buf, programStats.movelist);
9228 nps = (((double)programStats.nodes) /
9229 (((double)programStats.time)/100.0));
9231 cs = programStats.time % 100;
9232 s = programStats.time / 100;
9238 if (programStats.moves_left > 0 && appData.periodicUpdates) {
9239 if (programStats.move_name[0] != NULLCHAR) {
9240 sprintf(buf, "depth=%d %d/%d(%s) %+.2f %s%s\nNodes: %lu NPS: %d\nTime: %02d:%02d:%02d.%02d",
9242 programStats.nr_moves-programStats.moves_left,
9243 programStats.nr_moves, programStats.move_name,
9244 ((float)programStats.score)/100.0, programStats.movelist,
9245 only_one_move(programStats.movelist)?
9246 xtra[programStats.got_fail] : "",
9247 programStats.nodes, (int)nps, h, m, s, cs);
9249 sprintf(buf, "depth=%d %d/%d %+.2f %s%s\nNodes: %lu NPS: %d\nTime: %02d:%02d:%02d.%02d",
9251 programStats.nr_moves-programStats.moves_left,
9252 programStats.nr_moves, ((float)programStats.score)/100.0,
9253 programStats.movelist,
9254 only_one_move(programStats.movelist)?
9255 xtra[programStats.got_fail] : "",
9256 programStats.nodes, (int)nps, h, m, s, cs);
9259 sprintf(buf, "depth=%d %+.2f %s%s\nNodes: %lu NPS: %d\nTime: %02d:%02d:%02d.%02d",
9261 ((float)programStats.score)/100.0,
9262 programStats.movelist,
9263 only_one_move(programStats.movelist)?
9264 xtra[programStats.got_fail] : "",
9265 programStats.nodes, (int)nps, h, m, s, cs);
9268 DisplayAnalysisText(buf);
9272 DisplayComment(moveNumber, text)
9276 char title[MSG_SIZ];
9278 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
9279 strcpy(title, "Comment");
9281 sprintf(title, "Comment on %d.%s%s", moveNumber / 2 + 1,
9282 WhiteOnMove(moveNumber) ? " " : ".. ",
9283 parseList[moveNumber]);
9286 CommentPopUp(title, text);
9289 /* This routine sends a ^C interrupt to gnuchess, to awaken it if it
9290 * might be busy thinking or pondering. It can be omitted if your
9291 * gnuchess is configured to stop thinking immediately on any user
9292 * input. However, that gnuchess feature depends on the FIONREAD
9293 * ioctl, which does not work properly on some flavors of Unix.
9297 ChessProgramState *cps;
9300 if (!cps->useSigint) return;
9301 if (appData.noChessProgram || (cps->pr == NoProc)) return;
9303 case MachinePlaysWhite:
9304 case MachinePlaysBlack:
9305 case TwoMachinesPlay:
9306 case IcsPlayingWhite:
9307 case IcsPlayingBlack:
9310 /* Skip if we know it isn't thinking */
9311 if (!cps->maybeThinking) return;
9312 if (appData.debugMode)
9313 fprintf(debugFP, "Interrupting %s\n", cps->which);
9314 InterruptChildProcess(cps->pr);
9315 cps->maybeThinking = FALSE;
9320 #endif /*ATTENTION*/
9326 if (whiteTimeRemaining <= 0) {
9329 if (appData.icsActive) {
9330 if (appData.autoCallFlag &&
9331 gameMode == IcsPlayingBlack && !blackFlag) {
9332 SendToICS(ics_prefix);
9333 SendToICS("flag\n");
9337 DisplayTitle("Both flags fell");
9339 DisplayTitle("White's flag fell");
9340 if (appData.autoCallFlag) {
9341 GameEnds(BlackWins, "Black wins on time", GE_XBOARD);
9348 if (blackTimeRemaining <= 0) {
9351 if (appData.icsActive) {
9352 if (appData.autoCallFlag &&
9353 gameMode == IcsPlayingWhite && !whiteFlag) {
9354 SendToICS(ics_prefix);
9355 SendToICS("flag\n");
9359 DisplayTitle("Both flags fell");
9361 DisplayTitle("Black's flag fell");
9362 if (appData.autoCallFlag) {
9363 GameEnds(WhiteWins, "White wins on time", GE_XBOARD);
9376 if (!appData.clockMode || appData.icsActive ||
9377 gameMode == PlayFromGameFile || forwardMostMove == 0) return;
9379 if (timeIncrement >= 0) {
9380 if (WhiteOnMove(forwardMostMove)) {
9381 blackTimeRemaining += timeIncrement;
9383 whiteTimeRemaining += timeIncrement;
9387 * add time to clocks when time control is achieved
9389 if (movesPerSession) {
9390 switch ((forwardMostMove + 1) % (movesPerSession * 2)) {
9392 /* White made time control */
9393 whiteTimeRemaining += timeControl;
9396 /* Black made time control */
9397 blackTimeRemaining += timeControl;
9408 int wom = gameMode == EditPosition ?
9409 !blackPlaysFirst : WhiteOnMove(currentMove);
9410 DisplayWhiteClock(whiteTimeRemaining, wom);
9411 DisplayBlackClock(blackTimeRemaining, !wom);
9415 /* Timekeeping seems to be a portability nightmare. I think everyone
9416 has ftime(), but I'm really not sure, so I'm including some ifdefs
9417 to use other calls if you don't. Clocks will be less accurate if
9418 you have neither ftime nor gettimeofday.
9421 /* Get the current time as a TimeMark */
9426 #if HAVE_GETTIMEOFDAY
9428 struct timeval timeVal;
9429 struct timezone timeZone;
9431 gettimeofday(&timeVal, &timeZone);
9432 tm->sec = (long) timeVal.tv_sec;
9433 tm->ms = (int) (timeVal.tv_usec / 1000L);
9435 #else /*!HAVE_GETTIMEOFDAY*/
9438 #include <sys/timeb.h>
9442 tm->sec = (long) timeB.time;
9443 tm->ms = (int) timeB.millitm;
9445 #else /*!HAVE_FTIME && !HAVE_GETTIMEOFDAY*/
9446 tm->sec = (long) time(NULL);
9452 /* Return the difference in milliseconds between two
9453 time marks. We assume the difference will fit in a long!
9456 SubtractTimeMarks(tm2, tm1)
9457 TimeMark *tm2, *tm1;
9459 return 1000L*(tm2->sec - tm1->sec) +
9460 (long) (tm2->ms - tm1->ms);
9465 * Code to manage the game clocks.
9467 * In tournament play, black starts the clock and then white makes a move.
9468 * We give the human user a slight advantage if he is playing white---the
9469 * clocks don't run until he makes his first move, so it takes zero time.
9470 * Also, we don't account for network lag, so we could get out of sync
9471 * with GNU Chess's clock -- but then, referees are always right.
9474 static TimeMark tickStartTM;
9475 static long intendedTickLength;
9478 NextTickLength(timeRemaining)
9481 long nominalTickLength, nextTickLength;
9483 if (timeRemaining > 0L && timeRemaining <= 10000L)
9484 nominalTickLength = 100L;
9486 nominalTickLength = 1000L;
9487 nextTickLength = timeRemaining % nominalTickLength;
9488 if (nextTickLength <= 0) nextTickLength += nominalTickLength;
9490 return nextTickLength;
9493 /* Stop clocks and reset to a fresh time control */
9497 (void) StopClockTimer();
9498 if (appData.icsActive) {
9499 whiteTimeRemaining = blackTimeRemaining = 0;
9501 whiteTimeRemaining = blackTimeRemaining = timeControl;
9503 if (whiteFlag || blackFlag) {
9505 whiteFlag = blackFlag = FALSE;
9507 DisplayBothClocks();
9510 #define FUDGE 25 /* 25ms = 1/40 sec; should be plenty even for 50 Hz clocks */
9512 /* Decrement running clock by amount of time that has passed */
9517 long lastTickLength, fudge;
9520 if (!appData.clockMode) return;
9521 if (gameMode==AnalyzeMode || gameMode == AnalyzeFile) return;
9525 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
9527 /* Fudge if we woke up a little too soon */
9528 fudge = intendedTickLength - lastTickLength;
9529 if (fudge < 0 || fudge > FUDGE) fudge = 0;
9531 if (WhiteOnMove(forwardMostMove)) {
9532 timeRemaining = whiteTimeRemaining -= lastTickLength;
9533 DisplayWhiteClock(whiteTimeRemaining - fudge,
9534 WhiteOnMove(currentMove));
9536 timeRemaining = blackTimeRemaining -= lastTickLength;
9537 DisplayBlackClock(blackTimeRemaining - fudge,
9538 !WhiteOnMove(currentMove));
9541 if (CheckFlags()) return;
9544 intendedTickLength = NextTickLength(timeRemaining - fudge) + fudge;
9545 StartClockTimer(intendedTickLength);
9547 /* if the time remaining has fallen below the alarm threshold, sound the
9548 * alarm. if the alarm has sounded and (due to a takeback or time control
9549 * with increment) the time remaining has increased to a level above the
9550 * threshold, reset the alarm so it can sound again.
9553 if (appData.icsActive && appData.icsAlarm) {
9555 /* make sure we are dealing with the user's clock */
9556 if (!( ((gameMode == IcsPlayingWhite) && WhiteOnMove(currentMove)) ||
9557 ((gameMode == IcsPlayingBlack) && !WhiteOnMove(currentMove))
9560 if (alarmSounded && (timeRemaining > appData.icsAlarmTime)) {
9561 alarmSounded = FALSE;
9562 } else if (!alarmSounded && (timeRemaining <= appData.icsAlarmTime)) {
9564 alarmSounded = TRUE;
9570 /* A player has just moved, so stop the previously running
9571 clock and (if in clock mode) start the other one.
9572 We redisplay both clocks in case we're in ICS mode, because
9573 ICS gives us an update to both clocks after every move.
9574 Note that this routine is called *after* forwardMostMove
9575 is updated, so the last fractional tick must be subtracted
9576 from the color that is *not* on move now.
9581 long lastTickLength;
9583 int flagged = FALSE;
9587 if (StopClockTimer() && appData.clockMode) {
9588 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
9589 if (WhiteOnMove(forwardMostMove)) {
9590 blackTimeRemaining -= lastTickLength;
9592 whiteTimeRemaining -= lastTickLength;
9594 flagged = CheckFlags();
9598 if (flagged || !appData.clockMode) return;
9601 case MachinePlaysBlack:
9602 case MachinePlaysWhite:
9603 case BeginningOfGame:
9604 if (pausing) return;
9608 case PlayFromGameFile:
9617 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
9618 whiteTimeRemaining : blackTimeRemaining);
9619 StartClockTimer(intendedTickLength);
9623 /* Stop both clocks */
9627 long lastTickLength;
9630 if (!StopClockTimer()) return;
9631 if (!appData.clockMode) return;
9635 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
9636 if (WhiteOnMove(forwardMostMove)) {
9637 whiteTimeRemaining -= lastTickLength;
9638 DisplayWhiteClock(whiteTimeRemaining, WhiteOnMove(currentMove));
9640 blackTimeRemaining -= lastTickLength;
9641 DisplayBlackClock(blackTimeRemaining, !WhiteOnMove(currentMove));
9646 /* Start clock of player on move. Time may have been reset, so
9647 if clock is already running, stop and restart it. */
9651 (void) StopClockTimer(); /* in case it was running already */
9652 DisplayBothClocks();
9653 if (CheckFlags()) return;
9655 if (!appData.clockMode) return;
9656 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) return;
9658 GetTimeMark(&tickStartTM);
9659 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
9660 whiteTimeRemaining : blackTimeRemaining);
9661 StartClockTimer(intendedTickLength);
9668 long second, minute, hour, day;
9670 static char buf[32];
9672 if (ms > 0 && ms <= 9900) {
9673 /* convert milliseconds to tenths, rounding up */
9674 double tenths = floor( ((double)(ms + 99L)) / 100.00 );
9676 sprintf(buf, " %03.1f ", tenths/10.0);
9680 /* convert milliseconds to seconds, rounding up */
9681 /* use floating point to avoid strangeness of integer division
9682 with negative dividends on many machines */
9683 second = (long) floor(((double) (ms + 999L)) / 1000.0);
9690 day = second / (60 * 60 * 24);
9691 second = second % (60 * 60 * 24);
9692 hour = second / (60 * 60);
9693 second = second % (60 * 60);
9694 minute = second / 60;
9695 second = second % 60;
9698 sprintf(buf, " %s%ld:%02ld:%02ld:%02ld ",
9699 sign, day, hour, minute, second);
9701 sprintf(buf, " %s%ld:%02ld:%02ld ", sign, hour, minute, second);
9703 sprintf(buf, " %s%2ld:%02ld ", sign, minute, second);
9710 * This is necessary because some C libraries aren't ANSI C compliant yet.
9713 StrStr(string, match)
9714 char *string, *match;
9718 length = strlen(match);
9720 for (i = strlen(string) - length; i >= 0; i--, string++)
9721 if (!strncmp(match, string, length))
9728 StrCaseStr(string, match)
9729 char *string, *match;
9733 length = strlen(match);
9735 for (i = strlen(string) - length; i >= 0; i--, string++) {
9736 for (j = 0; j < length; j++) {
9737 if (ToLower(match[j]) != ToLower(string[j]))
9740 if (j == length) return string;
9754 c1 = ToLower(*s1++);
9755 c2 = ToLower(*s2++);
9756 if (c1 > c2) return 1;
9757 if (c1 < c2) return -1;
9758 if (c1 == NULLCHAR) return 0;
9767 return isupper(c) ? tolower(c) : c;
9775 return islower(c) ? toupper(c) : c;
9777 #endif /* !_amigados */
9785 if ((ret = (char *) malloc(strlen(s) + 1))) {
9792 StrSavePtr(s, savePtr)
9798 if ((*savePtr = (char *) malloc(strlen(s) + 1))) {
9799 strcpy(*savePtr, s);
9811 clock = time((time_t *)NULL);
9812 tm = localtime(&clock);
9813 sprintf(buf, "%04d.%02d.%02d",
9814 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday);
9815 return StrSave(buf);
9823 int i, j, fromX, fromY, toX, toY;
9829 whiteToPlay = (gameMode == EditPosition) ?
9830 !blackPlaysFirst : (move % 2 == 0);
9833 /* Piece placement data */
9834 for (i = BOARD_SIZE - 1; i >= 0; i--) {
9836 for (j = 0; j < BOARD_SIZE; j++) {
9837 if (boards[move][i][j] == EmptySquare) {
9840 if (emptycount > 0) {
9841 *p++ = '0' + emptycount;
9844 *p++ = PieceToChar(boards[move][i][j]);
9847 if (emptycount > 0) {
9848 *p++ = '0' + emptycount;
9856 *p++ = whiteToPlay ? 'w' : 'b';
9859 /* !!We don't keep track of castling availability, so fake it */
9861 if (boards[move][0][4] == WhiteKing) {
9862 if (boards[move][0][7] == WhiteRook) *p++ = 'K';
9863 if (boards[move][0][0] == WhiteRook) *p++ = 'Q';
9865 if (boards[move][7][4] == BlackKing) {
9866 if (boards[move][7][7] == BlackRook) *p++ = 'k';
9867 if (boards[move][7][0] == BlackRook) *p++ = 'q';
9869 if (q == p) *p++ = '-';
9872 /* En passant target square */
9873 if (move > backwardMostMove) {
9874 fromX = moveList[move - 1][0] - 'a';
9875 fromY = moveList[move - 1][1] - '1';
9876 toX = moveList[move - 1][2] - 'a';
9877 toY = moveList[move - 1][3] - '1';
9878 if (fromY == (whiteToPlay ? 6 : 1) &&
9879 toY == (whiteToPlay ? 4 : 3) &&
9880 boards[move][toY][toX] == (whiteToPlay ? BlackPawn : WhitePawn) &&
9882 /* 2-square pawn move just happened */
9884 *p++ = whiteToPlay ? '6' : '3';
9892 /* !!We don't keep track of halfmove clock for 50-move rule */
9896 /* Fullmove number */
9897 sprintf(p, "%d", (move / 2) + 1);
9899 return StrSave(buf);
9903 ParseFEN(board, blackPlaysFirst, fen)
9905 int *blackPlaysFirst;
9914 /* Piece placement data */
9915 for (i = BOARD_SIZE - 1; i >= 0; i--) {
9918 if (*p == '/' || *p == ' ') {
9920 emptycount = BOARD_SIZE - j;
9921 while (emptycount--) board[i][j++] = EmptySquare;
9923 } else if (isdigit(*p)) {
9924 emptycount = *p++ - '0';
9925 if (j + emptycount > BOARD_SIZE) return FALSE;
9926 while (emptycount--) board[i][j++] = EmptySquare;
9927 } else if (isalpha(*p)) {
9928 if (j >= BOARD_SIZE) return FALSE;
9929 board[i][j++] = CharToPiece(*p++);
9935 while (*p == '/' || *p == ' ') p++;
9940 *blackPlaysFirst = FALSE;
9943 *blackPlaysFirst = TRUE;
9948 /* !!We ignore the rest of the FEN notation */
9953 EditPositionPasteFEN(char *fen)
9956 Board initial_position;
9958 if (!ParseFEN(initial_position, &blackPlaysFirst, fen)) {
9959 DisplayError("Bad FEN position in clipboard", 0);
9962 int savedBlackPlaysFirst = blackPlaysFirst;
9963 EditPositionEvent();
9964 blackPlaysFirst = savedBlackPlaysFirst;
9965 CopyBoard(boards[0], initial_position);
9967 DisplayBothClocks();
9968 DrawPosition(FALSE, boards[currentMove]);