2 * backend.c -- Common back end for X and Windows NT versions of
5 * Copyright 1991 by Digital Equipment Corporation, Maynard, Massachusetts.
6 * Enhancements Copyright 1992-2001 Free Software Foundation, Inc.
8 * The following terms apply to Digital Equipment Corporation's copyright
10 * ------------------------------------------------------------------------
13 * Permission to use, copy, modify, and distribute this software and its
14 * documentation for any purpose and without fee is hereby granted,
15 * provided that the above copyright notice appear in all copies and that
16 * both that copyright notice and this permission notice appear in
17 * supporting documentation, and that the name of Digital not be
18 * used in advertising or publicity pertaining to distribution of the
19 * software without specific, written prior permission.
21 * DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
22 * ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
23 * DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
24 * ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
25 * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
26 * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
28 * ------------------------------------------------------------------------
30 * The following terms apply to the enhanced version of XBoard distributed
31 * by the Free Software Foundation:
32 * ------------------------------------------------------------------------
33 * This program is free software; you can redistribute it and/or modify
34 * it under the terms of the GNU General Public License as published by
35 * the Free Software Foundation; either version 2 of the License, or
36 * (at your option) any later version.
38 * This program is distributed in the hope that it will be useful,
39 * but WITHOUT ANY WARRANTY; without even the implied warranty of
40 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
41 * GNU General Public License for more details.
43 * You should have received a copy of the GNU General Public License
44 * along with this program; if not, write to the Free Software
45 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
46 * ------------------------------------------------------------------------
48 * See the file ChangeLog for a revision history. */
55 #include <sys/types.h>
62 #else /* not STDC_HEADERS */
65 # else /* not HAVE_STRING_H */
67 # endif /* not HAVE_STRING_H */
68 #endif /* not STDC_HEADERS */
71 # include <sys/fcntl.h>
72 #else /* not HAVE_SYS_FCNTL_H */
75 # endif /* HAVE_FCNTL_H */
76 #endif /* not HAVE_SYS_FCNTL_H */
78 #if TIME_WITH_SYS_TIME
79 # include <sys/time.h>
83 # include <sys/time.h>
89 #if defined(_amigados) && !defined(__GNUC__)
94 extern int gettimeofday(struct timeval *, struct timezone *);
102 #include "frontend.h"
109 #include "backendz.h"
113 # define _(s) gettext (s)
114 # define N_(s) gettext_noop (s)
121 /* A point in time */
123 long sec; /* Assuming this is >= 32 bits */
124 int ms; /* Assuming this is >= 16 bits */
127 /* Search stats from chessprogram */
129 char movelist[2*MSG_SIZ]; /* Last PV we were sent */
130 int depth; /* Current search depth */
131 int nr_moves; /* Total nr of root moves */
132 int moves_left; /* Moves remaining to be searched */
133 char move_name[MOVE_LEN]; /* Current move being searched, if provided */
134 u64 nodes; /* # of nodes searched */
135 int time; /* Search time (centiseconds) */
136 int score; /* Score (centipawns) */
137 int got_only_move; /* If last msg was "(only move)" */
138 int got_fail; /* 0 - nothing, 1 - got "--", 2 - got "++" */
139 int ok_to_send; /* handshaking between send & recv */
140 int line_is_book; /* 1 if movelist is book moves */
141 int seen_stat; /* 1 if we've seen the stat01: line */
144 int establish P((void));
145 void read_from_player P((InputSourceRef isr, VOIDSTAR closure,
146 char *buf, int count, int error));
147 void read_from_ics P((InputSourceRef isr, VOIDSTAR closure,
148 char *buf, int count, int error));
149 void SendToICS P((char *s));
150 void SendToICSDelayed P((char *s, long msdelay));
151 void SendMoveToICS P((ChessMove moveType, int fromX, int fromY,
153 void InitPosition P((int redraw));
154 void HandleMachineMove P((char *message, ChessProgramState *cps));
155 int AutoPlayOneMove P((void));
156 int LoadGameOneMove P((ChessMove readAhead));
157 int LoadGameFromFile P((char *filename, int n, char *title, int useList));
158 int LoadPositionFromFile P((char *filename, int n, char *title));
159 int SavePositionToFile P((char *filename));
160 void ApplyMove P((int fromX, int fromY, int toX, int toY, int promoChar,
162 void MakeMove P((int fromX, int fromY, int toX, int toY, int promoChar));
163 void ShowMove P((int fromX, int fromY, int toX, int toY));
164 void FinishMove P((ChessMove moveType, int fromX, int fromY, int toX, int toY,
165 /*char*/int promoChar));
166 void BackwardInner P((int target));
167 void ForwardInner P((int target));
168 void GameEnds P((ChessMove result, char *resultDetails, int whosays));
169 void EditPositionDone P((void));
170 void PrintOpponents P((FILE *fp));
171 void PrintPosition P((FILE *fp, int move));
172 void StartChessProgram P((ChessProgramState *cps));
173 void SendToProgram P((char *message, ChessProgramState *cps));
174 void SendMoveToProgram P((int moveNum, ChessProgramState *cps));
175 void ReceiveFromProgram P((InputSourceRef isr, VOIDSTAR closure,
176 char *buf, int count, int error));
177 void SendTimeControl P((ChessProgramState *cps,
178 int mps, long tc, int inc, int sd, int st));
179 char *TimeControlTagValue P((void));
180 void Attention P((ChessProgramState *cps));
181 void FeedMovesToProgram P((ChessProgramState *cps, int upto));
182 void ResurrectChessProgram P((void));
183 void DisplayComment P((int moveNumber, char *text));
184 void DisplayMove P((int moveNumber));
185 void DisplayAnalysis P((void));
187 void ParseGameHistory P((char *game));
188 void ParseBoard12 P((char *string));
189 void StartClocks P((void));
190 void SwitchClocks P((void));
191 void StopClocks P((void));
192 void ResetClocks P((void));
193 char *PGNDate P((void));
194 void SetGameInfo P((void));
195 Boolean ParseFEN P((Board board, int *blackPlaysFirst, char *fen));
196 int RegisterMove P((void));
197 void MakeRegisteredMove P((void));
198 void TruncateGame P((void));
199 int looking_at P((char *, int *, char *));
200 void CopyPlayerNameIntoFileName P((char **, char *));
201 char *SavePart P((char *));
202 int SaveGameOldStyle P((FILE *));
203 int SaveGamePGN P((FILE *));
204 void GetTimeMark P((TimeMark *));
205 long SubtractTimeMarks P((TimeMark *, TimeMark *));
206 int CheckFlags P((void));
207 long NextTickLength P((long));
208 void CheckTimeControl P((void));
209 void show_bytes P((FILE *, char *, int));
210 int string_to_rating P((char *str));
211 void ParseFeatures P((char* args, ChessProgramState *cps));
212 void InitBackEnd3 P((void));
213 void FeatureDone P((ChessProgramState* cps, int val));
214 void InitChessProgram P((ChessProgramState *cps));
217 extern void ConsoleCreate();
\r
219 extern int tinyLayout, smallLayout;
220 static ChessProgramStats programStats;
222 /* States for ics_getting_history */
224 #define H_REQUESTED 1
225 #define H_GOT_REQ_HEADER 2
226 #define H_GOT_UNREQ_HEADER 3
227 #define H_GETTING_MOVES 4
228 #define H_GOT_UNWANTED_HEADER 5
230 /* whosays values for GameEnds */
237 /* Maximum number of games in a cmail message */
238 #define CMAIL_MAX_GAMES 20
240 /* Different types of move when calling RegisterMove */
242 #define CMAIL_RESIGN 1
244 #define CMAIL_ACCEPT 3
246 /* Different types of result to remember for each game */
247 #define CMAIL_NOT_RESULT 0
248 #define CMAIL_OLD_RESULT 1
249 #define CMAIL_NEW_RESULT 2
251 /* Telnet protocol constants */
261 /* Fake up flags for now, as we aren't keeping track of castling
266 int flags = F_ALL_CASTLE_OK;
267 if ((index % 2) == 0) flags |= F_WHITE_ON_MOVE;
268 switch (gameInfo.variant) {
270 case VariantGiveaway:
271 flags |= F_IGNORE_CHECK;
272 flags &= ~F_ALL_CASTLE_OK;
275 flags |= F_IGNORE_CHECK | F_ATOMIC_CAPTURE;
277 case VariantKriegspiel:
278 flags |= F_KRIEGSPIEL_CAPTURE;
280 case VariantNoCastle:
281 flags &= ~F_ALL_CASTLE_OK;
289 FILE *gameFileFP, *debugFP;
291 char cmailMove[CMAIL_MAX_GAMES][MOVE_LEN], cmailMsg[MSG_SIZ];
292 char bookOutput[MSG_SIZ*10], thinkOutput[MSG_SIZ*10], lastHint[MSG_SIZ];
293 char thinkOutput1[MSG_SIZ*10];
295 ChessProgramState first, second;
297 /* premove variables */
300 int premoveFromX = 0;
301 int premoveFromY = 0;
302 int premovePromoChar = 0;
304 Boolean alarmSounded;
305 /* end premove variables */
307 char *ics_prefix = "$";
308 ics_type = ICS_GENERIC;
\r
310 int currentMove = 0, forwardMostMove = 0, backwardMostMove = 0;
311 int pauseExamForwardMostMove = 0;
312 int nCmailGames = 0, nCmailResults = 0, nCmailMovesRegistered = 0;
313 int cmailMoveRegistered[CMAIL_MAX_GAMES], cmailResult[CMAIL_MAX_GAMES];
314 int cmailMsgLoaded = FALSE, cmailMailedMove = FALSE;
315 int cmailOldMove = -1, firstMove = TRUE, flipView = FALSE;
316 int blackPlaysFirst = FALSE, startedFromSetupPosition = FALSE;
317 int searchTime = 0, pausing = FALSE, pauseExamInvalid = FALSE;
318 int whiteFlag = FALSE, blackFlag = FALSE;
319 int userOfferedDraw = FALSE;
320 int ics_user_moved = 0, ics_gamenum = -1, ics_getting_history = H_FALSE;
321 int matchMode = FALSE, hintRequested = FALSE, bookRequested = FALSE;
322 int cmailMoveType[CMAIL_MAX_GAMES];
323 long ics_clock_paused = 0;
324 ProcRef icsPR = NoProc, cmailPR = NoProc;
325 InputSourceRef telnetISR = NULL, fromUserISR = NULL, cmailISR = NULL;
326 GameMode gameMode = BeginningOfGame;
327 char moveList[MAX_MOVES][MOVE_LEN], parseList[MAX_MOVES][MOVE_LEN * 2];
328 char *commentList[MAX_MOVES], *cmailCommentList[CMAIL_MAX_GAMES];
329 char white_holding[64], black_holding[64];
330 TimeMark lastNodeCountTime;
331 long lastNodeCount=0;
332 int have_sent_ICS_logon = 0;
334 long whiteTimeRemaining, blackTimeRemaining, timeControl, timeIncrement;
335 long timeRemaining[2][MAX_MOVES];
337 TimeMark programStartTime;
338 char ics_handle[MSG_SIZ];
339 int have_set_title = 0;
341 /* animateTraining preserves the state of appData.animate
342 * when Training mode is activated. This allows the
343 * response to be animated when appData.animate == TRUE and
344 * appData.animateDragging == TRUE.
346 Boolean animateTraining;
352 Board boards[MAX_MOVES];
353 Board initialPosition = {
354 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
355 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
356 { WhitePawn, WhitePawn, WhitePawn, WhitePawn,
357 WhitePawn, WhitePawn, WhitePawn, WhitePawn },
358 { EmptySquare, EmptySquare, EmptySquare, EmptySquare,
359 EmptySquare, EmptySquare, EmptySquare, EmptySquare },
360 { EmptySquare, EmptySquare, EmptySquare, EmptySquare,
361 EmptySquare, EmptySquare, EmptySquare, EmptySquare },
362 { EmptySquare, EmptySquare, EmptySquare, EmptySquare,
363 EmptySquare, EmptySquare, EmptySquare, EmptySquare },
364 { EmptySquare, EmptySquare, EmptySquare, EmptySquare,
365 EmptySquare, EmptySquare, EmptySquare, EmptySquare },
366 { BlackPawn, BlackPawn, BlackPawn, BlackPawn,
367 BlackPawn, BlackPawn, BlackPawn, BlackPawn },
368 { BlackRook, BlackKnight, BlackBishop, BlackQueen,
369 BlackKing, BlackBishop, BlackKnight, BlackRook }
371 Board twoKingsPosition = {
372 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
373 WhiteKing, WhiteKing, WhiteKnight, WhiteRook },
374 { WhitePawn, WhitePawn, WhitePawn, WhitePawn,
375 WhitePawn, WhitePawn, WhitePawn, WhitePawn },
376 { EmptySquare, EmptySquare, EmptySquare, EmptySquare,
377 EmptySquare, EmptySquare, EmptySquare, EmptySquare },
378 { EmptySquare, EmptySquare, EmptySquare, EmptySquare,
379 EmptySquare, EmptySquare, EmptySquare, EmptySquare },
380 { EmptySquare, EmptySquare, EmptySquare, EmptySquare,
381 EmptySquare, EmptySquare, EmptySquare, EmptySquare },
382 { EmptySquare, EmptySquare, EmptySquare, EmptySquare,
383 EmptySquare, EmptySquare, EmptySquare, EmptySquare },
384 { BlackPawn, BlackPawn, BlackPawn, BlackPawn,
385 BlackPawn, BlackPawn, BlackPawn, BlackPawn },
386 { BlackRook, BlackKnight, BlackBishop, BlackQueen,
387 BlackKing, BlackKing, BlackKnight, BlackRook }
391 /* Convert str to a rating. Checks for special cases of "----",
392 "++++", etc. Also strips ()'s */
394 string_to_rating(str)
397 while(*str && !isdigit(*str)) ++str;
399 return 0; /* One of the special "no rating" cases */
407 /* Init programStats */
408 programStats.movelist[0] = 0;
409 programStats.depth = 0;
410 programStats.nr_moves = 0;
411 programStats.moves_left = 0;
412 programStats.nodes = 0;
413 programStats.time = 100;
414 programStats.score = 0;
415 programStats.got_only_move = 0;
416 programStats.got_fail = 0;
417 programStats.line_is_book = 0;
423 int matched, min, sec;
425 GetTimeMark(&programStartTime);
428 programStats.ok_to_send = 1;
429 programStats.seen_stat = 0;
432 * Initialize game list
438 * Internet chess server status
440 if (appData.icsActive) {
441 appData.matchMode = FALSE;
442 appData.matchGames = 0;
444 appData.noChessProgram = !appData.zippyPlay;
446 appData.zippyPlay = FALSE;
447 appData.zippyTalk = FALSE;
448 appData.noChessProgram = TRUE;
450 if (*appData.icsHelper != NULLCHAR) {
451 appData.useTelnet = TRUE;
452 appData.telnetProgram = appData.icsHelper;
455 appData.zippyTalk = appData.zippyPlay = FALSE;
459 * Parse timeControl resource
461 if (!ParseTimeControl(appData.timeControl, appData.timeIncrement,
462 appData.movesPerSession)) {
464 sprintf(buf, _("bad timeControl option %s"), appData.timeControl);
465 DisplayFatalError(buf, 0, 2);
469 * Parse searchTime resource
471 if (*appData.searchTime != NULLCHAR) {
472 matched = sscanf(appData.searchTime, "%d:%d", &min, &sec);
474 searchTime = min * 60;
475 } else if (matched == 2) {
476 searchTime = min * 60 + sec;
479 sprintf(buf, _("bad searchTime option %s"), appData.searchTime);
480 DisplayFatalError(buf, 0, 2);
484 first.which = "first";
485 second.which = "second";
486 first.maybeThinking = second.maybeThinking = FALSE;
487 first.pr = second.pr = NoProc;
488 first.isr = second.isr = NULL;
489 first.sendTime = second.sendTime = 2;
490 first.sendDrawOffers = 1;
491 if (appData.firstPlaysBlack) {
492 first.twoMachinesColor = "black\n";
493 second.twoMachinesColor = "white\n";
495 first.twoMachinesColor = "white\n";
496 second.twoMachinesColor = "black\n";
498 first.program = appData.firstChessProgram;
499 second.program = appData.secondChessProgram;
500 first.host = appData.firstHost;
501 second.host = appData.secondHost;
502 first.dir = appData.firstDirectory;
503 second.dir = appData.secondDirectory;
504 first.other = &second;
505 second.other = &first;
506 first.initString = appData.initString;
507 second.initString = appData.secondInitString;
508 first.computerString = appData.firstComputerString;
509 second.computerString = appData.secondComputerString;
510 first.useSigint = second.useSigint = TRUE;
511 first.useSigterm = second.useSigterm = TRUE;
512 first.reuse = appData.reuseFirst;
513 second.reuse = appData.reuseSecond;
514 first.useSetboard = second.useSetboard = FALSE;
515 first.useSAN = second.useSAN = FALSE;
516 first.usePing = second.usePing = FALSE;
517 first.lastPing = second.lastPing = 0;
518 first.lastPong = second.lastPong = 0;
519 first.usePlayother = second.usePlayother = FALSE;
520 first.useColors = second.useColors = TRUE;
521 first.useUsermove = second.useUsermove = FALSE;
522 first.sendICS = second.sendICS = FALSE;
523 first.sendName = second.sendName = appData.icsActive;
524 first.sdKludge = second.sdKludge = FALSE;
525 first.stKludge = second.stKludge = FALSE;
526 TidyProgramName(first.program, first.host, first.tidy);
527 TidyProgramName(second.program, second.host, second.tidy);
528 first.matchWins = second.matchWins = 0;
529 strcpy(first.variants, appData.variant);
530 strcpy(second.variants, appData.variant);
531 first.analysisSupport = second.analysisSupport = 2; /* detect */
532 first.analyzing = second.analyzing = FALSE;
533 first.initDone = second.initDone = FALSE;
535 if (appData.firstProtocolVersion > PROTOVER ||
536 appData.firstProtocolVersion < 1) {
538 sprintf(buf, _("protocol version %d not supported"),
539 appData.firstProtocolVersion);
540 DisplayFatalError(buf, 0, 2);
542 first.protocolVersion = appData.firstProtocolVersion;
545 if (appData.secondProtocolVersion > PROTOVER ||
546 appData.secondProtocolVersion < 1) {
548 sprintf(buf, _("protocol version %d not supported"),
549 appData.secondProtocolVersion);
550 DisplayFatalError(buf, 0, 2);
552 second.protocolVersion = appData.secondProtocolVersion;
555 if (appData.icsActive) {
556 appData.clockMode = TRUE; /* changes dynamically in ICS mode */
557 } else if (*appData.searchTime != NULLCHAR || appData.noChessProgram) {
558 appData.clockMode = FALSE;
559 first.sendTime = second.sendTime = 0;
563 /* Override some settings from environment variables, for backward
564 compatibility. Unfortunately it's not feasible to have the env
565 vars just set defaults, at least in xboard. Ugh.
567 if (appData.icsActive && (appData.zippyPlay || appData.zippyTalk)) {
572 if (appData.noChessProgram) {
573 programVersion = (char*) malloc(5 + strlen(PRODUCT) + strlen(VERSION)
574 + strlen(PATCHLEVEL));
575 sprintf(programVersion, "%s %s.%s", PRODUCT, VERSION, PATCHLEVEL);
579 while (*q != ' ' && *q != NULLCHAR) q++;
581 while (p > first.program && *(p-1) != '/') p--;
582 programVersion = (char*) malloc(8 + strlen(PRODUCT) + strlen(VERSION)
583 + strlen(PATCHLEVEL) + (q - p));
584 sprintf(programVersion, "%s %s.%s + ", PRODUCT, VERSION, PATCHLEVEL);
585 strncat(programVersion, p, q - p);
588 if (!appData.icsActive) {
590 /* Check for variants that are supported only in ICS mode,
591 or not at all. Some that are accepted here nevertheless
592 have bugs; see comments below.
594 VariantClass variant = StringToVariant(appData.variant);
596 case VariantBughouse: /* need four players and two boards */
597 case VariantKriegspiel: /* need to hide pieces and move details */
598 case VariantFischeRandom: /* castling doesn't work, shuffle not done */
599 sprintf(buf, _("Variant %s supported only in ICS mode"), appData.variant);
600 DisplayFatalError(buf, 0, 2);
604 case VariantLoadable:
614 sprintf(buf, _("Unknown variant name %s"), appData.variant);
615 DisplayFatalError(buf, 0, 2);
618 case VariantNormal: /* definitely works! */
619 case VariantWildCastle: /* pieces not automatically shuffled */
620 case VariantNoCastle: /* pieces not automatically shuffled */
621 case VariantCrazyhouse: /* holdings not shown,
622 offboard interposition not understood */
623 case VariantLosers: /* should work except for win condition,
624 and doesn't know captures are mandatory */
625 case VariantSuicide: /* should work except for win condition,
626 and doesn't know captures are mandatory */
627 case VariantGiveaway: /* should work except for win condition,
628 and doesn't know captures are mandatory */
629 case VariantTwoKings: /* should work */
630 case VariantAtomic: /* should work except for win condition */
631 case Variant3Check: /* should work except for win condition */
632 case VariantShatranj: /* might work if TestLegality is off */
639 ParseTimeControl(tc, ti, mps)
644 int matched, min, sec;
646 matched = sscanf(tc, "%d:%d", &min, &sec);
648 timeControl = min * 60 * 1000;
649 } else if (matched == 2) {
650 timeControl = (min * 60 + sec) * 1000;
656 timeIncrement = ti * 1000; /* convert to ms */
660 movesPerSession = mps;
668 if (appData.debugMode) {
669 fprintf(debugFP, "%s\n", programVersion);
672 if (appData.matchGames > 0) {
673 appData.matchMode = TRUE;
674 } else if (appData.matchMode) {
675 appData.matchGames = 1;
678 if (appData.noChessProgram || first.protocolVersion == 1) {
681 /* kludge: allow timeout for initial "feature" commands */
683 DisplayMessage("", "Starting chess program");
684 ScheduleDelayedEvent(InitBackEnd3, FEATURE_TIMEOUT);
689 InitBackEnd3 P((void))
691 GameMode initialMode;
695 InitChessProgram(&first);
\r
698 /* Make a console window if needed */
\r
699 if (appData.icsActive) ConsoleCreate();
\r
702 if (appData.icsActive) {
705 if (*appData.icsCommPort != NULLCHAR) {
706 sprintf(buf, _("Could not open comm port %s"),
707 appData.icsCommPort);
709 sprintf(buf, _("Could not connect to host %s, port %s"),
710 appData.icsHost, appData.icsPort);
712 DisplayFatalError(buf, err, 1);
717 AddInputSource(icsPR, FALSE, read_from_ics, &telnetISR);
719 AddInputSource(NoProc, FALSE, read_from_player, &fromUserISR);
720 } else if (appData.noChessProgram) {
726 if (*appData.cmailGameName != NULLCHAR) {
728 OpenLoopback(&cmailPR);
730 AddInputSource(cmailPR, FALSE, CmailSigHandlerCallBack, &cmailISR);
734 DisplayMessage("", "");
735 if (StrCaseCmp(appData.initialMode, "") == 0) {
736 initialMode = BeginningOfGame;
737 } else if (StrCaseCmp(appData.initialMode, "TwoMachines") == 0) {
738 initialMode = TwoMachinesPlay;
739 } else if (StrCaseCmp(appData.initialMode, "AnalyzeFile") == 0) {
740 initialMode = AnalyzeFile;
741 } else if (StrCaseCmp(appData.initialMode, "Analysis") == 0) {
742 initialMode = AnalyzeMode;
743 } else if (StrCaseCmp(appData.initialMode, "MachineWhite") == 0) {
744 initialMode = MachinePlaysWhite;
745 } else if (StrCaseCmp(appData.initialMode, "MachineBlack") == 0) {
746 initialMode = MachinePlaysBlack;
747 } else if (StrCaseCmp(appData.initialMode, "EditGame") == 0) {
748 initialMode = EditGame;
749 } else if (StrCaseCmp(appData.initialMode, "EditPosition") == 0) {
750 initialMode = EditPosition;
751 } else if (StrCaseCmp(appData.initialMode, "Training") == 0) {
752 initialMode = Training;
754 sprintf(buf, _("Unknown initialMode %s"), appData.initialMode);
755 DisplayFatalError(buf, 0, 2);
759 if (appData.matchMode) {
760 /* Set up machine vs. machine match */
761 if (appData.noChessProgram) {
762 DisplayFatalError(_("Can't have a match with no chess programs"),
768 if (*appData.loadGameFile != NULLCHAR) {
769 if (!LoadGameFromFile(appData.loadGameFile,
770 appData.loadGameIndex,
771 appData.loadGameFile, FALSE)) {
772 DisplayFatalError(_("Bad game file"), 0, 1);
775 } else if (*appData.loadPositionFile != NULLCHAR) {
776 if (!LoadPositionFromFile(appData.loadPositionFile,
777 appData.loadPositionIndex,
778 appData.loadPositionFile)) {
779 DisplayFatalError(_("Bad position file"), 0, 1);
784 } else if (*appData.cmailGameName != NULLCHAR) {
785 /* Set up cmail mode */
786 ReloadCmailMsgEvent(TRUE);
788 /* Set up other modes */
789 if (initialMode == AnalyzeFile) {
790 if (*appData.loadGameFile == NULLCHAR) {
791 DisplayFatalError(_("AnalyzeFile mode requires a game file"), 0, 1);
795 if (*appData.loadGameFile != NULLCHAR) {
796 (void) LoadGameFromFile(appData.loadGameFile,
797 appData.loadGameIndex,
798 appData.loadGameFile, TRUE);
799 } else if (*appData.loadPositionFile != NULLCHAR) {
800 (void) LoadPositionFromFile(appData.loadPositionFile,
801 appData.loadPositionIndex,
802 appData.loadPositionFile);
804 if (initialMode == AnalyzeMode) {
805 if (appData.noChessProgram) {
806 DisplayFatalError(_("Analysis mode requires a chess engine"), 0, 2);
809 if (appData.icsActive) {
810 DisplayFatalError(_("Analysis mode does not work with ICS mode"),0,2);
814 } else if (initialMode == AnalyzeFile) {
815 ShowThinkingEvent(TRUE);
817 AnalysisPeriodicEvent(1);
818 } else if (initialMode == MachinePlaysWhite) {
819 if (appData.noChessProgram) {
820 DisplayFatalError(_("MachineWhite mode requires a chess engine"),
824 if (appData.icsActive) {
825 DisplayFatalError(_("MachineWhite mode does not work with ICS mode"),
830 } else if (initialMode == MachinePlaysBlack) {
831 if (appData.noChessProgram) {
832 DisplayFatalError(_("MachineBlack mode requires a chess engine"),
836 if (appData.icsActive) {
837 DisplayFatalError(_("MachineBlack mode does not work with ICS mode"),
842 } else if (initialMode == TwoMachinesPlay) {
843 if (appData.noChessProgram) {
844 DisplayFatalError(_("TwoMachines mode requires a chess engine"),
848 if (appData.icsActive) {
849 DisplayFatalError(_("TwoMachines mode does not work with ICS mode"),
854 } else if (initialMode == EditGame) {
856 } else if (initialMode == EditPosition) {
858 } else if (initialMode == Training) {
859 if (*appData.loadGameFile == NULLCHAR) {
860 DisplayFatalError(_("Training mode requires a game file"), 0, 2);
869 * Establish will establish a contact to a remote host.port.
870 * Sets icsPR to a ProcRef for a process (or pseudo-process)
871 * used to talk to the host.
872 * Returns 0 if okay, error code if not.
879 if (*appData.icsCommPort != NULLCHAR) {
880 /* Talk to the host through a serial comm port */
881 return OpenCommPort(appData.icsCommPort, &icsPR);
883 } else if (*appData.gateway != NULLCHAR) {
884 if (*appData.remoteShell == NULLCHAR) {
885 /* Use the rcmd protocol to run telnet program on a gateway host */
886 sprintf(buf, "%s %s %s",
887 appData.telnetProgram, appData.icsHost, appData.icsPort);
888 return OpenRcmd(appData.gateway, appData.remoteUser, buf, &icsPR);
891 /* Use the rsh program to run telnet program on a gateway host */
892 if (*appData.remoteUser == NULLCHAR) {
893 sprintf(buf, "%s %s %s %s %s", appData.remoteShell,
894 appData.gateway, appData.telnetProgram,
895 appData.icsHost, appData.icsPort);
897 sprintf(buf, "%s %s -l %s %s %s %s",
898 appData.remoteShell, appData.gateway,
899 appData.remoteUser, appData.telnetProgram,
900 appData.icsHost, appData.icsPort);
902 return StartChildProcess(buf, "", &icsPR);
905 } else if (appData.useTelnet) {
906 return OpenTelnet(appData.icsHost, appData.icsPort, &icsPR);
909 /* TCP socket interface differs somewhat between
910 Unix and NT; handle details in the front end.
912 return OpenTCP(appData.icsHost, appData.icsPort, &icsPR);
917 show_bytes(fp, buf, count)
923 if (*buf < 040 || *(unsigned char *) buf > 0177) {
924 fprintf(fp, "\\%03o", *buf & 0xff);
933 /* Returns an errno value */
935 OutputMaybeTelnet(pr, message, count, outError)
941 char buf[8192], *p, *q, *buflim;
942 int left, newcount, outcount;
944 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet ||
945 *appData.gateway != NULLCHAR) {
946 if (appData.debugMode) {
947 fprintf(debugFP, ">ICS: ");
948 show_bytes(debugFP, message, count);
949 fprintf(debugFP, "\n");
951 return OutputToProcess(pr, message, count, outError);
954 buflim = &buf[sizeof(buf)-1]; /* allow 1 byte for expanding last char */
961 if (appData.debugMode) {
962 fprintf(debugFP, ">ICS: ");
963 show_bytes(debugFP, buf, newcount);
964 fprintf(debugFP, "\n");
966 outcount = OutputToProcess(pr, buf, newcount, outError);
967 if (outcount < newcount) return -1; /* to be sure */
974 } else if (((unsigned char) *p) == TN_IAC) {
975 *q++ = (char) TN_IAC;
982 if (appData.debugMode) {
983 fprintf(debugFP, ">ICS: ");
984 show_bytes(debugFP, buf, newcount);
985 fprintf(debugFP, "\n");
987 outcount = OutputToProcess(pr, buf, newcount, outError);
988 if (outcount < newcount) return -1; /* to be sure */
993 read_from_player(isr, closure, message, count, error)
1000 int outError, outCount;
1001 static int gotEof = 0;
1003 /* Pass data read from player on to ICS */
1006 outCount = OutputMaybeTelnet(icsPR, message, count, &outError);
1007 if (outCount < count) {
1008 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1010 } else if (count < 0) {
1011 RemoveInputSource(isr);
1012 DisplayFatalError(_("Error reading from keyboard"), error, 1);
1013 } else if (gotEof++ > 0) {
1014 RemoveInputSource(isr);
1015 DisplayFatalError(_("Got end of file from keyboard"), 0, 0);
1023 int count, outCount, outError;
1025 if (icsPR == NULL) return;
1028 outCount = OutputMaybeTelnet(icsPR, s, count, &outError);
1029 if (outCount < count) {
1030 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1034 /* This is used for sending logon scripts to the ICS. Sending
1035 without a delay causes problems when using timestamp on ICC
1036 (at least on my machine). */
1038 SendToICSDelayed(s,msdelay)
1042 int count, outCount, outError;
1044 if (icsPR == NULL) return;
1047 if (appData.debugMode) {
1048 fprintf(debugFP, ">ICS: ");
1049 show_bytes(debugFP, s, count);
1050 fprintf(debugFP, "\n");
1052 outCount = OutputToProcessDelayed(icsPR, s, count, &outError,
1054 if (outCount < count) {
1055 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1060 /* Remove all highlighting escape sequences in s
1061 Also deletes any suffix starting with '('
1064 StripHighlightAndTitle(s)
1067 static char retbuf[MSG_SIZ];
1070 while (*s != NULLCHAR) {
1071 while (*s == '\033') {
1072 while (*s != NULLCHAR && !isalpha(*s)) s++;
1073 if (*s != NULLCHAR) s++;
1075 while (*s != NULLCHAR && *s != '\033') {
1076 if (*s == '(' || *s == '[') {
1087 /* Remove all highlighting escape sequences in s */
1092 static char retbuf[MSG_SIZ];
1095 while (*s != NULLCHAR) {
1096 while (*s == '\033') {
1097 while (*s != NULLCHAR && !isalpha(*s)) s++;
1098 if (*s != NULLCHAR) s++;
1100 while (*s != NULLCHAR && *s != '\033') {
1108 char *variantNames[] = VARIANT_NAMES;
1113 return variantNames[v];
1117 /* Identify a variant from the strings the chess servers use or the
1118 PGN Variant tag names we use. */
1125 VariantClass v = VariantNormal;
1126 int i, found = FALSE;
1131 for (i=0; i<sizeof(variantNames)/sizeof(char*); i++) {
1132 if (StrCaseStr(e, variantNames[i])) {
1133 v = (VariantClass) i;
1140 if ((StrCaseStr(e, "fischer") && StrCaseStr(e, "random"))
1141 || StrCaseStr(e, "wild/fr")) {
1142 v = VariantFischeRandom;
1143 } else if ((i = 4, p = StrCaseStr(e, "wild")) ||
1144 (i = 1, p = StrCaseStr(e, "w"))) {
1146 while (*p && (isspace(*p) || *p == '(' || *p == '/')) p++;
1153 case 0: /* FICS only, actually */
1155 /* Castling legal even if K starts on d-file */
1156 v = VariantWildCastle;
1161 /* Castling illegal even if K & R happen to start in
1162 normal positions. */
1163 v = VariantNoCastle;
1176 /* Castling legal iff K & R start in normal positions */
1182 /* Special wilds for position setup; unclear what to do here */
1183 v = VariantLoadable;
1186 /* Bizarre ICC game */
1187 v = VariantTwoKings;
1190 v = VariantKriegspiel;
1196 v = VariantFischeRandom;
1199 v = VariantCrazyhouse;
1202 v = VariantBughouse;
1208 /* Not quite the same as FICS suicide! */
1209 v = VariantGiveaway;
1215 v = VariantShatranj;
1218 /* Temporary names for future ICC types. The name *will* change in
1219 the next xboard/WinBoard release after ICC defines it. */
1246 /* Found "wild" or "w" in the string but no number;
1247 must assume it's normal chess. */
1251 sprintf(buf, "Unknown wild type %d", wnum);
1252 DisplayError(buf, 0);
1258 if (appData.debugMode) {
1259 fprintf(debugFP, _("recognized '%s' (%d) as variant %s\n"),
1260 e, wnum, VariantName(v));
1265 static int leftover_start = 0, leftover_len = 0;
1266 char star_match[STAR_MATCH_N][MSG_SIZ];
1268 /* Test whether pattern is present at &buf[*index]; if so, return TRUE,
1269 advance *index beyond it, and set leftover_start to the new value of
1270 *index; else return FALSE. If pattern contains the character '*', it
1271 matches any sequence of characters not containing '\r', '\n', or the
1272 character following the '*' (if any), and the matched sequence(s) are
1273 copied into star_match.
1276 looking_at(buf, index, pattern)
1281 char *bufp = &buf[*index], *patternp = pattern;
1283 char *matchp = star_match[0];
1286 if (*patternp == NULLCHAR) {
1287 *index = leftover_start = bufp - buf;
1291 if (*bufp == NULLCHAR) return FALSE;
1292 if (*patternp == '*') {
1293 if (*bufp == *(patternp + 1)) {
1295 matchp = star_match[++star_count];
1299 } else if (*bufp == '\n' || *bufp == '\r') {
1301 if (*patternp == NULLCHAR)
1306 *matchp++ = *bufp++;
1310 if (*patternp != *bufp) return FALSE;
1317 SendToPlayer(data, length)
1321 int error, outCount;
1322 outCount = OutputToProcess(NoProc, data, length, &error);
1323 if (outCount < length) {
1324 DisplayFatalError(_("Error writing to display"), error, 1);
1329 PackHolding(packed, holding)
1341 switch (runlength) {
1352 sprintf(q, "%d", runlength);
1364 /* Telnet protocol requests from the front end */
1366 TelnetRequest(ddww, option)
1367 unsigned char ddww, option;
1369 unsigned char msg[3];
1370 int outCount, outError;
1372 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet) return;
1374 if (appData.debugMode) {
1375 char buf1[8], buf2[8], *ddwwStr, *optionStr;
1391 sprintf(buf1, "%d", ddww);
1400 sprintf(buf2, "%d", option);
1403 fprintf(debugFP, ">%s %s ", ddwwStr, optionStr);
1408 outCount = OutputToProcess(icsPR, (char *)msg, 3, &outError);
1410 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1417 if (!appData.icsActive) return;
1418 TelnetRequest(TN_DO, TN_ECHO);
1424 if (!appData.icsActive) return;
1425 TelnetRequest(TN_DONT, TN_ECHO);
1428 static int loggedOn = FALSE;
1430 /*-- Game start info cache: --*/
1432 char gs_kind[MSG_SIZ];
1433 static char player1Name[128] = "";
1434 static char player2Name[128] = "";
1435 static int player1Rating = -1;
1436 static int player2Rating = -1;
1437 /*----------------------------*/
1440 read_from_ics(isr, closure, data, count, error)
1447 #define BUF_SIZE 8192
1448 #define STARTED_NONE 0
1449 #define STARTED_MOVES 1
1450 #define STARTED_BOARD 2
1451 #define STARTED_OBSERVE 3
1452 #define STARTED_HOLDINGS 4
1453 #define STARTED_CHATTER 5
1454 #define STARTED_COMMENT 6
1455 #define STARTED_MOVES_NOHIDE 7
1457 static int started = STARTED_NONE;
1458 static char parse[20000];
1459 static int parse_pos = 0;
1460 static char buf[BUF_SIZE + 1];
1461 static int firstTime = TRUE, intfSet = FALSE;
1462 static ColorClass curColor = ColorNormal;
1463 static ColorClass prevColor = ColorNormal;
1464 static int savingComment = FALSE;
1471 /* For zippy color lines of winboard
\r
1472 * cleanup for gcc compiler */
\r
1478 if (appData.debugMode) {
1480 fprintf(debugFP, "<ICS: ");
1481 show_bytes(debugFP, data, count);
1482 fprintf(debugFP, "\n");
1488 /* If last read ended with a partial line that we couldn't parse,
1489 prepend it to the new read and try again. */
1490 if (leftover_len > 0) {
1491 for (i=0; i<leftover_len; i++)
1492 buf[i] = buf[leftover_start + i];
1495 /* Copy in new characters, removing nulls and \r's */
1496 buf_len = leftover_len;
1497 for (i = 0; i < count; i++) {
1498 if (data[i] != NULLCHAR && data[i] != '\r')
1499 buf[buf_len++] = data[i];
1502 buf[buf_len] = NULLCHAR;
1503 next_out = leftover_len;
1507 while (i < buf_len) {
1508 /* Deal with part of the TELNET option negotiation
1509 protocol. We refuse to do anything beyond the
1510 defaults, except that we allow the WILL ECHO option,
1511 which ICS uses to turn off password echoing when we are
1512 directly connected to it. We reject this option
1513 if localLineEditing mode is on (always on in xboard)
1514 and we are talking to port 23, which might be a real
1515 telnet server that will try to keep WILL ECHO on permanently.
1517 if (buf_len - i >= 3 && (unsigned char) buf[i] == TN_IAC) {
1518 static int remoteEchoOption = FALSE; /* telnet ECHO option */
1519 unsigned char option;
1521 switch ((unsigned char) buf[++i]) {
1523 if (appData.debugMode)
1524 fprintf(debugFP, "\n<WILL ");
1525 switch (option = (unsigned char) buf[++i]) {
1527 if (appData.debugMode)
1528 fprintf(debugFP, "ECHO ");
1529 /* Reply only if this is a change, according
1530 to the protocol rules. */
1531 if (remoteEchoOption) break;
1532 if (appData.localLineEditing &&
1533 atoi(appData.icsPort) == TN_PORT) {
1534 TelnetRequest(TN_DONT, TN_ECHO);
1537 TelnetRequest(TN_DO, TN_ECHO);
1538 remoteEchoOption = TRUE;
1542 if (appData.debugMode)
1543 fprintf(debugFP, "%d ", option);
1544 /* Whatever this is, we don't want it. */
1545 TelnetRequest(TN_DONT, option);
1550 if (appData.debugMode)
1551 fprintf(debugFP, "\n<WONT ");
1552 switch (option = (unsigned char) buf[++i]) {
1554 if (appData.debugMode)
1555 fprintf(debugFP, "ECHO ");
1556 /* Reply only if this is a change, according
1557 to the protocol rules. */
1558 if (!remoteEchoOption) break;
1560 TelnetRequest(TN_DONT, TN_ECHO);
1561 remoteEchoOption = FALSE;
1564 if (appData.debugMode)
1565 fprintf(debugFP, "%d ", (unsigned char) option);
1566 /* Whatever this is, it must already be turned
1567 off, because we never agree to turn on
1568 anything non-default, so according to the
1569 protocol rules, we don't reply. */
1574 if (appData.debugMode)
1575 fprintf(debugFP, "\n<DO ");
1576 switch (option = (unsigned char) buf[++i]) {
1578 /* Whatever this is, we refuse to do it. */
1579 if (appData.debugMode)
1580 fprintf(debugFP, "%d ", option);
1581 TelnetRequest(TN_WONT, option);
1586 if (appData.debugMode)
1587 fprintf(debugFP, "\n<DONT ");
1588 switch (option = (unsigned char) buf[++i]) {
1590 if (appData.debugMode)
1591 fprintf(debugFP, "%d ", option);
1592 /* Whatever this is, we are already not doing
1593 it, because we never agree to do anything
1594 non-default, so according to the protocol
1595 rules, we don't reply. */
1600 if (appData.debugMode)
1601 fprintf(debugFP, "\n<IAC ");
1602 /* Doubled IAC; pass it through */
1606 if (appData.debugMode)
1607 fprintf(debugFP, "\n<%d ", (unsigned char) buf[i]);
1608 /* Drop all other telnet commands on the floor */
1611 if (oldi > next_out)
1612 SendToPlayer(&buf[next_out], oldi - next_out);
1618 /* OK, this at least will *usually* work */
1619 if (!loggedOn && looking_at(buf, &i, "ics%")) {
1623 if (loggedOn && !intfSet) {
1624 if (ics_type == ICS_ICC) {
1626 "/set-quietly interface %s\n/set-quietly style 12\n",
1629 } else if (ics_type == ICS_CHESSNET) {
1630 sprintf(str, "/style 12\n");
1632 strcpy(str, "alias $ @\n$set interface ");
1633 strcat(str, programVersion);
1634 strcat(str, "\n$iset startpos 1\n$iset ms 1\n");
1636 strcat(str, "$iset nohighlight 1\n");
1638 strcat(str, "$iset lock 1\n$style 12\n");
1644 if (started == STARTED_COMMENT) {
1645 /* Accumulate characters in comment */
1646 parse[parse_pos++] = buf[i];
1647 if (buf[i] == '\n') {
1648 parse[parse_pos] = NULLCHAR;
1649 AppendComment(forwardMostMove, StripHighlight(parse));
1650 started = STARTED_NONE;
1652 /* Don't match patterns against characters in chatter */
1657 if (started == STARTED_CHATTER) {
1658 if (buf[i] != '\n') {
1659 /* Don't match patterns against characters in chatter */
1663 started = STARTED_NONE;
1666 /* Kludge to deal with rcmd protocol */
1667 if (firstTime && looking_at(buf, &i, "\001*")) {
1668 DisplayFatalError(&buf[1], 0, 1);
1674 if (!loggedOn && looking_at(buf, &i, "chessclub.com")) {
1677 if (appData.debugMode)
1678 fprintf(debugFP, "ics_type %d\n", ics_type);
1681 if (!loggedOn && looking_at(buf, &i, "freechess.org")) {
1682 ics_type = ICS_FICS;
1684 if (appData.debugMode)
1685 fprintf(debugFP, "ics_type %d\n", ics_type);
1688 if (!loggedOn && looking_at(buf, &i, "chess.net")) {
1689 ics_type = ICS_CHESSNET;
1691 if (appData.debugMode)
1692 fprintf(debugFP, "ics_type %d\n", ics_type);
1697 (looking_at(buf, &i, "\"*\" is *a registered name") ||
1698 looking_at(buf, &i, "Logging you in as \"*\"") ||
1699 looking_at(buf, &i, "will be \"*\""))) {
1700 strcpy(ics_handle, star_match[0]);
1704 if (loggedOn && !have_set_title && ics_handle[0] != NULLCHAR) {
1706 sprintf(buf, "%s@%s", ics_handle, appData.icsHost);
1707 DisplayIcsInteractionTitle(buf);
1708 have_set_title = TRUE;
1711 /* skip finger notes */
1712 if (started == STARTED_NONE &&
1713 ((buf[i] == ' ' && isdigit(buf[i+1])) ||
1714 (buf[i] == '1' && buf[i+1] == '0')) &&
1715 buf[i+2] == ':' && buf[i+3] == ' ') {
1716 started = STARTED_CHATTER;
1721 /* skip formula vars */
1722 if (started == STARTED_NONE &&
1723 buf[i] == 'f' && isdigit(buf[i+1]) && buf[i+2] == ':') {
1724 started = STARTED_CHATTER;
1730 if (appData.zippyTalk || appData.zippyPlay) {
1733 /* Backup address for color zippy lines */
\r
1735 if (loggedOn == TRUE)
\r
1736 if (ZippyControl(buf, &backup) || ZippyConverse(buf, &backup) ||
\r
1737 (appData.zippyPlay && ZippyMatch(buf, &backup)));
\r
1739 if (ZippyControl(buf, &i) ||
1740 ZippyConverse(buf, &i) ||
1741 (appData.zippyPlay && ZippyMatch(buf, &i))) {
1748 if (/* Don't color "message" or "messages" output */
1749 (tkind = 5, looking_at(buf, &i, "*. * (*:*): ")) ||
1750 looking_at(buf, &i, "*. * at *:*: ") ||
1751 looking_at(buf, &i, "--* (*:*): ") ||
1752 /* Regular tells and says */
1753 (tkind = 1, looking_at(buf, &i, "* tells you: ")) ||
1754 looking_at(buf, &i, "* (your partner) tells you: ") ||
1755 looking_at(buf, &i, "* says: ") ||
1756 /* Message notifications (same color as tells) */
1757 looking_at(buf, &i, "* has left a message ") ||
1758 looking_at(buf, &i, "* just sent you a message:\n") ||
1759 /* Whispers and kibitzes */
1760 (tkind = 2, looking_at(buf, &i, "* whispers: ")) ||
1761 looking_at(buf, &i, "* kibitzes: ") ||
1763 (tkind = 3, looking_at(buf, &i, "*(*: "))) {
1765 if (tkind == 1 && strchr(star_match[0], ':')) {
1766 /* Avoid "tells you:" spoofs in channels */
1769 if (star_match[0][0] == NULLCHAR ||
1770 strchr(star_match[0], ' ') ||
1771 (tkind == 3 && strchr(star_match[1], ' '))) {
1772 /* Reject bogus matches */
1775 if (appData.colorize) {
1776 if (oldi > next_out) {
1777 SendToPlayer(&buf[next_out], oldi - next_out);
1782 Colorize(ColorTell, FALSE);
1783 curColor = ColorTell;
1786 Colorize(ColorKibitz, FALSE);
1787 curColor = ColorKibitz;
1790 p = strrchr(star_match[1], '(');
1797 Colorize(ColorChannel1, FALSE);
1798 curColor = ColorChannel1;
1800 Colorize(ColorChannel, FALSE);
1801 curColor = ColorChannel;
1805 curColor = ColorNormal;
1809 if (started == STARTED_NONE && appData.autoComment &&
1810 (gameMode == IcsObserving ||
1811 gameMode == IcsPlayingWhite ||
1812 gameMode == IcsPlayingBlack)) {
1813 parse_pos = i - oldi;
1814 memcpy(parse, &buf[oldi], parse_pos);
1815 parse[parse_pos] = NULLCHAR;
1816 started = STARTED_COMMENT;
1817 savingComment = TRUE;
1819 started = STARTED_CHATTER;
1820 savingComment = FALSE;
1827 if (looking_at(buf, &i, "* s-shouts: ") ||
1828 looking_at(buf, &i, "* c-shouts: ")) {
1829 if (appData.colorize) {
1830 if (oldi > next_out) {
1831 SendToPlayer(&buf[next_out], oldi - next_out);
1834 Colorize(ColorSShout, FALSE);
1835 curColor = ColorSShout;
1838 started = STARTED_CHATTER;
1842 if (looking_at(buf, &i, "--->")) {
1847 if (looking_at(buf, &i, "* shouts: ") ||
1848 looking_at(buf, &i, "--> ")) {
1849 if (appData.colorize) {
1850 if (oldi > next_out) {
1851 SendToPlayer(&buf[next_out], oldi - next_out);
1854 Colorize(ColorShout, FALSE);
1855 curColor = ColorShout;
1858 started = STARTED_CHATTER;
1862 if (looking_at( buf, &i, "Challenge:")) {
1863 if (appData.colorize) {
1864 if (oldi > next_out) {
1865 SendToPlayer(&buf[next_out], oldi - next_out);
1868 Colorize(ColorChallenge, FALSE);
1869 curColor = ColorChallenge;
1875 if (looking_at(buf, &i, "* offers you") ||
1876 looking_at(buf, &i, "* offers to be") ||
1877 looking_at(buf, &i, "* would like to") ||
1878 looking_at(buf, &i, "* requests to") ||
1879 looking_at(buf, &i, "Your opponent offers") ||
1880 looking_at(buf, &i, "Your opponent requests")) {
1882 if (appData.colorize) {
1883 if (oldi > next_out) {
1884 SendToPlayer(&buf[next_out], oldi - next_out);
1887 Colorize(ColorRequest, FALSE);
1888 curColor = ColorRequest;
1893 if (looking_at(buf, &i, "* (*) seeking")) {
1894 if (appData.colorize) {
1895 if (oldi > next_out) {
1896 SendToPlayer(&buf[next_out], oldi - next_out);
1899 Colorize(ColorSeek, FALSE);
1900 curColor = ColorSeek;
1905 if (looking_at(buf, &i, "\\ ")) {
1906 if (prevColor != ColorNormal) {
1907 if (oldi > next_out) {
1908 SendToPlayer(&buf[next_out], oldi - next_out);
1911 Colorize(prevColor, TRUE);
1912 curColor = prevColor;
1914 if (savingComment) {
1915 parse_pos = i - oldi;
1916 memcpy(parse, &buf[oldi], parse_pos);
1917 parse[parse_pos] = NULLCHAR;
1918 started = STARTED_COMMENT;
1920 started = STARTED_CHATTER;
1925 if (looking_at(buf, &i, "Black Strength :") ||
1926 looking_at(buf, &i, "<<< style 10 board >>>") ||
1927 looking_at(buf, &i, "<10>") ||
1928 looking_at(buf, &i, "#@#")) {
1929 /* Wrong board style */
1931 SendToICS(ics_prefix);
1932 SendToICS("set style 12\n");
1933 SendToICS(ics_prefix);
1934 SendToICS("refresh\n");
1938 if (!have_sent_ICS_logon && looking_at(buf, &i, "login:")) {
1940 have_sent_ICS_logon = 1;
1944 if (ics_getting_history != H_GETTING_MOVES /*smpos kludge*/ &&
1945 (looking_at(buf, &i, "\n<12> ") ||
1946 looking_at(buf, &i, "<12> "))) {
1948 if (oldi > next_out) {
1949 SendToPlayer(&buf[next_out], oldi - next_out);
1952 started = STARTED_BOARD;
1957 if ((started == STARTED_NONE && looking_at(buf, &i, "\n<b1> ")) ||
1958 looking_at(buf, &i, "<b1> ")) {
1959 if (oldi > next_out) {
1960 SendToPlayer(&buf[next_out], oldi - next_out);
1963 started = STARTED_HOLDINGS;
1968 if (looking_at(buf, &i, "* *vs. * *--- *")) {
1970 /* Header for a move list -- first line */
1972 switch (ics_getting_history) {
1976 case BeginningOfGame:
1977 /* User typed "moves" or "oldmoves" while we
1978 were idle. Pretend we asked for these
1979 moves and soak them up so user can step
1980 through them and/or save them.
1983 gameMode = IcsObserving;
1986 ics_getting_history = H_GOT_UNREQ_HEADER;
1988 case EditGame: /*?*/
1989 case EditPosition: /*?*/
1990 /* Should above feature work in these modes too? */
1991 /* For now it doesn't */
1992 ics_getting_history = H_GOT_UNWANTED_HEADER;
1995 ics_getting_history = H_GOT_UNWANTED_HEADER;
2000 /* Is this the right one? */
2001 if (gameInfo.white && gameInfo.black &&
2002 strcmp(gameInfo.white, star_match[0]) == 0 &&
2003 strcmp(gameInfo.black, star_match[2]) == 0) {
2005 ics_getting_history = H_GOT_REQ_HEADER;
2008 case H_GOT_REQ_HEADER:
2009 case H_GOT_UNREQ_HEADER:
2010 case H_GOT_UNWANTED_HEADER:
2011 case H_GETTING_MOVES:
2012 /* Should not happen */
2013 DisplayError(_("Error gathering move list: two headers"), 0);
2014 ics_getting_history = H_FALSE;
2018 /* Save player ratings into gameInfo if needed */
2019 if ((ics_getting_history == H_GOT_REQ_HEADER ||
2020 ics_getting_history == H_GOT_UNREQ_HEADER) &&
2021 (gameInfo.whiteRating == -1 ||
2022 gameInfo.blackRating == -1)) {
2024 gameInfo.whiteRating = string_to_rating(star_match[1]);
2025 gameInfo.blackRating = string_to_rating(star_match[3]);
2026 if (appData.debugMode)
2027 fprintf(debugFP, _("Ratings from header: W %d, B %d\n"),
2028 gameInfo.whiteRating, gameInfo.blackRating);
2033 if (looking_at(buf, &i,
2034 "* * match, initial time: * minute*, increment: * second")) {
2035 /* Header for a move list -- second line */
2036 /* Initial board will follow if this is a wild game */
2038 if (gameInfo.event != NULL) free(gameInfo.event);
2039 sprintf(str, "ICS %s %s match", star_match[0], star_match[1]);
2040 gameInfo.event = StrSave(str);
2041 gameInfo.variant = StringToVariant(gameInfo.event);
2045 if (looking_at(buf, &i, "Move ")) {
2046 /* Beginning of a move list */
2047 switch (ics_getting_history) {
2049 /* Normally should not happen */
2050 /* Maybe user hit reset while we were parsing */
2053 /* Happens if we are ignoring a move list that is not
2054 * the one we just requested. Common if the user
2055 * tries to observe two games without turning off
2058 case H_GETTING_MOVES:
2059 /* Should not happen */
2060 DisplayError(_("Error gathering move list: nested"), 0);
2061 ics_getting_history = H_FALSE;
2063 case H_GOT_REQ_HEADER:
2064 ics_getting_history = H_GETTING_MOVES;
2065 started = STARTED_MOVES;
2067 if (oldi > next_out) {
2068 SendToPlayer(&buf[next_out], oldi - next_out);
2071 case H_GOT_UNREQ_HEADER:
2072 ics_getting_history = H_GETTING_MOVES;
2073 started = STARTED_MOVES_NOHIDE;
2076 case H_GOT_UNWANTED_HEADER:
2077 ics_getting_history = H_FALSE;
2083 if (looking_at(buf, &i, "% ") ||
2084 ((started == STARTED_MOVES || started == STARTED_MOVES_NOHIDE)
2085 && looking_at(buf, &i, "}*"))) {
2086 savingComment = FALSE;
2089 case STARTED_MOVES_NOHIDE:
2090 memcpy(&parse[parse_pos], &buf[oldi], i - oldi);
2091 parse[parse_pos + i - oldi] = NULLCHAR;
2092 ParseGameHistory(parse);
2094 if (appData.zippyPlay && first.initDone) {
2095 FeedMovesToProgram(&first, forwardMostMove);
2096 if (gameMode == IcsPlayingWhite) {
2097 if (WhiteOnMove(forwardMostMove)) {
2098 if (first.sendTime) {
2099 if (first.useColors) {
2100 SendToProgram("black\n", &first);
2102 SendTimeRemaining(&first, TRUE);
2104 if (first.useColors) {
2105 SendToProgram("white\ngo\n", &first);
2107 SendToProgram("go\n", &first);
2109 first.maybeThinking = TRUE;
2111 if (first.usePlayother) {
2112 if (first.sendTime) {
2113 SendTimeRemaining(&first, TRUE);
2115 SendToProgram("playother\n", &first);
2121 } else if (gameMode == IcsPlayingBlack) {
2122 if (!WhiteOnMove(forwardMostMove)) {
2123 if (first.sendTime) {
2124 if (first.useColors) {
2125 SendToProgram("white\n", &first);
2127 SendTimeRemaining(&first, FALSE);
2129 if (first.useColors) {
2130 SendToProgram("black\ngo\n", &first);
2132 SendToProgram("go\n", &first);
2134 first.maybeThinking = TRUE;
2136 if (first.usePlayother) {
2137 if (first.sendTime) {
2138 SendTimeRemaining(&first, FALSE);
2140 SendToProgram("playother\n", &first);
2149 if (gameMode == IcsObserving && ics_gamenum == -1) {
2150 /* Moves came from oldmoves or moves command
2151 while we weren't doing anything else.
2153 currentMove = forwardMostMove;
2154 ClearHighlights();/*!!could figure this out*/
2155 flipView = appData.flipView;
2156 DrawPosition(FALSE, boards[currentMove]);
2157 DisplayBothClocks();
2158 sprintf(str, "%s vs. %s",
2159 gameInfo.white, gameInfo.black);
2163 /* Moves were history of an active game */
2164 if (gameInfo.resultDetails != NULL) {
2165 free(gameInfo.resultDetails);
2166 gameInfo.resultDetails = NULL;
2169 HistorySet(parseList, backwardMostMove,
2170 forwardMostMove, currentMove-1);
2171 DisplayMove(currentMove - 1);
2172 if (started == STARTED_MOVES) next_out = i;
2173 started = STARTED_NONE;
2174 ics_getting_history = H_FALSE;
2177 case STARTED_OBSERVE:
2178 started = STARTED_NONE;
2179 SendToICS(ics_prefix);
2180 SendToICS("refresh\n");
2189 if ((started == STARTED_MOVES || started == STARTED_BOARD ||
2190 started == STARTED_HOLDINGS ||
2191 started == STARTED_MOVES_NOHIDE) && i >= leftover_len) {
2192 /* Accumulate characters in move list or board */
2193 parse[parse_pos++] = buf[i];
2196 /* Start of game messages. Mostly we detect start of game
2197 when the first board image arrives. On some versions
2198 of the ICS, though, we need to do a "refresh" after starting
2199 to observe in order to get the current board right away. */
2200 if (looking_at(buf, &i, "Adding game * to observation list")) {
2201 started = STARTED_OBSERVE;
2205 /* Handle auto-observe */
2206 if (appData.autoObserve &&
2207 (gameMode == IcsIdle || gameMode == BeginningOfGame) &&
2208 looking_at(buf, &i, "Game notification: * (*) vs. * (*)")) {
2210 /* Choose the player that was highlighted, if any. */
2211 if (star_match[0][0] == '\033' ||
2212 star_match[1][0] != '\033') {
2213 player = star_match[0];
2215 player = star_match[2];
2217 sprintf(str, "%sobserve %s\n",
2218 ics_prefix, StripHighlightAndTitle(player));
2221 /* Save ratings from notify string */
2222 strcpy(player1Name, star_match[0]);
2223 player1Rating = string_to_rating(star_match[1]);
2224 strcpy(player2Name, star_match[2]);
2225 player2Rating = string_to_rating(star_match[3]);
2227 if (appData.debugMode)
2229 "Ratings from 'Game notification:' %s %d, %s %d\n",
2230 player1Name, player1Rating,
2231 player2Name, player2Rating);
2236 /* Deal with automatic examine mode after a game,
2237 and with IcsObserving -> IcsExamining transition */
2238 if (looking_at(buf, &i, "Entering examine mode for game *") ||
2239 looking_at(buf, &i, "has made you an examiner of game *")) {
2241 int gamenum = atoi(star_match[0]);
2242 if ((gameMode == IcsIdle || gameMode == IcsObserving) &&
2243 gamenum == ics_gamenum) {
2244 /* We were already playing or observing this game;
2245 no need to refetch history */
2246 gameMode = IcsExamining;
2248 pauseExamForwardMostMove = forwardMostMove;
2249 } else if (currentMove < forwardMostMove) {
2250 ForwardInner(forwardMostMove);
2253 /* I don't think this case really can happen */
2254 SendToICS(ics_prefix);
2255 SendToICS("refresh\n");
2260 /* Error messages */
2261 if (ics_user_moved) {
2262 if (looking_at(buf, &i, "Illegal move") ||
2263 looking_at(buf, &i, "Not a legal move") ||
2264 looking_at(buf, &i, "Your king is in check") ||
2265 looking_at(buf, &i, "It isn't your turn") ||
2266 looking_at(buf, &i, "It is not your move")) {
2269 if (forwardMostMove > backwardMostMove) {
2270 currentMove = --forwardMostMove;
2271 DisplayMove(currentMove - 1); /* before DMError */
2272 DisplayMoveError("Illegal move (rejected by ICS)");
2273 DrawPosition(FALSE, boards[currentMove]);
2275 DisplayBothClocks();
2281 if (looking_at(buf, &i, "still have time") ||
2282 looking_at(buf, &i, "not out of time") ||
2283 looking_at(buf, &i, "either player is out of time") ||
2284 looking_at(buf, &i, "has timeseal; checking")) {
2285 /* We must have called his flag a little too soon */
2286 whiteFlag = blackFlag = FALSE;
2290 if (looking_at(buf, &i, "added * seconds to") ||
2291 looking_at(buf, &i, "seconds were added to")) {
2292 /* Update the clocks */
2293 SendToICS(ics_prefix);
2294 SendToICS("refresh\n");
2298 if (!ics_clock_paused && looking_at(buf, &i, "clock paused")) {
2299 ics_clock_paused = TRUE;
2304 if (ics_clock_paused && looking_at(buf, &i, "clock resumed")) {
2305 ics_clock_paused = FALSE;
2310 /* Grab player ratings from the Creating: message.
2311 Note we have to check for the special case when
2312 the ICS inserts things like [white] or [black]. */
2313 if (looking_at(buf, &i, "Creating: * (*)* * (*)") ||
2314 looking_at(buf, &i, "Creating: * (*) [*] * (*)")) {
2316 0 player 1 name (not necessarily white)
2318 2 empty, white, or black (IGNORED)
2319 3 player 2 name (not necessarily black)
2322 The names/ratings are sorted out when the game
2323 actually starts (below).
2325 strcpy(player1Name, StripHighlightAndTitle(star_match[0]));
2326 player1Rating = string_to_rating(star_match[1]);
2327 strcpy(player2Name, StripHighlightAndTitle(star_match[3]));
2328 player2Rating = string_to_rating(star_match[4]);
2330 if (appData.debugMode)
2332 "Ratings from 'Creating:' %s %d, %s %d\n",
2333 player1Name, player1Rating,
2334 player2Name, player2Rating);
2339 /* Improved generic start/end-of-game messages */
2340 if ((tkind=0, looking_at(buf, &i, "{Game * (* vs. *) *}*")) ||
2341 (tkind=1, looking_at(buf, &i, "{Game * (*(*) vs. *(*)) *}*"))){
2342 /* If tkind == 0: */
2343 /* star_match[0] is the game number */
2344 /* [1] is the white player's name */
2345 /* [2] is the black player's name */
2346 /* For end-of-game: */
2347 /* [3] is the reason for the game end */
2348 /* [4] is a PGN end game-token, preceded by " " */
2349 /* For start-of-game: */
2350 /* [3] begins with "Creating" or "Continuing" */
2351 /* [4] is " *" or empty (don't care). */
2352 int gamenum = atoi(star_match[0]);
2353 char *whitename, *blackname, *why, *endtoken;
2354 ChessMove endtype = (ChessMove) 0;
2357 whitename = star_match[1];
2358 blackname = star_match[2];
2359 why = star_match[3];
2360 endtoken = star_match[4];
2362 whitename = star_match[1];
2363 blackname = star_match[3];
2364 why = star_match[5];
2365 endtoken = star_match[6];
2368 /* Game start messages */
2369 if (strncmp(why, "Creating ", 9) == 0 ||
2370 strncmp(why, "Continuing ", 11) == 0) {
2371 gs_gamenum = gamenum;
2372 strcpy(gs_kind, strchr(why, ' ') + 1);
2374 if (appData.zippyPlay) {
2375 ZippyGameStart(whitename, blackname);
2381 /* Game end messages */
2382 if (gameMode == IcsIdle || gameMode == BeginningOfGame ||
2383 ics_gamenum != gamenum) {
2386 while (endtoken[0] == ' ') endtoken++;
2387 switch (endtoken[0]) {
2390 endtype = GameUnfinished;
2393 endtype = BlackWins;
2396 if (endtoken[1] == '/')
2397 endtype = GameIsDrawn;
2399 endtype = WhiteWins;
2402 GameEnds(endtype, why, GE_ICS);
2404 if (appData.zippyPlay && first.initDone) {
2405 ZippyGameEnd(endtype, why);
2406 if (first.pr == NULL) {
2407 /* Start the next process early so that we'll
2408 be ready for the next challenge */
2409 StartChessProgram(&first);
2411 /* Send "new" early, in case this command takes
2412 a long time to finish, so that we'll be ready
2413 for the next challenge. */
2420 if (looking_at(buf, &i, "Removing game * from observation") ||
2421 looking_at(buf, &i, "no longer observing game *") ||
2422 looking_at(buf, &i, "Game * (*) has no examiners")) {
2423 if (gameMode == IcsObserving &&
2424 atoi(star_match[0]) == ics_gamenum)
2429 ics_user_moved = FALSE;
2434 if (looking_at(buf, &i, "no longer examining game *")) {
2435 if (gameMode == IcsExamining &&
2436 atoi(star_match[0]) == ics_gamenum)
2440 ics_user_moved = FALSE;
2445 /* Advance leftover_start past any newlines we find,
2446 so only partial lines can get reparsed */
2447 if (looking_at(buf, &i, "\n")) {
2448 prevColor = curColor;
2449 if (curColor != ColorNormal) {
2450 if (oldi > next_out) {
2451 SendToPlayer(&buf[next_out], oldi - next_out);
2454 Colorize(ColorNormal, FALSE);
2455 curColor = ColorNormal;
2457 if (started == STARTED_BOARD) {
2458 started = STARTED_NONE;
2459 parse[parse_pos] = NULLCHAR;
2460 ParseBoard12(parse);
2463 /* Send premove here */
2464 if (appData.premove) {
2466 if (currentMove == 0 &&
2467 gameMode == IcsPlayingWhite &&
2468 appData.premoveWhite) {
2469 sprintf(str, "%s%s\n", ics_prefix,
2470 appData.premoveWhiteText);
2471 if (appData.debugMode)
2472 fprintf(debugFP, "Sending premove:\n");
2474 } else if (currentMove == 1 &&
2475 gameMode == IcsPlayingBlack &&
2476 appData.premoveBlack) {
2477 sprintf(str, "%s%s\n", ics_prefix,
2478 appData.premoveBlackText);
2479 if (appData.debugMode)
2480 fprintf(debugFP, "Sending premove:\n");
2482 } else if (gotPremove) {
2484 ClearPremoveHighlights();
2485 if (appData.debugMode)
2486 fprintf(debugFP, "Sending premove:\n");
2487 UserMoveEvent(premoveFromX, premoveFromY,
2488 premoveToX, premoveToY,
2493 /* Usually suppress following prompt */
2494 if (!(forwardMostMove == 0 && gameMode == IcsExamining)) {
2495 if (looking_at(buf, &i, "*% ")) {
2496 savingComment = FALSE;
2500 } else if (started == STARTED_HOLDINGS) {
2502 char new_piece[MSG_SIZ];
2503 started = STARTED_NONE;
2504 parse[parse_pos] = NULLCHAR;
2505 if (appData.debugMode)
2506 fprintf(debugFP, "Parsing holdings: %s\n", parse);
2507 if (sscanf(parse, " game %d", &gamenum) == 1 &&
2508 gamenum == ics_gamenum) {
2509 if (gameInfo.variant == VariantNormal) {
2510 gameInfo.variant = VariantCrazyhouse; /*temp guess*/
2511 /* Get a move list just to see the header, which
2512 will tell us whether this is really bug or zh */
2513 if (ics_getting_history == H_FALSE) {
2514 ics_getting_history = H_REQUESTED;
2515 sprintf(str, "%smoves %d\n", ics_prefix, gamenum);
2519 new_piece[0] = NULLCHAR;
2520 sscanf(parse, "game %d white [%s black [%s <- %s",
2521 &gamenum, white_holding, black_holding,
2523 white_holding[strlen(white_holding)-1] = NULLCHAR;
2524 black_holding[strlen(black_holding)-1] = NULLCHAR;
2526 if (appData.zippyPlay && first.initDone) {
2527 ZippyHoldings(white_holding, black_holding,
2531 if (tinyLayout || smallLayout) {
2532 char wh[16], bh[16];
2533 PackHolding(wh, white_holding);
2534 PackHolding(bh, black_holding);
2535 sprintf(str, "[%s-%s] %s-%s", wh, bh,
2536 gameInfo.white, gameInfo.black);
2538 sprintf(str, "%s [%s] vs. %s [%s]",
2539 gameInfo.white, white_holding,
2540 gameInfo.black, black_holding);
2542 DrawPosition(FALSE, NULL);
2545 /* Suppress following prompt */
2546 if (looking_at(buf, &i, "*% ")) {
2547 savingComment = FALSE;
2554 i++; /* skip unparsed character and loop back */
2557 if (started != STARTED_MOVES && started != STARTED_BOARD &&
2558 started != STARTED_HOLDINGS && i > next_out) {
2559 SendToPlayer(&buf[next_out], i - next_out);
2563 leftover_len = buf_len - leftover_start;
2564 /* if buffer ends with something we couldn't parse,
2565 reparse it after appending the next read */
2567 } else if (count == 0) {
2568 RemoveInputSource(isr);
2569 DisplayFatalError(_("Connection closed by ICS"), 0, 0);
2571 DisplayFatalError(_("Error reading from ICS"), error, 1);
2576 /* Board style 12 looks like this:
2578 <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
2580 * The "<12> " is stripped before it gets to this routine. The two
2581 * trailing 0's (flip state and clock ticking) are later addition, and
2582 * some chess servers may not have them, or may have only the first.
2583 * Additional trailing fields may be added in the future.
2586 #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"
2588 #define RELATION_OBSERVING_PLAYED 0
2589 #define RELATION_OBSERVING_STATIC -2 /* examined, oldmoves, or smoves */
2590 #define RELATION_PLAYING_MYMOVE 1
2591 #define RELATION_PLAYING_NOTMYMOVE -1
2592 #define RELATION_EXAMINING 2
2593 #define RELATION_ISOLATED_BOARD -3
2594 #define RELATION_STARTING_POSITION -4 /* FICS only */
2597 ParseBoard12(string)
2600 GameMode newGameMode;
2601 int gamenum, newGame, newMove, relation, basetime, increment, ics_flip = 0;
2602 int j, k, n, moveNum, white_stren, black_stren, white_time, black_time;
2603 int double_push, castle_ws, castle_wl, castle_bs, castle_bl, irrev_count;
2604 char to_play, board_chars[72];
2605 char move_str[500], str[500], elapsed_time[500];
2606 char black[32], white[32];
2608 int prevMove = currentMove;
2611 int fromX, fromY, toX, toY;
2614 fromX = fromY = toX = toY = -1;
2618 if (appData.debugMode)
2619 fprintf(debugFP, _("Parsing board: %s\n"), string);
2621 move_str[0] = NULLCHAR;
2622 elapsed_time[0] = NULLCHAR;
2623 n = sscanf(string, PATTERN, board_chars, &to_play, &double_push,
2624 &castle_ws, &castle_wl, &castle_bs, &castle_bl, &irrev_count,
2625 &gamenum, white, black, &relation, &basetime, &increment,
2626 &white_stren, &black_stren, &white_time, &black_time,
2627 &moveNum, str, elapsed_time, move_str, &ics_flip,
2631 sprintf(str, _("Failed to parse board string:\n\"%s\""), string);
2632 DisplayError(str, 0);
2636 /* Convert the move number to internal form */
2637 moveNum = (moveNum - 1) * 2;
2638 if (to_play == 'B') moveNum++;
2639 if (moveNum >= MAX_MOVES) {
2640 DisplayFatalError(_("Game too long; increase MAX_MOVES and recompile"),
2646 case RELATION_OBSERVING_PLAYED:
2647 case RELATION_OBSERVING_STATIC:
2648 if (gamenum == -1) {
2649 /* Old ICC buglet */
2650 relation = RELATION_OBSERVING_STATIC;
2652 newGameMode = IcsObserving;
2654 case RELATION_PLAYING_MYMOVE:
2655 case RELATION_PLAYING_NOTMYMOVE:
2657 ((relation == RELATION_PLAYING_MYMOVE) == (to_play == 'W')) ?
2658 IcsPlayingWhite : IcsPlayingBlack;
2660 case RELATION_EXAMINING:
2661 newGameMode = IcsExamining;
2663 case RELATION_ISOLATED_BOARD:
2665 /* Just display this board. If user was doing something else,
2666 we will forget about it until the next board comes. */
2667 newGameMode = IcsIdle;
2669 case RELATION_STARTING_POSITION:
2670 newGameMode = gameMode;
2674 /* Modify behavior for initial board display on move listing
2677 switch (ics_getting_history) {
2681 case H_GOT_REQ_HEADER:
2682 case H_GOT_UNREQ_HEADER:
2683 /* This is the initial position of the current game */
2684 gamenum = ics_gamenum;
2685 moveNum = 0; /* old ICS bug workaround */
2686 if (to_play == 'B') {
2687 startedFromSetupPosition = TRUE;
2688 blackPlaysFirst = TRUE;
2690 if (forwardMostMove == 0) forwardMostMove = 1;
2691 if (backwardMostMove == 0) backwardMostMove = 1;
2692 if (currentMove == 0) currentMove = 1;
2694 newGameMode = gameMode;
2695 relation = RELATION_STARTING_POSITION; /* ICC needs this */
2697 case H_GOT_UNWANTED_HEADER:
2698 /* This is an initial board that we don't want */
2700 case H_GETTING_MOVES:
2701 /* Should not happen */
2702 DisplayError(_("Error gathering move list: extra board"), 0);
2703 ics_getting_history = H_FALSE;
2707 /* Take action if this is the first board of a new game, or of a
2708 different game than is currently being displayed. */
2709 if (gamenum != ics_gamenum || newGameMode != gameMode ||
2710 relation == RELATION_ISOLATED_BOARD) {
2712 /* Forget the old game and get the history (if any) of the new one */
2713 if (gameMode != BeginningOfGame) {
2717 if (appData.autoRaiseBoard) BoardToTop();
2719 if (gamenum == -1) {
2720 newGameMode = IcsIdle;
2721 } else if (moveNum > 0 && newGameMode != IcsIdle &&
2722 appData.getMoveList) {
2723 /* Need to get game history */
2724 ics_getting_history = H_REQUESTED;
2725 sprintf(str, "%smoves %d\n", ics_prefix, gamenum);
2729 /* Initially flip the board to have black on the bottom if playing
2730 black or if the ICS flip flag is set, but let the user change
2731 it with the Flip View button. */
2732 flipView = appData.autoFlipView ?
2733 (newGameMode == IcsPlayingBlack) || ics_flip :
2736 /* Done with values from previous mode; copy in new ones */
2737 gameMode = newGameMode;
2739 ics_gamenum = gamenum;
2740 if (gamenum == gs_gamenum) {
2741 int klen = strlen(gs_kind);
2742 if (gs_kind[klen - 1] == '.') gs_kind[klen - 1] = NULLCHAR;
2743 sprintf(str, "ICS %s", gs_kind);
2744 gameInfo.event = StrSave(str);
2746 gameInfo.event = StrSave("ICS game");
2748 gameInfo.site = StrSave(appData.icsHost);
2749 gameInfo.date = PGNDate();
2750 gameInfo.round = StrSave("-");
2751 gameInfo.white = StrSave(white);
2752 gameInfo.black = StrSave(black);
2753 timeControl = basetime * 60 * 1000;
2754 timeIncrement = increment * 1000;
2755 movesPerSession = 0;
2756 gameInfo.timeControl = TimeControlTagValue();
2757 gameInfo.variant = StringToVariant(gameInfo.event);
2759 /* Do we have the ratings? */
2760 if (strcmp(player1Name, white) == 0 &&
2761 strcmp(player2Name, black) == 0) {
2762 if (appData.debugMode)
2763 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
2764 player1Rating, player2Rating);
2765 gameInfo.whiteRating = player1Rating;
2766 gameInfo.blackRating = player2Rating;
2767 } else if (strcmp(player2Name, white) == 0 &&
2768 strcmp(player1Name, black) == 0) {
2769 if (appData.debugMode)
2770 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
2771 player2Rating, player1Rating);
2772 gameInfo.whiteRating = player2Rating;
2773 gameInfo.blackRating = player1Rating;
2775 player1Name[0] = player2Name[0] = NULLCHAR;
2777 /* Silence shouts if requested */
2778 if (appData.quietPlay &&
2779 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)) {
2780 SendToICS(ics_prefix);
2781 SendToICS("set shout 0\n");
2785 /* Deal with midgame name changes */
2787 if (!gameInfo.white || strcmp(gameInfo.white, white) != 0) {
2788 if (gameInfo.white) free(gameInfo.white);
2789 gameInfo.white = StrSave(white);
2791 if (!gameInfo.black || strcmp(gameInfo.black, black) != 0) {
2792 if (gameInfo.black) free(gameInfo.black);
2793 gameInfo.black = StrSave(black);
2797 /* Throw away game result if anything actually changes in examine mode */
2798 if (gameMode == IcsExamining && !newGame) {
2799 gameInfo.result = GameUnfinished;
2800 if (gameInfo.resultDetails != NULL) {
2801 free(gameInfo.resultDetails);
2802 gameInfo.resultDetails = NULL;
2806 /* In pausing && IcsExamining mode, we ignore boards coming
2807 in if they are in a different variation than we are. */
2808 if (pauseExamInvalid) return;
2809 if (pausing && gameMode == IcsExamining) {
2810 if (moveNum <= pauseExamForwardMostMove) {
2811 pauseExamInvalid = TRUE;
2812 forwardMostMove = pauseExamForwardMostMove;
2817 /* Parse the board */
2818 for (k = 0; k < 8; k++)
2819 for (j = 0; j < 8; j++)
2820 board[k][j] = CharToPiece(board_chars[(7-k)*9 + j]);
2821 CopyBoard(boards[moveNum], board);
2823 startedFromSetupPosition =
2824 !CompareBoards(board, initialPosition);
2827 if (ics_getting_history == H_GOT_REQ_HEADER ||
2828 ics_getting_history == H_GOT_UNREQ_HEADER) {
2829 /* This was an initial position from a move list, not
2830 the current position */
2834 /* Update currentMove and known move number limits */
2835 newMove = newGame || moveNum > forwardMostMove;
2837 forwardMostMove = backwardMostMove = currentMove = moveNum;
2838 if (gameMode == IcsExamining && moveNum == 0) {
2839 /* Workaround for ICS limitation: we are not told the wild
2840 type when starting to examine a game. But if we ask for
2841 the move list, the move list header will tell us */
2842 ics_getting_history = H_REQUESTED;
2843 sprintf(str, "%smoves %d\n", ics_prefix, gamenum);
2846 } else if (moveNum == forwardMostMove + 1 || moveNum == forwardMostMove
2847 || (moveNum < forwardMostMove && moveNum >= backwardMostMove)) {
2848 forwardMostMove = moveNum;
2849 if (!pausing || currentMove > forwardMostMove)
2850 currentMove = forwardMostMove;
2852 /* New part of history that is not contiguous with old part */
2853 if (pausing && gameMode == IcsExamining) {
2854 pauseExamInvalid = TRUE;
2855 forwardMostMove = pauseExamForwardMostMove;
2858 forwardMostMove = backwardMostMove = currentMove = moveNum;
2859 if (gameMode == IcsExamining && moveNum > 0 && appData.getMoveList) {
2860 ics_getting_history = H_REQUESTED;
2861 sprintf(str, "%smoves %d\n", ics_prefix, gamenum);
2866 /* Update the clocks */
2867 if (strchr(elapsed_time, '.')) {
2869 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time;
2870 timeRemaining[1][moveNum] = blackTimeRemaining = black_time;
2872 /* Time is in seconds */
2873 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time * 1000;
2874 timeRemaining[1][moveNum] = blackTimeRemaining = black_time * 1000;
2879 if (appData.zippyPlay && newGame &&
2880 gameMode != IcsObserving && gameMode != IcsIdle &&
2881 gameMode != IcsExamining)
2882 ZippyFirstBoard(moveNum, basetime, increment);
2885 /* Put the move on the move list, first converting
2886 to canonical algebraic form. */
2888 if (moveNum <= backwardMostMove) {
2889 /* We don't know what the board looked like before
2891 strcpy(parseList[moveNum - 1], move_str);
2892 strcat(parseList[moveNum - 1], " ");
2893 strcat(parseList[moveNum - 1], elapsed_time);
2894 moveList[moveNum - 1][0] = NULLCHAR;
2895 } else if (ParseOneMove(move_str, moveNum - 1, &moveType,
2896 &fromX, &fromY, &toX, &toY, &promoChar)) {
2897 (void) CoordsToAlgebraic(boards[moveNum - 1],
2898 PosFlags(moveNum - 1), EP_UNKNOWN,
2899 fromY, fromX, toY, toX, promoChar,
2900 parseList[moveNum-1]);
2901 switch (MateTest(boards[moveNum], PosFlags(moveNum), EP_UNKNOWN)){
2907 strcat(parseList[moveNum - 1], "+");
2910 strcat(parseList[moveNum - 1], "#");
2913 strcat(parseList[moveNum - 1], " ");
2914 strcat(parseList[moveNum - 1], elapsed_time);
2915 /* currentMoveString is set as a side-effect of ParseOneMove */
2916 strcpy(moveList[moveNum - 1], currentMoveString);
2917 strcat(moveList[moveNum - 1], "\n");
2918 } else if (strcmp(move_str, "none") == 0) {
2919 /* Again, we don't know what the board looked like;
2920 this is really the start of the game. */
2921 parseList[moveNum - 1][0] = NULLCHAR;
2922 moveList[moveNum - 1][0] = NULLCHAR;
2923 backwardMostMove = moveNum;
2924 startedFromSetupPosition = TRUE;
2925 fromX = fromY = toX = toY = -1;
2927 /* Move from ICS was illegal!? Punt. */
2929 if (appData.testLegality && appData.debugMode) {
2930 sprintf(str, "Illegal move \"%s\" from ICS", move_str);
2931 DisplayError(str, 0);
2934 strcpy(parseList[moveNum - 1], move_str);
2935 strcat(parseList[moveNum - 1], " ");
2936 strcat(parseList[moveNum - 1], elapsed_time);
2937 moveList[moveNum - 1][0] = NULLCHAR;
2938 fromX = fromY = toX = toY = -1;
2942 /* Send move to chess program (BEFORE animating it). */
2943 if (appData.zippyPlay && !newGame && newMove &&
2944 (!appData.getMoveList || backwardMostMove == 0) && first.initDone) {
2946 if ((gameMode == IcsPlayingWhite && WhiteOnMove(moveNum)) ||
2947 (gameMode == IcsPlayingBlack && !WhiteOnMove(moveNum))) {
2948 if (moveList[moveNum - 1][0] == NULLCHAR) {
2949 sprintf(str, _("Couldn't parse move \"%s\" from ICS"),
2951 DisplayError(str, 0);
2953 if (first.sendTime) {
2954 SendTimeRemaining(&first, gameMode == IcsPlayingWhite);
2956 SendMoveToProgram(moveNum - 1, &first);
2959 if (first.useColors) {
2960 SendToProgram(gameMode == IcsPlayingWhite ?
2962 "black\ngo\n", &first);
2964 SendToProgram("go\n", &first);
2966 first.maybeThinking = TRUE;
2969 } else if (gameMode == IcsObserving || gameMode == IcsExamining) {
2970 if (moveList[moveNum - 1][0] == NULLCHAR) {
2971 sprintf(str, _("Couldn't parse move \"%s\" from ICS"), move_str);
2972 DisplayError(str, 0);
2974 SendMoveToProgram(moveNum - 1, &first);
2981 if (moveNum > 0 && !gotPremove) {
2982 /* If move comes from a remote source, animate it. If it
2983 isn't remote, it will have already been animated. */
2984 if (!pausing && !ics_user_moved && prevMove == moveNum - 1) {
2985 AnimateMove(boards[moveNum - 1], fromX, fromY, toX, toY);
2987 if (!pausing && appData.highlightLastMove) {
2988 SetHighlights(fromX, fromY, toX, toY);
2992 /* Start the clocks */
2993 whiteFlag = blackFlag = FALSE;
2994 appData.clockMode = !(basetime == 0 && increment == 0);
2996 ics_clock_paused = TRUE;
2998 } else if (ticking == 1) {
2999 ics_clock_paused = FALSE;
3001 if (gameMode == IcsIdle ||
3002 relation == RELATION_OBSERVING_STATIC ||
3003 relation == RELATION_EXAMINING ||
3005 DisplayBothClocks();
3009 /* Display opponents and material strengths */
3010 if (gameInfo.variant != VariantBughouse &&
3011 gameInfo.variant != VariantCrazyhouse) {
3012 if (tinyLayout || smallLayout) {
3013 sprintf(str, "%s(%d) %s(%d) {%d %d}",
3014 gameInfo.white, white_stren, gameInfo.black, black_stren,
3015 basetime, increment);
3017 sprintf(str, "%s (%d) vs. %s (%d) {%d %d}",
3018 gameInfo.white, white_stren, gameInfo.black, black_stren,
3019 basetime, increment);
3025 /* Display the board */
3028 if (appData.premove)
3030 ((gameMode == IcsPlayingWhite) && (WhiteOnMove(currentMove))) ||
3031 ((gameMode == IcsPlayingBlack) && (!WhiteOnMove(currentMove))))
3032 ClearPremoveHighlights();
3034 DrawPosition(FALSE, boards[currentMove]);
3035 DisplayMove(moveNum - 1);
3036 if (appData.ringBellAfterMoves && !ics_user_moved)
3040 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
3047 if (appData.icsActive && gameMode != IcsIdle && ics_gamenum > 0) {
3048 ics_getting_history = H_REQUESTED;
3049 sprintf(buf, "%smoves %d\n", ics_prefix, ics_gamenum);
3055 AnalysisPeriodicEvent(force)
3058 if (((programStats.ok_to_send == 0 || programStats.line_is_book)
3059 && !force) || !appData.periodicUpdates)
3062 /* Send . command to Crafty to collect stats */
3063 SendToProgram(".\n", &first);
3065 /* Don't send another until we get a response (this makes
3066 us stop sending to old Crafty's which don't understand
3067 the "." command (sending illegal cmds resets node count & time,
3068 which looks bad)) */
3069 programStats.ok_to_send = 0;
3073 SendMoveToProgram(moveNum, cps)
3075 ChessProgramState *cps;
3078 if (cps->useUsermove) {
3079 SendToProgram("usermove ", cps);
3083 if ((space = strchr(parseList[moveNum], ' ')) != NULL) {
3084 int len = space - parseList[moveNum];
3085 memcpy(buf, parseList[moveNum], len);
3087 buf[len] = NULLCHAR;
3089 sprintf(buf, "%s\n", parseList[moveNum]);
3091 SendToProgram(buf, cps);
3093 SendToProgram(moveList[moveNum], cps);
3098 SendMoveToICS(moveType, fromX, fromY, toX, toY)
3100 int fromX, fromY, toX, toY;
3102 char user_move[MSG_SIZ];
3106 sprintf(user_move, "say Internal error; bad moveType %d (%d,%d-%d,%d)",
3107 (int)moveType, fromX, fromY, toX, toY);
3108 DisplayError(user_move + strlen("say "), 0);
3110 case WhiteKingSideCastle:
3111 case BlackKingSideCastle:
3112 case WhiteQueenSideCastleWild:
3113 case BlackQueenSideCastleWild:
3114 sprintf(user_move, "o-o\n");
3116 case WhiteQueenSideCastle:
3117 case BlackQueenSideCastle:
3118 case WhiteKingSideCastleWild:
3119 case BlackKingSideCastleWild:
3120 sprintf(user_move, "o-o-o\n");
3122 case WhitePromotionQueen:
3123 case BlackPromotionQueen:
3124 case WhitePromotionRook:
3125 case BlackPromotionRook:
3126 case WhitePromotionBishop:
3127 case BlackPromotionBishop:
3128 case WhitePromotionKnight:
3129 case BlackPromotionKnight:
3130 case WhitePromotionKing:
3131 case BlackPromotionKing:
3132 sprintf(user_move, "%c%c%c%c=%c\n",
3133 'a' + fromX, '1' + fromY, 'a' + toX, '1' + toY,
3134 PieceToChar(PromoPiece(moveType)));
3138 sprintf(user_move, "%c@%c%c\n",
3139 ToUpper(PieceToChar((ChessSquare) fromX)),
3140 'a' + toX, '1' + toY);
3143 case WhiteCapturesEnPassant:
3144 case BlackCapturesEnPassant:
3145 case IllegalMove: /* could be a variant we don't quite understand */
3146 sprintf(user_move, "%c%c%c%c\n",
3147 'a' + fromX, '1' + fromY, 'a' + toX, '1' + toY);
3150 SendToICS(user_move);
3154 CoordsToComputerAlgebraic(rf, ff, rt, ft, promoChar, move)
3159 if (rf == DROP_RANK) {
3160 sprintf(move, "%c@%c%c\n",
3161 ToUpper(PieceToChar((ChessSquare) ff)), 'a' + ft, '1' + rt);
3163 if (promoChar == 'x' || promoChar == NULLCHAR) {
3164 sprintf(move, "%c%c%c%c\n",
3165 'a' + ff, '1' + rf, 'a' + ft, '1' + rt);
3167 sprintf(move, "%c%c%c%c%c\n",
3168 'a' + ff, '1' + rf, 'a' + ft, '1' + rt, promoChar);
3174 ProcessICSInitScript(f)
3179 while (fgets(buf, MSG_SIZ, f)) {
3180 SendToICSDelayed(buf,(long)appData.msLoginDelay);
3187 /* Parser for moves from gnuchess, ICS, or user typein box */
3189 ParseOneMove(move, moveNum, moveType, fromX, fromY, toX, toY, promoChar)
3192 ChessMove *moveType;
3193 int *fromX, *fromY, *toX, *toY;
3196 *moveType = yylexstr(moveNum, move);
3197 switch (*moveType) {
3198 case WhitePromotionQueen:
3199 case BlackPromotionQueen:
3200 case WhitePromotionRook:
3201 case BlackPromotionRook:
3202 case WhitePromotionBishop:
3203 case BlackPromotionBishop:
3204 case WhitePromotionKnight:
3205 case BlackPromotionKnight:
3206 case WhitePromotionKing:
3207 case BlackPromotionKing:
3209 case WhiteCapturesEnPassant:
3210 case BlackCapturesEnPassant:
3211 case WhiteKingSideCastle:
3212 case WhiteQueenSideCastle:
3213 case BlackKingSideCastle:
3214 case BlackQueenSideCastle:
3215 case WhiteKingSideCastleWild:
3216 case WhiteQueenSideCastleWild:
3217 case BlackKingSideCastleWild:
3218 case BlackQueenSideCastleWild:
3219 case IllegalMove: /* bug or odd chess variant */
3220 *fromX = currentMoveString[0] - 'a';
3221 *fromY = currentMoveString[1] - '1';
3222 *toX = currentMoveString[2] - 'a';
3223 *toY = currentMoveString[3] - '1';
3224 *promoChar = currentMoveString[4];
3225 if (*fromX < 0 || *fromX > 7 || *fromY < 0 || *fromY > 7 ||
3226 *toX < 0 || *toX > 7 || *toY < 0 || *toY > 7) {
3227 *fromX = *fromY = *toX = *toY = 0;
3230 if (appData.testLegality) {
3231 return (*moveType != IllegalMove);
3233 return !(fromX == fromY && toX == toY);
3238 *fromX = *moveType == WhiteDrop ?
3239 (int) CharToPiece(ToUpper(currentMoveString[0])) :
3240 (int) CharToPiece(ToLower(currentMoveString[0]));
3242 *toX = currentMoveString[2] - 'a';
3243 *toY = currentMoveString[3] - '1';
3244 *promoChar = NULLCHAR;
3248 case ImpossibleMove:
3249 case (ChessMove) 0: /* end of file */
3259 *fromX = *fromY = *toX = *toY = 0;
3260 *promoChar = NULLCHAR;
3267 InitPosition(redraw)
3270 currentMove = forwardMostMove = backwardMostMove = 0;
3271 switch (gameInfo.variant) {
3273 CopyBoard(boards[0], initialPosition);
3275 case VariantTwoKings:
3276 CopyBoard(boards[0], twoKingsPosition);
3277 startedFromSetupPosition = TRUE;
3279 case VariantWildCastle:
3280 CopyBoard(boards[0], initialPosition);
3281 /* !!?shuffle with kings guaranteed to be on d or e file */
3283 case VariantNoCastle:
3284 CopyBoard(boards[0], initialPosition);
3285 /* !!?unconstrained back-rank shuffle */
3287 case VariantFischeRandom:
3288 CopyBoard(boards[0], initialPosition);
3289 /* !!shuffle according to FR rules */
3293 DrawPosition(FALSE, boards[currentMove]);
3297 SendBoard(cps, moveNum)
3298 ChessProgramState *cps;
3301 char message[MSG_SIZ];
3303 if (cps->useSetboard) {
3304 char* fen = PositionToFEN(moveNum);
3305 sprintf(message, "setboard %s\n", fen);
3306 SendToProgram(message, cps);
3312 /* Kludge to set black to move, avoiding the troublesome and now
3313 * deprecated "black" command.
3315 if (!WhiteOnMove(moveNum)) SendToProgram("a2a3\n", cps);
3317 SendToProgram("edit\n", cps);
3318 SendToProgram("#\n", cps);
3319 for (i = BOARD_SIZE - 1; i >= 0; i--) {
3320 bp = &boards[moveNum][i][0];
3321 for (j = 0; j < BOARD_SIZE; j++, bp++) {
3322 if ((int) *bp < (int) BlackPawn) {
3323 sprintf(message, "%c%c%c\n", PieceToChar(*bp),
3325 SendToProgram(message, cps);
3330 SendToProgram("c\n", cps);
3331 for (i = BOARD_SIZE - 1; i >= 0; i--) {
3332 bp = &boards[moveNum][i][0];
3333 for (j = 0; j < BOARD_SIZE; j++, bp++) {
3334 if (((int) *bp != (int) EmptySquare)
3335 && ((int) *bp >= (int) BlackPawn)) {
3336 sprintf(message, "%c%c%c\n", ToUpper(PieceToChar(*bp)),
3338 SendToProgram(message, cps);
3343 SendToProgram(".\n", cps);
3348 IsPromotion(fromX, fromY, toX, toY)
3349 int fromX, fromY, toX, toY;
3351 return gameMode != EditPosition &&
3352 fromX >=0 && fromY >= 0 && toX >= 0 && toY >= 0 &&
3353 ((boards[currentMove][fromY][fromX] == WhitePawn && toY == 7) ||
3354 (boards[currentMove][fromY][fromX] == BlackPawn && toY == 0));
3359 PieceForSquare (x, y)
3363 if (x < 0 || x >= BOARD_SIZE || y < 0 || y >= BOARD_SIZE)
3366 return boards[currentMove][y][x];
3370 OKToStartUserMove(x, y)
3373 ChessSquare from_piece;
3376 if (matchMode) return FALSE;
3377 if (gameMode == EditPosition) return TRUE;
3379 if (x >= 0 && y >= 0)
3380 from_piece = boards[currentMove][y][x];
3382 from_piece = EmptySquare;
3384 if (from_piece == EmptySquare) return FALSE;
3386 white_piece = (int)from_piece >= (int)WhitePawn &&
3387 (int)from_piece <= (int)WhiteKing;
3390 case PlayFromGameFile:
3392 case TwoMachinesPlay:
3400 case MachinePlaysWhite:
3401 case IcsPlayingBlack:
3402 if (appData.zippyPlay) return FALSE;
3404 DisplayMoveError(_("You are playing Black"));
3409 case MachinePlaysBlack:
3410 case IcsPlayingWhite:
3411 if (appData.zippyPlay) return FALSE;
3413 DisplayMoveError(_("You are playing White"));
3419 if (!white_piece && WhiteOnMove(currentMove)) {
3420 DisplayMoveError(_("It is White's turn"));
3423 if (white_piece && !WhiteOnMove(currentMove)) {
3424 DisplayMoveError(_("It is Black's turn"));
3427 if (cmailMsgLoaded && (currentMove < cmailOldMove)) {
3428 /* Editing correspondence game history */
3429 /* Could disallow this or prompt for confirmation */
3432 if (currentMove < forwardMostMove) {
3433 /* Discarding moves */
3434 /* Could prompt for confirmation here,
3435 but I don't think that's such a good idea */
3436 forwardMostMove = currentMove;
3440 case BeginningOfGame:
3441 if (appData.icsActive) return FALSE;
3442 if (!appData.noChessProgram) {
3444 DisplayMoveError(_("You are playing White"));
3451 if (!white_piece && WhiteOnMove(currentMove)) {
3452 DisplayMoveError(_("It is White's turn"));
3455 if (white_piece && !WhiteOnMove(currentMove)) {
3456 DisplayMoveError(_("It is Black's turn"));
3465 if (currentMove != forwardMostMove && gameMode != AnalyzeMode
3466 && gameMode != AnalyzeFile && gameMode != Training) {
3467 DisplayMoveError(_("Displayed position is not current"));
3473 FILE *lastLoadGameFP = NULL, *lastLoadPositionFP = NULL;
3474 int lastLoadGameNumber = 0, lastLoadPositionNumber = 0;
3475 int lastLoadGameUseList = FALSE;
3476 char lastLoadGameTitle[MSG_SIZ], lastLoadPositionTitle[MSG_SIZ];
3477 ChessMove lastLoadGameStart = (ChessMove) 0;
3481 UserMoveEvent(fromX, fromY, toX, toY, promoChar)
3482 int fromX, fromY, toX, toY;
3487 if (fromX < 0 || fromY < 0) return;
3488 if ((fromX == toX) && (fromY == toY)) {
3492 /* Check if the user is playing in turn. This is complicated because we
3493 let the user "pick up" a piece before it is his turn. So the piece he
3494 tried to pick up may have been captured by the time he puts it down!
3495 Therefore we use the color the user is supposed to be playing in this
3496 test, not the color of the piece that is currently on the starting
3497 square---except in EditGame mode, where the user is playing both
3498 sides; fortunately there the capture race can't happen. (It can
3499 now happen in IcsExamining mode, but that's just too bad. The user
3500 will get a somewhat confusing message in that case.)
3504 case PlayFromGameFile:
3506 case TwoMachinesPlay:
3510 /* We switched into a game mode where moves are not accepted,
3511 perhaps while the mouse button was down. */
3514 case MachinePlaysWhite:
3515 /* User is moving for Black */
3516 if (WhiteOnMove(currentMove)) {
3517 DisplayMoveError(_("It is White's turn"));
3522 case MachinePlaysBlack:
3523 /* User is moving for White */
3524 if (!WhiteOnMove(currentMove)) {
3525 DisplayMoveError(_("It is Black's turn"));
3532 case BeginningOfGame:
3535 if ((int) boards[currentMove][fromY][fromX] >= (int) BlackPawn &&
3536 (int) boards[currentMove][fromY][fromX] <= (int) BlackKing) {
3537 /* User is moving for Black */
3538 if (WhiteOnMove(currentMove)) {
3539 DisplayMoveError(_("It is White's turn"));
3543 /* User is moving for White */
3544 if (!WhiteOnMove(currentMove)) {
3545 DisplayMoveError(_("It is Black's turn"));
3551 case IcsPlayingBlack:
3552 /* User is moving for Black */
3553 if (WhiteOnMove(currentMove)) {
3554 if (!appData.premove) {
3555 DisplayMoveError(_("It is White's turn"));
3556 } else if (toX >= 0 && toY >= 0) {
3559 premoveFromX = fromX;
3560 premoveFromY = fromY;
3561 premovePromoChar = promoChar;
3563 if (appData.debugMode)
3564 fprintf(debugFP, "Got premove: fromX %d,"
3565 "fromY %d, toX %d, toY %d\n",
3566 fromX, fromY, toX, toY);
3572 case IcsPlayingWhite:
3573 /* User is moving for White */
3574 if (!WhiteOnMove(currentMove)) {
3575 if (!appData.premove) {
3576 DisplayMoveError(_("It is Black's turn"));
3577 } else if (toX >= 0 && toY >= 0) {
3580 premoveFromX = fromX;
3581 premoveFromY = fromY;
3582 premovePromoChar = promoChar;
3584 if (appData.debugMode)
3585 fprintf(debugFP, "Got premove: fromX %d,"
3586 "fromY %d, toX %d, toY %d\n",
3587 fromX, fromY, toX, toY);
3597 if (toX == -2 || toY == -2) {
3598 boards[0][fromY][fromX] = EmptySquare;
3599 DrawPosition(FALSE, boards[currentMove]);
3600 } else if (toX >= 0 && toY >= 0) {
3601 boards[0][toY][toX] = boards[0][fromY][fromX];
3602 boards[0][fromY][fromX] = EmptySquare;
3603 DrawPosition(FALSE, boards[currentMove]);
3608 if (toX < 0 || toY < 0) return;
3609 userOfferedDraw = FALSE;
3611 if (appData.testLegality) {
3612 moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
3613 EP_UNKNOWN, fromY, fromX, toY, toX, promoChar);
3614 if (moveType == IllegalMove || moveType == ImpossibleMove) {
3615 DisplayMoveError(_("Illegal move"));
3619 moveType = PromoCharToMoveType(WhiteOnMove(currentMove), promoChar);
3622 if (gameMode == Training) {
3623 /* compare the move played on the board to the next move in the
3624 * game. If they match, display the move and the opponent's response.
3625 * If they don't match, display an error message.
3629 CopyBoard(testBoard, boards[currentMove]);
3630 ApplyMove(fromX, fromY, toX, toY, promoChar, testBoard);
3632 if (CompareBoards(testBoard, boards[currentMove+1])) {
3633 ForwardInner(currentMove+1);
3635 /* Autoplay the opponent's response.
3636 * if appData.animate was TRUE when Training mode was entered,
3637 * the response will be animated.
3639 saveAnimate = appData.animate;
3640 appData.animate = animateTraining;
3641 ForwardInner(currentMove+1);
3642 appData.animate = saveAnimate;
3644 /* check for the end of the game */
3645 if (currentMove >= forwardMostMove) {
3646 gameMode = PlayFromGameFile;
3648 SetTrainingModeOff();
3649 DisplayInformation(_("End of game"));
3652 DisplayError(_("Incorrect move"), 0);
3657 FinishMove(moveType, fromX, fromY, toX, toY, promoChar);
3660 /* Common tail of UserMoveEvent and DropMenuEvent */
3662 FinishMove(moveType, fromX, fromY, toX, toY, promoChar)
3664 int fromX, fromY, toX, toY;
3665 /*char*/int promoChar;
3667 /* Ok, now we know that the move is good, so we can kill
3668 the previous line in Analysis Mode */
3669 if (gameMode == AnalyzeMode && currentMove < forwardMostMove) {
3670 forwardMostMove = currentMove;
3673 /* If we need the chess program but it's dead, restart it */
3674 ResurrectChessProgram();
3676 /* A user move restarts a paused game*/
3680 thinkOutput[0] = NULLCHAR;
3682 MakeMove(fromX, fromY, toX, toY, promoChar); /*updates forwardMostMove*/
3684 if (gameMode == BeginningOfGame) {
3685 if (appData.noChessProgram) {
3686 gameMode = EditGame;
3690 gameMode = MachinePlaysBlack;
3692 sprintf(buf, "%s vs. %s", gameInfo.white, gameInfo.black);
3694 if (first.sendName) {
3695 sprintf(buf, "name %s\n", gameInfo.white);
3696 SendToProgram(buf, &first);
3702 /* Relay move to ICS or chess engine */
3703 if (appData.icsActive) {
3704 if (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
3705 gameMode == IcsExamining) {
3706 SendMoveToICS(moveType, fromX, fromY, toX, toY);
3710 if (first.sendTime && (gameMode == BeginningOfGame ||
3711 gameMode == MachinePlaysWhite ||
3712 gameMode == MachinePlaysBlack)) {
3713 SendTimeRemaining(&first, gameMode != MachinePlaysBlack);
3715 SendMoveToProgram(forwardMostMove-1, &first);
3716 if (gameMode != EditGame && gameMode != PlayFromGameFile) {
3717 first.maybeThinking = TRUE;
3719 if (currentMove == cmailOldMove + 1) {
3720 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
3724 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
3728 switch (MateTest(boards[currentMove], PosFlags(currentMove),
3734 if (WhiteOnMove(currentMove)) {
3735 GameEnds(BlackWins, "Black mates", GE_PLAYER);
3737 GameEnds(WhiteWins, "White mates", GE_PLAYER);
3741 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
3746 case MachinePlaysBlack:
3747 case MachinePlaysWhite:
3748 /* disable certain menu options while machine is thinking */
3749 SetMachineThinkingEnables();
3758 HandleMachineMove(message, cps)
3760 ChessProgramState *cps;
3762 char machineMove[MSG_SIZ], buf1[MSG_SIZ*10], buf2[MSG_SIZ];
3763 char realname[MSG_SIZ];
3764 int fromX, fromY, toX, toY;
3771 * Kludge to ignore BEL characters
3773 while (*message == '\007') message++;
3776 * Look for book output
3778 if (cps == &first && bookRequested) {
3779 if (message[0] == '\t' || message[0] == ' ') {
3780 /* Part of the book output is here; append it */
3781 strcat(bookOutput, message);
3782 strcat(bookOutput, " \n");
3784 } else if (bookOutput[0] != NULLCHAR) {
3785 /* All of book output has arrived; display it */
3786 char *p = bookOutput;
3787 while (*p != NULLCHAR) {
3788 if (*p == '\t') *p = ' ';
3791 DisplayInformation(bookOutput);
3792 bookRequested = FALSE;
3793 /* Fall through to parse the current output */
3798 * Look for machine move.
3800 if ((sscanf(message, "%s %s %s", buf1, buf2, machineMove) == 3 &&
3801 strcmp(buf2, "...") == 0) ||
3802 (sscanf(message, "%s %s", buf1, machineMove) == 2 &&
3803 strcmp(buf1, "move") == 0)) {
3805 /* This method is only useful on engines that support ping */
3806 if (cps->lastPing != cps->lastPong) {
3807 if (gameMode == BeginningOfGame) {
3808 /* Extra move from before last new; ignore */
3809 if (appData.debugMode) {
3810 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
3813 if (appData.debugMode) {
3814 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
3815 cps->which, gameMode);
3817 SendToProgram("undo\n", cps);
3823 case BeginningOfGame:
3824 /* Extra move from before last reset; ignore */
3825 if (appData.debugMode) {
3826 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
3833 /* Extra move after we tried to stop. The mode test is
3834 not a reliable way of detecting this problem, but it's
3835 the best we can do on engines that don't support ping.
3837 if (appData.debugMode) {
3838 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
3839 cps->which, gameMode);
3841 SendToProgram("undo\n", cps);
3844 case MachinePlaysWhite:
3845 case IcsPlayingWhite:
3846 machineWhite = TRUE;
3849 case MachinePlaysBlack:
3850 case IcsPlayingBlack:
3851 machineWhite = FALSE;
3854 case TwoMachinesPlay:
3855 machineWhite = (cps->twoMachinesColor[0] == 'w');
3858 if (WhiteOnMove(forwardMostMove) != machineWhite) {
3859 if (appData.debugMode) {
3861 "Ignoring move out of turn by %s, gameMode %d"
3862 ", forwardMost %d\n",
3863 cps->which, gameMode, forwardMostMove);
3868 if (!ParseOneMove(machineMove, forwardMostMove, &moveType,
3869 &fromX, &fromY, &toX, &toY, &promoChar)) {
3870 /* Machine move could not be parsed; ignore it. */
3871 sprintf(buf1, _("Illegal move \"%s\" from %s machine"),
3872 machineMove, cps->which);
3873 DisplayError(buf1, 0);
3874 if (gameMode == TwoMachinesPlay) {
3875 GameEnds(machineWhite ? BlackWins : WhiteWins,
3876 "Forfeit due to illegal move", GE_XBOARD);
3881 hintRequested = FALSE;
3882 lastHint[0] = NULLCHAR;
3883 bookRequested = FALSE;
3884 /* Program may be pondering now */
3885 cps->maybeThinking = TRUE;
3886 if (cps->sendTime == 2) cps->sendTime = 1;
3887 if (cps->offeredDraw) cps->offeredDraw--;
3890 if ((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack) &&
3892 SendMoveToICS(moveType, fromX, fromY, toX, toY);
3896 /* currentMoveString is set as a side-effect of ParseOneMove */
3897 strcpy(machineMove, currentMoveString);
3898 strcat(machineMove, "\n");
3899 strcpy(moveList[forwardMostMove], machineMove);
3901 MakeMove(fromX, fromY, toX, toY, promoChar);/*updates forwardMostMove*/
3903 if (gameMode == TwoMachinesPlay) {
3904 if (cps->other->sendTime) {
3905 SendTimeRemaining(cps->other,
3906 cps->other->twoMachinesColor[0] == 'w');
3908 SendMoveToProgram(forwardMostMove-1, cps->other);
3911 if (cps->other->useColors) {
3912 SendToProgram(cps->other->twoMachinesColor, cps->other);
3914 SendToProgram("go\n", cps->other);
3916 cps->other->maybeThinking = TRUE;
3919 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
3920 if (!pausing && appData.ringBellAfterMoves) {
3924 * Reenable menu items that were disabled while
3925 * machine was thinking
3927 if (gameMode != TwoMachinesPlay)
3928 SetUserThinkingEnables();
3932 /* Set special modes for chess engines. Later something general
3933 * could be added here; for now there is just one kludge feature,
3934 * needed because Crafty 15.10 and earlier don't ignore SIGINT
3935 * when "xboard" is given as an interactive command.
3937 if (strncmp(message, "kibitz Hello from Crafty", 24) == 0) {
3938 cps->useSigint = FALSE;
3939 cps->useSigterm = FALSE;
3943 * Look for communication commands
3945 if (!strncmp(message, "telluser ", 9)) {
3946 DisplayNote(message + 9);
3949 if (!strncmp(message, "tellusererror ", 14)) {
3950 DisplayError(message + 14, 0);
3953 if (!strncmp(message, "tellopponent ", 13)) {
3954 if (appData.icsActive) {
3956 sprintf(buf1, "%ssay %s\n", ics_prefix, message + 13);
3960 DisplayNote(message + 13);
3964 if (!strncmp(message, "tellothers ", 11)) {
3965 if (appData.icsActive) {
3967 sprintf(buf1, "%swhisper %s\n", ics_prefix, message + 11);
3973 if (!strncmp(message, "tellall ", 8)) {
3974 if (appData.icsActive) {
3976 sprintf(buf1, "%skibitz %s\n", ics_prefix, message + 8);
3980 DisplayNote(message + 8);
3984 if (strncmp(message, "warning", 7) == 0) {
3985 /* Undocumented feature, use tellusererror in new code */
3986 DisplayError(message, 0);
3989 if (sscanf(message, "askuser %s %[^\n]", buf1, buf2) == 2) {
3990 strcpy(realname, cps->tidy);
3991 strcat(realname, " query");
3992 AskQuestion(realname, buf2, buf1, cps->pr);
3995 /* Commands from the engine directly to ICS. We don't allow these to be
3996 * sent until we are logged on. Crafty kibitzes have been known to
3997 * interfere with the login process.
4000 if (!strncmp(message, "tellics ", 8)) {
4001 SendToICS(message + 8);
4005 if (!strncmp(message, "tellicsnoalias ", 15)) {
4006 SendToICS(ics_prefix);
4007 SendToICS(message + 15);
4011 /* The following are for backward compatibility only */
4012 if (!strncmp(message,"whisper",7) || !strncmp(message,"kibitz",6) ||
4013 !strncmp(message,"draw",4) || !strncmp(message,"tell",3)) {
4014 SendToICS(ics_prefix);
4020 if (strncmp(message, "feature ", 8) == 0) {
4021 ParseFeatures(message+8, cps);
4023 if (sscanf(message, "pong %d", &cps->lastPong) == 1) {
4027 * If the move is illegal, cancel it and redraw the board.
4028 * Also deal with other error cases. Matching is rather loose
4029 * here to accommodate engines written before the spec.
4031 if (strncmp(message + 1, "llegal move", 11) == 0 ||
4032 strncmp(message, "Error", 5) == 0) {
4033 if (StrStr(message, "name") ||
4034 StrStr(message, "rating") || StrStr(message, "?") ||
4035 StrStr(message, "result") || StrStr(message, "board") ||
4036 StrStr(message, "bk") || StrStr(message, "computer") ||
4037 StrStr(message, "variant") || StrStr(message, "hint") ||
4038 StrStr(message, "random") || StrStr(message, "depth") ||
4039 StrStr(message, "accepted")) {
4042 if (StrStr(message, "protover")) {
4043 /* Program is responding to input, so it's apparently done
4044 initializing, and this error message indicates it is
4045 protocol version 1. So we don't need to wait any longer
4046 for it to initialize and send feature commands. */
4047 FeatureDone(cps, 1);
4048 cps->protocolVersion = 1;
4051 cps->maybeThinking = FALSE;
4053 if (StrStr(message, "draw")) {
4054 /* Program doesn't have "draw" command */
4055 cps->sendDrawOffers = 0;
4058 if (cps->sendTime != 1 &&
4059 (StrStr(message, "time") || StrStr(message, "otim"))) {
4060 /* Program apparently doesn't have "time" or "otim" command */
4064 if (StrStr(message, "analyze")) {
4065 cps->analysisSupport = FALSE;
4066 cps->analyzing = FALSE;
4068 sprintf(buf2, "%s does not support analysis", cps->tidy);
4069 DisplayError(buf2, 0);
4072 if (StrStr(message, "(no matching move)st")) {
4073 /* Special kludge for GNU Chess 4 only */
4074 cps->stKludge = TRUE;
4075 SendTimeControl(cps, movesPerSession, timeControl,
4076 timeIncrement, appData.searchDepth,
4080 if (StrStr(message, "(no matching move)sd")) {
4081 /* Special kludge for GNU Chess 4 only */
4082 cps->sdKludge = TRUE;
4083 SendTimeControl(cps, movesPerSession, timeControl,
4084 timeIncrement, appData.searchDepth,
4088 if (!StrStr(message, "llegal")) return;
4089 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
4090 gameMode == IcsIdle) return;
4091 if (forwardMostMove <= backwardMostMove) return;
4093 /* Following removed: it caused a bug where a real illegal move
4094 message in analyze mored would be ignored. */
4095 if (cps == &first && programStats.ok_to_send == 0) {
4096 /* Bogus message from Crafty responding to "." This filtering
4097 can miss some of the bad messages, but fortunately the bug
4098 is fixed in current Crafty versions, so it doesn't matter. */
4102 if (pausing) PauseEvent();
4103 if (gameMode == PlayFromGameFile) {
4104 /* Stop reading this game file */
4105 gameMode = EditGame;
4108 currentMove = --forwardMostMove;
4109 DisplayMove(currentMove-1); /* before DisplayMoveError */
4111 DisplayBothClocks();
4112 sprintf(buf1, _("Illegal move \"%s\" (rejected by %s chess program)"),
4113 parseList[currentMove], cps->which);
4114 DisplayMoveError(buf1);
4115 DrawPosition(FALSE, boards[currentMove]);
4118 if (strncmp(message, "time", 4) == 0 && StrStr(message, "Illegal")) {
4119 /* Program has a broken "time" command that
4120 outputs a string not ending in newline.
4126 * If chess program startup fails, exit with an error message.
4127 * Attempts to recover here are futile.
4129 if ((StrStr(message, "unknown host") != NULL)
4130 || (StrStr(message, "No remote directory") != NULL)
4131 || (StrStr(message, "not found") != NULL)
4132 || (StrStr(message, "No such file") != NULL)
4133 || (StrStr(message, "can't alloc") != NULL)
4134 || (StrStr(message, "Permission denied") != NULL)) {
4136 cps->maybeThinking = FALSE;
4137 sprintf(buf1, _("Failed to start %s chess program %s on %s: %s\n"),
4138 cps->which, cps->program, cps->host, message);
4139 RemoveInputSource(cps->isr);
4140 DisplayFatalError(buf1, 0, 1);
4145 * Look for hint output
4147 if (sscanf(message, "Hint: %s", buf1) == 1) {
4148 if (cps == &first && hintRequested) {
4149 hintRequested = FALSE;
4150 if (ParseOneMove(buf1, forwardMostMove, &moveType,
4151 &fromX, &fromY, &toX, &toY, &promoChar)) {
4152 (void) CoordsToAlgebraic(boards[forwardMostMove],
4153 PosFlags(forwardMostMove), EP_UNKNOWN,
4154 fromY, fromX, toY, toX, promoChar, buf1);
4155 sprintf(buf2, "Hint: %s", buf1);
4156 DisplayInformation(buf2);
4158 /* Hint move could not be parsed!? */
4160 _("Illegal hint move \"%s\"\nfrom %s chess program"),
4162 DisplayError(buf2, 0);
4165 strcpy(lastHint, buf1);
4171 * Ignore other messages if game is not in progress
4173 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
4174 gameMode == IcsIdle || cps->lastPing != cps->lastPong) return;
4177 * look for win, lose, draw, or draw offer
4179 if (strncmp(message, "1-0", 3) == 0) {
4180 char *p, *q, *r = "";
4181 p = strchr(message, '{');
4189 GameEnds(WhiteWins, r, GE_ENGINE);
4191 } else if (strncmp(message, "0-1", 3) == 0) {
4192 char *p, *q, *r = "";
4193 p = strchr(message, '{');
4201 /* Kludge for Arasan 4.1 bug */
4202 if (strcmp(r, "Black resigns") == 0) {
4203 GameEnds(WhiteWins, r, GE_ENGINE);
4206 GameEnds(BlackWins, r, GE_ENGINE);
4208 } else if (strncmp(message, "1/2", 3) == 0) {
4209 char *p, *q, *r = "";
4210 p = strchr(message, '{');
4218 GameEnds(GameIsDrawn, r, GE_ENGINE);
4221 } else if (strncmp(message, "White resign", 12) == 0) {
4222 GameEnds(BlackWins, "White resigns", GE_ENGINE);
4224 } else if (strncmp(message, "Black resign", 12) == 0) {
4225 GameEnds(WhiteWins, "Black resigns", GE_ENGINE);
4227 } else if (strncmp(message, "White", 5) == 0 &&
4228 message[5] != '(' &&
4229 StrStr(message, "Black") == NULL) {
4230 GameEnds(WhiteWins, "White mates", GE_ENGINE);
4232 } else if (strncmp(message, "Black", 5) == 0 &&
4233 message[5] != '(') {
4234 GameEnds(BlackWins, "Black mates", GE_ENGINE);
4236 } else if (strcmp(message, "resign") == 0 ||
4237 strcmp(message, "computer resigns") == 0) {
4239 case MachinePlaysBlack:
4240 case IcsPlayingBlack:
4241 GameEnds(WhiteWins, "Black resigns", GE_ENGINE);
4243 case MachinePlaysWhite:
4244 case IcsPlayingWhite:
4245 GameEnds(BlackWins, "White resigns", GE_ENGINE);
4247 case TwoMachinesPlay:
4248 if (cps->twoMachinesColor[0] == 'w')
4249 GameEnds(BlackWins, "White resigns", GE_ENGINE);
4251 GameEnds(WhiteWins, "Black resigns", GE_ENGINE);
4258 } else if (strncmp(message, "opponent mates", 14) == 0) {
4260 case MachinePlaysBlack:
4261 case IcsPlayingBlack:
4262 GameEnds(WhiteWins, "White mates", GE_ENGINE);
4264 case MachinePlaysWhite:
4265 case IcsPlayingWhite:
4266 GameEnds(BlackWins, "Black mates", GE_ENGINE);
4268 case TwoMachinesPlay:
4269 if (cps->twoMachinesColor[0] == 'w')
4270 GameEnds(BlackWins, "Black mates", GE_ENGINE);
4272 GameEnds(WhiteWins, "White mates", GE_ENGINE);
4279 } else if (strncmp(message, "computer mates", 14) == 0) {
4281 case MachinePlaysBlack:
4282 case IcsPlayingBlack:
4283 GameEnds(BlackWins, "Black mates", GE_ENGINE);
4285 case MachinePlaysWhite:
4286 case IcsPlayingWhite:
4287 GameEnds(WhiteWins, "White mates", GE_ENGINE);
4289 case TwoMachinesPlay:
4290 if (cps->twoMachinesColor[0] == 'w')
4291 GameEnds(WhiteWins, "White mates", GE_ENGINE);
4293 GameEnds(BlackWins, "Black mates", GE_ENGINE);
4300 } else if (strncmp(message, "checkmate", 9) == 0) {
4301 if (WhiteOnMove(forwardMostMove)) {
4302 GameEnds(BlackWins, "Black mates", GE_ENGINE);
4304 GameEnds(WhiteWins, "White mates", GE_ENGINE);
4307 } else if (strstr(message, "Draw") != NULL ||
4308 strstr(message, "game is a draw") != NULL) {
4309 GameEnds(GameIsDrawn, "Draw", GE_ENGINE);
4311 } else if (strstr(message, "offer") != NULL &&
4312 strstr(message, "draw") != NULL) {
4314 if (appData.zippyPlay && first.initDone) {
4315 /* Relay offer to ICS */
4316 SendToICS(ics_prefix);
4317 SendToICS("draw\n");
4320 cps->offeredDraw = 2; /* valid until this engine moves twice */
4321 if (gameMode == TwoMachinesPlay) {
4322 if (cps->other->offeredDraw) {
4323 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
4325 if (cps->other->sendDrawOffers) {
4326 SendToProgram("draw\n", cps->other);
4329 } else if (gameMode == MachinePlaysWhite ||
4330 gameMode == MachinePlaysBlack) {
4331 if (userOfferedDraw) {
4332 DisplayInformation(_("Machine accepts your draw offer"));
4333 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
4335 DisplayInformation(_("Machine offers a draw\nSelect Action / Draw to agree"));
4342 * Look for thinking output
4344 if (appData.showThinking) {
4345 int plylev, mvleft, mvtot, curscore, time;
4346 char mvname[MOVE_LEN];
4350 int prefixHint = FALSE;
4351 mvname[0] = NULLCHAR;
4354 case MachinePlaysBlack:
4355 case IcsPlayingBlack:
4356 if (WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
4358 case MachinePlaysWhite:
4359 case IcsPlayingWhite:
4360 if (!WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
4365 case TwoMachinesPlay:
4366 if ((cps->twoMachinesColor[0] == 'w') !=
4367 WhiteOnMove(forwardMostMove)) {
4378 if (sscanf(message, "%d%c %d %d" u64Display "%[^\n]\n",
4379 &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5) {
4381 if (plyext != ' ' && plyext != '\t') {
4384 programStats.depth = plylev;
4385 programStats.nodes = nodes;
4386 programStats.time = time;
4387 programStats.score = curscore;
4388 programStats.got_only_move = 0;
4390 /* Buffer overflow protection */
4391 if (buf1[0] != NULLCHAR) {
4392 if (strlen(buf1) >= sizeof(programStats.movelist)
4393 && appData.debugMode) {
4395 "PV is too long; using the first %d bytes.\n",
4396 sizeof(programStats.movelist) - 1);
4398 strncpy(programStats.movelist, buf1,
4399 sizeof(programStats.movelist));
4400 programStats.movelist[sizeof(programStats.movelist) - 1]
4403 sprintf(programStats.movelist, " no PV\n");
4406 if (programStats.seen_stat) {
4407 programStats.ok_to_send = 1;
4410 if (strchr(programStats.movelist, '(') != NULL) {
4411 programStats.line_is_book = 1;
4412 programStats.nr_moves = 0;
4413 programStats.moves_left = 0;
4415 programStats.line_is_book = 0;
4418 sprintf(thinkOutput, "[%d]%c%+.2f %s%s%s",
4420 (gameMode == TwoMachinesPlay ?
4421 ToUpper(cps->twoMachinesColor[0]) : ' '),
4422 ((double) curscore) / 100.0,
4423 prefixHint ? lastHint : "",
4424 prefixHint ? " " : "", buf1);
4426 if (currentMove == forwardMostMove ||
4427 gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
4428 DisplayMove(currentMove - 1);
4433 } else if ((p=StrStr(message, "(only move)")) != NULL) {
4434 /* crafty (9.25+) says "(only move) <move>"
4435 * if there is only 1 legal move
4437 sscanf(p, "(only move) %s", buf1);
4438 sprintf(thinkOutput, "%s (only move)", buf1);
4439 sprintf(programStats.movelist, "%s (only move)", buf1);
4440 programStats.depth = 1;
4441 programStats.nr_moves = 1;
4442 programStats.moves_left = 1;
4443 programStats.nodes = 1;
4444 programStats.time = 1;
4445 programStats.got_only_move = 1;
4447 /* Not really, but we also use this member to
4448 mean "line isn't going to change" (Crafty
4449 isn't searching, so stats won't change) */
4450 programStats.line_is_book = 1;
4452 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
4453 gameMode == AnalyzeFile) {
4454 DisplayMove(currentMove - 1);
4458 } else if (sscanf(message,"stat01: %d" u64Display "%d %d %d %s",
4459 &time, &nodes, &plylev, &mvleft,
4460 &mvtot, mvname) >= 5) {
4461 /* The stat01: line is from Crafty (9.29+) in response
4462 to the "." command */
4463 programStats.seen_stat = 1;
4464 cps->maybeThinking = TRUE;
4466 if (programStats.got_only_move || !appData.periodicUpdates)
4469 programStats.depth = plylev;
4470 programStats.time = time;
4471 programStats.nodes = nodes;
4472 programStats.moves_left = mvleft;
4473 programStats.nr_moves = mvtot;
4474 strcpy(programStats.move_name, mvname);
4475 programStats.ok_to_send = 1;
4479 } else if (strncmp(message,"++",2) == 0) {
4480 /* Crafty 9.29+ outputs this */
4481 programStats.got_fail = 2;
4484 } else if (strncmp(message,"--",2) == 0) {
4485 /* Crafty 9.29+ outputs this */
4486 programStats.got_fail = 1;
4489 } else if (thinkOutput[0] != NULLCHAR &&
4490 strncmp(message, " ", 4) == 0) {
4492 while (*p && *p == ' ') p++;
4493 strcat(thinkOutput, " ");
4494 strcat(thinkOutput, p);
4495 strcat(programStats.movelist, " ");
4496 strcat(programStats.movelist, p);
4497 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
4498 gameMode == AnalyzeFile) {
4499 DisplayMove(currentMove - 1);
4509 /* Parse a game score from the character string "game", and
4510 record it as the history of the current game. The game
4511 score is NOT assumed to start from the standard position.
4512 The display is not updated in any way.
4515 ParseGameHistory(game)
4519 int fromX, fromY, toX, toY, boardIndex;
4524 if (appData.debugMode)
4525 fprintf(debugFP, "Parsing game history: %s\n", game);
4527 if (gameInfo.event == NULL) gameInfo.event = StrSave("ICS game");
4528 gameInfo.site = StrSave(appData.icsHost);
4529 gameInfo.date = PGNDate();
4530 gameInfo.round = StrSave("-");
4532 /* Parse out names of players */
4533 while (*game == ' ') game++;
4535 while (*game != ' ') *p++ = *game++;
4537 gameInfo.white = StrSave(buf);
4538 while (*game == ' ') game++;
4540 while (*game != ' ' && *game != '\n') *p++ = *game++;
4542 gameInfo.black = StrSave(buf);
4545 boardIndex = blackPlaysFirst ? 1 : 0;
4548 yyboardindex = boardIndex;
4549 moveType = (ChessMove) yylex();
4551 case WhitePromotionQueen:
4552 case BlackPromotionQueen:
4553 case WhitePromotionRook:
4554 case BlackPromotionRook:
4555 case WhitePromotionBishop:
4556 case BlackPromotionBishop:
4557 case WhitePromotionKnight:
4558 case BlackPromotionKnight:
4559 case WhitePromotionKing:
4560 case BlackPromotionKing:
4562 case WhiteCapturesEnPassant:
4563 case BlackCapturesEnPassant:
4564 case WhiteKingSideCastle:
4565 case WhiteQueenSideCastle:
4566 case BlackKingSideCastle:
4567 case BlackQueenSideCastle:
4568 case WhiteKingSideCastleWild:
4569 case WhiteQueenSideCastleWild:
4570 case BlackKingSideCastleWild:
4571 case BlackQueenSideCastleWild:
4572 case IllegalMove: /* maybe suicide chess, etc. */
4573 fromX = currentMoveString[0] - 'a';
4574 fromY = currentMoveString[1] - '1';
4575 toX = currentMoveString[2] - 'a';
4576 toY = currentMoveString[3] - '1';
4577 promoChar = currentMoveString[4];
4581 fromX = moveType == WhiteDrop ?
4582 (int) CharToPiece(ToUpper(currentMoveString[0])) :
4583 (int) CharToPiece(ToLower(currentMoveString[0]));
4585 toX = currentMoveString[2] - 'a';
4586 toY = currentMoveString[3] - '1';
4587 promoChar = NULLCHAR;
4591 sprintf(buf, _("Ambiguous move in ICS output: \"%s\""), yy_text);
4592 DisplayError(buf, 0);
4594 case ImpossibleMove:
4596 sprintf(buf, _("Illegal move in ICS output: \"%s\""), yy_text);
4597 DisplayError(buf, 0);
4599 case (ChessMove) 0: /* end of file */
4600 if (boardIndex < backwardMostMove) {
4601 /* Oops, gap. How did that happen? */
4602 DisplayError(_("Gap in move list"), 0);
4605 backwardMostMove = blackPlaysFirst ? 1 : 0;
4606 if (boardIndex > forwardMostMove) {
4607 forwardMostMove = boardIndex;
4611 if (boardIndex > (blackPlaysFirst ? 1 : 0)) {
4612 strcat(parseList[boardIndex-1], " ");
4613 strcat(parseList[boardIndex-1], yy_text);
4625 case GameUnfinished:
4626 if (gameMode == IcsExamining) {
4627 if (boardIndex < backwardMostMove) {
4628 /* Oops, gap. How did that happen? */
4631 backwardMostMove = blackPlaysFirst ? 1 : 0;
4634 gameInfo.result = moveType;
4635 p = strchr(yy_text, '{');
4636 if (p == NULL) p = strchr(yy_text, '(');
4639 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
4641 q = strchr(p, *p == '{' ? '}' : ')');
4642 if (q != NULL) *q = NULLCHAR;
4645 gameInfo.resultDetails = StrSave(p);
4648 if (boardIndex >= forwardMostMove &&
4649 !(gameMode == IcsObserving && ics_gamenum == -1)) {
4650 backwardMostMove = blackPlaysFirst ? 1 : 0;
4653 (void) CoordsToAlgebraic(boards[boardIndex], PosFlags(boardIndex),
4654 EP_UNKNOWN, fromY, fromX, toY, toX, promoChar,
4655 parseList[boardIndex]);
4656 CopyBoard(boards[boardIndex + 1], boards[boardIndex]);
4657 /* currentMoveString is set as a side-effect of yylex */
4658 strcpy(moveList[boardIndex], currentMoveString);
4659 strcat(moveList[boardIndex], "\n");
4661 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[boardIndex]);
4662 switch (MateTest(boards[boardIndex],
4663 PosFlags(boardIndex), EP_UNKNOWN)) {
4669 strcat(parseList[boardIndex - 1], "+");
4672 strcat(parseList[boardIndex - 1], "#");
4679 /* Apply a move to the given board */
4681 ApplyMove(fromX, fromY, toX, toY, promoChar, board)
4682 int fromX, fromY, toX, toY;
4686 ChessSquare captured = board[toY][toX];
4687 if (fromY == DROP_RANK) {
4689 board[toY][toX] = (ChessSquare) fromX;
4690 } else if (fromX == toX && fromY == toY) {
4692 } else if (fromY == 0 && fromX == 4
4693 && board[fromY][fromX] == WhiteKing
4694 && toY == 0 && toX == 6) {
4695 board[fromY][fromX] = EmptySquare;
4696 board[toY][toX] = WhiteKing;
4697 board[fromY][7] = EmptySquare;
4698 board[toY][5] = WhiteRook;
4699 } else if (fromY == 0 && fromX == 4
4700 && board[fromY][fromX] == WhiteKing
4701 && toY == 0 && toX == 2) {
4702 board[fromY][fromX] = EmptySquare;
4703 board[toY][toX] = WhiteKing;
4704 board[fromY][0] = EmptySquare;
4705 board[toY][3] = WhiteRook;
4706 } else if (fromY == 0 && fromX == 3
4707 && board[fromY][fromX] == WhiteKing
4708 && toY == 0 && toX == 5) {
4709 board[fromY][fromX] = EmptySquare;
4710 board[toY][toX] = WhiteKing;
4711 board[fromY][7] = EmptySquare;
4712 board[toY][4] = WhiteRook;
4713 } else if (fromY == 0 && fromX == 3
4714 && board[fromY][fromX] == WhiteKing
4715 && toY == 0 && toX == 1) {
4716 board[fromY][fromX] = EmptySquare;
4717 board[toY][toX] = WhiteKing;
4718 board[fromY][0] = EmptySquare;
4719 board[toY][2] = WhiteRook;
4720 } else if (board[fromY][fromX] == WhitePawn
4722 /* white pawn promotion */
4723 board[7][toX] = CharToPiece(ToUpper(promoChar));
4724 if (board[7][toX] == EmptySquare) {
4725 board[7][toX] = WhiteQueen;
4727 board[fromY][fromX] = EmptySquare;
4728 } else if ((fromY == 4)
4730 && (board[fromY][fromX] == WhitePawn)
4731 && (board[toY][toX] == EmptySquare)) {
4732 board[fromY][fromX] = EmptySquare;
4733 board[toY][toX] = WhitePawn;
4734 captured = board[toY - 1][toX];
4735 board[toY - 1][toX] = EmptySquare;
4736 } else if (fromY == 7 && fromX == 4
4737 && board[fromY][fromX] == BlackKing
4738 && toY == 7 && toX == 6) {
4739 board[fromY][fromX] = EmptySquare;
4740 board[toY][toX] = BlackKing;
4741 board[fromY][7] = EmptySquare;
4742 board[toY][5] = BlackRook;
4743 } else if (fromY == 7 && fromX == 4
4744 && board[fromY][fromX] == BlackKing
4745 && toY == 7 && toX == 2) {
4746 board[fromY][fromX] = EmptySquare;
4747 board[toY][toX] = BlackKing;
4748 board[fromY][0] = EmptySquare;
4749 board[toY][3] = BlackRook;
4750 } else if (fromY == 7 && fromX == 3
4751 && board[fromY][fromX] == BlackKing
4752 && toY == 7 && toX == 5) {
4753 board[fromY][fromX] = EmptySquare;
4754 board[toY][toX] = BlackKing;
4755 board[fromY][7] = EmptySquare;
4756 board[toY][4] = BlackRook;
4757 } else if (fromY == 7 && fromX == 3
4758 && board[fromY][fromX] == BlackKing
4759 && toY == 7 && toX == 1) {
4760 board[fromY][fromX] = EmptySquare;
4761 board[toY][toX] = BlackKing;
4762 board[fromY][0] = EmptySquare;
4763 board[toY][2] = BlackRook;
4764 } else if (board[fromY][fromX] == BlackPawn
4766 /* black pawn promotion */
4767 board[0][toX] = CharToPiece(ToLower(promoChar));
4768 if (board[0][toX] == EmptySquare) {
4769 board[0][toX] = BlackQueen;
4771 board[fromY][fromX] = EmptySquare;
4772 } else if ((fromY == 3)
4774 && (board[fromY][fromX] == BlackPawn)
4775 && (board[toY][toX] == EmptySquare)) {
4776 board[fromY][fromX] = EmptySquare;
4777 board[toY][toX] = BlackPawn;
4778 captured = board[toY + 1][toX];
4779 board[toY + 1][toX] = EmptySquare;
4781 board[toY][toX] = board[fromY][fromX];
4782 board[fromY][fromX] = EmptySquare;
4784 if (gameInfo.variant == VariantCrazyhouse) {
4786 /* !!A lot more code needs to be written to support holdings */
4787 if (fromY == DROP_RANK) {
4788 /* Delete from holdings */
4789 if (holdings[(int) fromX] > 0) holdings[(int) fromX]--;
4791 if (captured != EmptySquare) {
4792 /* Add to holdings */
4793 if (captured < BlackPawn) {
4794 holdings[(int)captured - (int)BlackPawn + (int)WhitePawn]++;
4796 holdings[(int)captured - (int)WhitePawn + (int)BlackPawn]++;
4800 } else if (gameInfo.variant == VariantAtomic) {
4801 if (captured != EmptySquare) {
4803 for (y = toY-1; y <= toY+1; y++) {
4804 for (x = toX-1; x <= toX+1; x++) {
4805 if (y >= 0 && y <= 7 && x >= 0 && x <= 7 &&
4806 board[y][x] != WhitePawn && board[y][x] != BlackPawn) {
4807 board[y][x] = EmptySquare;
4811 board[toY][toX] = EmptySquare;
4816 /* Updates forwardMostMove */
4818 MakeMove(fromX, fromY, toX, toY, promoChar)
4819 int fromX, fromY, toX, toY;
4823 if (forwardMostMove >= MAX_MOVES) {
4824 DisplayFatalError(_("Game too long; increase MAX_MOVES and recompile"),
4829 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
4830 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
4831 if (commentList[forwardMostMove] != NULL) {
4832 free(commentList[forwardMostMove]);
4833 commentList[forwardMostMove] = NULL;
4835 CopyBoard(boards[forwardMostMove], boards[forwardMostMove - 1]);
4836 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[forwardMostMove]);
4837 gameInfo.result = GameUnfinished;
4838 if (gameInfo.resultDetails != NULL) {
4839 free(gameInfo.resultDetails);
4840 gameInfo.resultDetails = NULL;
4842 CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar,
4843 moveList[forwardMostMove - 1]);
4844 (void) CoordsToAlgebraic(boards[forwardMostMove - 1],
4845 PosFlags(forwardMostMove - 1), EP_UNKNOWN,
4846 fromY, fromX, toY, toX, promoChar,
4847 parseList[forwardMostMove - 1]);
4848 switch (MateTest(boards[forwardMostMove],
4849 PosFlags(forwardMostMove), EP_UNKNOWN)){
4855 strcat(parseList[forwardMostMove - 1], "+");
4858 strcat(parseList[forwardMostMove - 1], "#");
4863 /* Updates currentMove if not pausing */
4865 ShowMove(fromX, fromY, toX, toY)
4867 int instant = (gameMode == PlayFromGameFile) ?
4868 (matchMode || (appData.timeDelay == 0 && !pausing)) : pausing;
4869 if (!pausing || gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
4871 if (forwardMostMove == currentMove + 1) {
4872 AnimateMove(boards[forwardMostMove - 1],
4873 fromX, fromY, toX, toY);
4875 if (appData.highlightLastMove) {
4876 SetHighlights(fromX, fromY, toX, toY);
4879 currentMove = forwardMostMove;
4882 if (instant) return;
4883 DisplayMove(currentMove - 1);
4884 DrawPosition(FALSE, boards[currentMove]);
4885 DisplayBothClocks();
4886 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
4891 InitChessProgram(cps)
4892 ChessProgramState *cps;
4895 if (appData.noChessProgram) return;
4896 hintRequested = FALSE;
4897 bookRequested = FALSE;
4898 SendToProgram(cps->initString, cps);
4899 if (gameInfo.variant != VariantNormal &&
4900 gameInfo.variant != VariantLoadable) {
4901 char *v = VariantName(gameInfo.variant);
4902 if (StrStr(cps->variants, v) == NULL) {
4903 sprintf(buf, _("Variant %s not supported by %s"), v, cps->tidy);
4904 DisplayFatalError(buf, 0, 1);
4907 sprintf(buf, "variant %s\n", VariantName(gameInfo.variant));
4908 SendToProgram(buf, cps);
4911 sprintf(buf, "ics %s\n", appData.icsActive ? appData.icsHost : "-");
4912 SendToProgram(buf, cps);
4914 cps->maybeThinking = FALSE;
4915 cps->offeredDraw = 0;
4916 if (!appData.icsActive) {
4917 SendTimeControl(cps, movesPerSession, timeControl,
4918 timeIncrement, appData.searchDepth,
4921 if (appData.showThinking) {
4922 SendToProgram("post\n", cps);
4924 SendToProgram("hard\n", cps);
4925 if (!appData.ponderNextMove) {
4926 /* Warning: "easy" is a toggle in GNU Chess, so don't send
4927 it without being sure what state we are in first. "hard"
4928 is not a toggle, so that one is OK.
4930 SendToProgram("easy\n", cps);
4933 sprintf(buf, "ping %d\n", ++cps->lastPing);
4934 SendToProgram(buf, cps);
4936 cps->initDone = TRUE;
4941 StartChessProgram(cps)
4942 ChessProgramState *cps;
4947 if (appData.noChessProgram) return;
4948 cps->initDone = FALSE;
4950 if (strcmp(cps->host, "localhost") == 0) {
4951 err = StartChildProcess(cps->program, cps->dir, &cps->pr);
4952 } else if (*appData.remoteShell == NULLCHAR) {
4953 err = OpenRcmd(cps->host, appData.remoteUser, cps->program, &cps->pr);
4955 if (*appData.remoteUser == NULLCHAR) {
4956 sprintf(buf, "%s %s %s", appData.remoteShell, cps->host,
4959 sprintf(buf, "%s %s -l %s %s", appData.remoteShell,
4960 cps->host, appData.remoteUser, cps->program);
4962 err = StartChildProcess(buf, "", &cps->pr);
4966 sprintf(buf, "Startup failure on '%s'", cps->program);
4967 DisplayFatalError(buf, err, 1);
4973 cps->isr = AddInputSource(cps->pr, TRUE, ReceiveFromProgram, cps);
4974 if (cps->protocolVersion > 1) {
4975 sprintf(buf, "xboard\nprotover %d\n", cps->protocolVersion);
4976 SendToProgram(buf, cps);
4978 SendToProgram("xboard\n", cps);
4984 TwoMachinesEventIfReady P((void))
4986 if (first.lastPing != first.lastPong) {
4987 DisplayMessage("", "Waiting for first chess program");
4988 ScheduleDelayedEvent(TwoMachinesEventIfReady, 1000);
4991 if (second.lastPing != second.lastPong) {
4992 DisplayMessage("", "Waiting for second chess program");
4993 ScheduleDelayedEvent(TwoMachinesEventIfReady, 1000);
5001 NextMatchGame P((void))
5004 if (*appData.loadGameFile != NULLCHAR) {
5005 LoadGameFromFile(appData.loadGameFile,
5006 appData.loadGameIndex,
5007 appData.loadGameFile, FALSE);
5008 } else if (*appData.loadPositionFile != NULLCHAR) {
5009 LoadPositionFromFile(appData.loadPositionFile,
5010 appData.loadPositionIndex,
5011 appData.loadPositionFile);
5013 TwoMachinesEventIfReady();
5017 GameEnds(result, resultDetails, whosays)
5019 char *resultDetails;
5022 GameMode nextGameMode;
5025 if (appData.debugMode) {
5026 fprintf(debugFP, "GameEnds(%d, %s, %d)\n",
5027 result, resultDetails ? resultDetails : "(null)", whosays);
5030 if (appData.icsActive && whosays == GE_ENGINE) {
5031 /* If we are playing on ICS, the server decides when the
5032 game is over, but the engine can offer to draw, claim
5036 if (appData.zippyPlay && first.initDone) {
5037 if (result == GameIsDrawn) {
5038 /* In case draw still needs to be claimed */
5039 SendToICS(ics_prefix);
5040 SendToICS("draw\n");
5041 } else if (StrCaseStr(resultDetails, "resign")) {
5042 SendToICS(ics_prefix);
5043 SendToICS("resign\n");
5050 /* If we're loading the game from a file, stop */
5051 if (whosays == GE_FILE) {
5052 (void) StopLoadGameTimer();
5056 /* Cancel draw offers */
5057 first.offeredDraw = second.offeredDraw = 0;
5059 /* If this is an ICS game, only ICS can really say it's done;
5060 if not, anyone can. */
5061 isIcsGame = (gameMode == IcsPlayingWhite ||
5062 gameMode == IcsPlayingBlack ||
5063 gameMode == IcsObserving ||
5064 gameMode == IcsExamining);
5066 if (!isIcsGame || whosays == GE_ICS) {
5067 /* OK -- not an ICS game, or ICS said it was done */
5069 if (!isIcsGame && !appData.noChessProgram)
5070 SetUserThinkingEnables();
5072 if (resultDetails != NULL) {
5073 gameInfo.result = result;
5074 gameInfo.resultDetails = StrSave(resultDetails);
5076 /* Tell program how game ended in case it is learning */
5077 if (gameMode == MachinePlaysWhite ||
5078 gameMode == MachinePlaysBlack ||
5079 gameMode == TwoMachinesPlay ||
5080 gameMode == IcsPlayingWhite ||
5081 gameMode == IcsPlayingBlack ||
5082 gameMode == BeginningOfGame) {
5084 sprintf(buf, "result %s {%s}\n", PGNResult(result),
5086 if (first.pr != NoProc) {
5087 SendToProgram(buf, &first);
5089 if (second.pr != NoProc &&
5090 gameMode == TwoMachinesPlay) {
5091 SendToProgram(buf, &second);
5095 /* display last move only if game was not loaded from file */
5096 if ((whosays != GE_FILE) && (currentMove == forwardMostMove))
5097 DisplayMove(currentMove - 1);
5099 if (forwardMostMove != 0) {
5100 if (gameMode != PlayFromGameFile && gameMode != EditGame) {
5101 if (*appData.saveGameFile != NULLCHAR) {
5102 SaveGameToFile(appData.saveGameFile, TRUE);
5103 } else if (appData.autoSaveGames) {
5106 if (*appData.savePositionFile != NULLCHAR) {
5107 SavePositionToFile(appData.savePositionFile);
5113 if (appData.icsActive) {
5114 if (appData.quietPlay &&
5115 (gameMode == IcsPlayingWhite ||
5116 gameMode == IcsPlayingBlack)) {
5117 SendToICS(ics_prefix);
5118 SendToICS("set shout 1\n");
5120 nextGameMode = IcsIdle;
5121 ics_user_moved = FALSE;
5122 /* clean up premove. It's ugly when the game has ended and the
5123 * premove highlights are still on the board.
5127 ClearPremoveHighlights();
5128 DrawPosition(FALSE, boards[currentMove]);
5130 if (whosays == GE_ICS) {
5133 if (gameMode == IcsPlayingWhite)
5135 else if(gameMode == IcsPlayingBlack)
5139 if (gameMode == IcsPlayingBlack)
5141 else if(gameMode == IcsPlayingWhite)
5148 PlayIcsUnfinishedSound();
5151 } else if (gameMode == EditGame ||
5152 gameMode == PlayFromGameFile ||
5153 gameMode == AnalyzeMode ||
5154 gameMode == AnalyzeFile) {
5155 nextGameMode = gameMode;
5157 nextGameMode = EndOfGame;
5162 nextGameMode = gameMode;
5165 if (appData.noChessProgram) {
5166 gameMode = nextGameMode;
5172 /* Put first chess program into idle state */
5173 if (first.pr != NoProc &&
5174 (gameMode == MachinePlaysWhite ||
5175 gameMode == MachinePlaysBlack ||
5176 gameMode == TwoMachinesPlay ||
5177 gameMode == IcsPlayingWhite ||
5178 gameMode == IcsPlayingBlack ||
5179 gameMode == BeginningOfGame)) {
5180 SendToProgram("force\n", &first);
5181 if (first.usePing) {
5183 sprintf(buf, "ping %d\n", ++first.lastPing);
5184 SendToProgram(buf, &first);
5187 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
5188 /* Kill off first chess program */
5189 if (first.isr != NULL)
5190 RemoveInputSource(first.isr);
5193 if (first.pr != NoProc) {
5195 SendToProgram("quit\n", &first);
5196 DestroyChildProcess(first.pr, first.useSigterm);
5201 /* Put second chess program into idle state */
5202 if (second.pr != NoProc &&
5203 gameMode == TwoMachinesPlay) {
5204 SendToProgram("force\n", &second);
5205 if (second.usePing) {
5207 sprintf(buf, "ping %d\n", ++second.lastPing);
5208 SendToProgram(buf, &second);
5211 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
5212 /* Kill off second chess program */
5213 if (second.isr != NULL)
5214 RemoveInputSource(second.isr);
5217 if (second.pr != NoProc) {
5218 SendToProgram("quit\n", &second);
5219 DestroyChildProcess(second.pr, second.useSigterm);
5224 if (matchMode && gameMode == TwoMachinesPlay) {
5227 if (first.twoMachinesColor[0] == 'w') {
5234 if (first.twoMachinesColor[0] == 'b') {
5243 if (matchGame < appData.matchGames) {
5245 tmp = first.twoMachinesColor;
5246 first.twoMachinesColor = second.twoMachinesColor;
5247 second.twoMachinesColor = tmp;
5248 gameMode = nextGameMode;
5250 ScheduleDelayedEvent(NextMatchGame, 10000);
5254 gameMode = nextGameMode;
5255 sprintf(buf, _("Match %s vs. %s: final score %d-%d-%d"),
5256 first.tidy, second.tidy,
5257 first.matchWins, second.matchWins,
5258 appData.matchGames - (first.matchWins + second.matchWins));
5259 DisplayFatalError(buf, 0, 0);
5262 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile) &&
5263 !(nextGameMode == AnalyzeMode || nextGameMode == AnalyzeFile))
5265 gameMode = nextGameMode;
5269 /* Assumes program was just initialized (initString sent).
5270 Leaves program in force mode. */
5272 FeedMovesToProgram(cps, upto)
5273 ChessProgramState *cps;
5278 if (appData.debugMode)
5279 fprintf(debugFP, "Feeding %smoves %d through %d to %s chess program\n",
5280 startedFromSetupPosition ? "position and " : "",
5281 backwardMostMove, upto, cps->which);
5282 SendToProgram("force\n", cps);
5283 if (startedFromSetupPosition) {
5284 SendBoard(cps, backwardMostMove);
5286 for (i = backwardMostMove; i < upto; i++) {
5287 SendMoveToProgram(i, cps);
5293 ResurrectChessProgram()
5295 /* The chess program may have exited.
5296 If so, restart it and feed it all the moves made so far. */
5298 if (appData.noChessProgram || first.pr != NoProc) return;
5300 StartChessProgram(&first);
5301 InitChessProgram(&first);
5302 FeedMovesToProgram(&first, currentMove);
5304 if (!first.sendTime) {
5305 /* can't tell gnuchess what its clock should read,
5306 so we bow to its notion. */
5308 timeRemaining[0][currentMove] = whiteTimeRemaining;
5309 timeRemaining[1][currentMove] = blackTimeRemaining;
5312 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile) &&
5313 first.analysisSupport) {
5314 SendToProgram("analyze\n", &first);
5315 first.analyzing = TRUE;
5328 if (appData.debugMode) {
5329 fprintf(debugFP, "Reset(%d, %d) from gameMode %d\n",
5330 redraw, init, gameMode);
5333 pausing = pauseExamInvalid = FALSE;
5334 startedFromSetupPosition = blackPlaysFirst = FALSE;
5336 whiteFlag = blackFlag = FALSE;
5337 userOfferedDraw = FALSE;
5338 hintRequested = bookRequested = FALSE;
5339 first.maybeThinking = FALSE;
5340 second.maybeThinking = FALSE;
5341 thinkOutput[0] = NULLCHAR;
5342 lastHint[0] = NULLCHAR;
5343 ClearGameInfo(&gameInfo);
5344 gameInfo.variant = StringToVariant(appData.variant);
5345 ics_user_moved = ics_clock_paused = FALSE;
5346 ics_getting_history = H_FALSE;
5348 white_holding[0] = black_holding[0] = NULLCHAR;
5349 ClearProgramStats();
5353 flipView = appData.flipView;
5354 ClearPremoveHighlights();
5356 alarmSounded = FALSE;
5358 GameEnds((ChessMove) 0, NULL, GE_PLAYER);
5360 gameMode = BeginningOfGame;
5362 InitPosition(redraw);
5363 for (i = 0; i < MAX_MOVES; i++) {
5364 if (commentList[i] != NULL) {
5365 free(commentList[i]);
5366 commentList[i] = NULL;
5370 timeRemaining[0][0] = whiteTimeRemaining;
5371 timeRemaining[1][0] = blackTimeRemaining;
5372 if (first.pr == NULL) {
5373 StartChessProgram(&first);
5375 if (init) InitChessProgram(&first);
5377 DisplayMessage("", "");
5378 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
5385 if (!AutoPlayOneMove())
5387 if (matchMode || appData.timeDelay == 0)
5389 if (appData.timeDelay < 0 || gameMode == AnalyzeFile)
5391 StartLoadGameTimer((long)(1000.0 * appData.timeDelay));
5400 int fromX, fromY, toX, toY;
5402 if (appData.debugMode) {
5403 fprintf(debugFP, "AutoPlayOneMove(): current %d\n", currentMove);
5406 if (gameMode != PlayFromGameFile)
5409 if (currentMove >= forwardMostMove) {
5410 gameMode = EditGame;
5415 toX = moveList[currentMove][2] - 'a';
5416 toY = moveList[currentMove][3] - '1';
5418 if (moveList[currentMove][1] == '@') {
5419 if (appData.highlightLastMove) {
5420 SetHighlights(-1, -1, toX, toY);
5423 fromX = moveList[currentMove][0] - 'a';
5424 fromY = moveList[currentMove][1] - '1';
5425 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
5427 if (appData.highlightLastMove) {
5428 SetHighlights(fromX, fromY, toX, toY);
5431 DisplayMove(currentMove);
5432 SendMoveToProgram(currentMove++, &first);
5433 DisplayBothClocks();
5434 DrawPosition(FALSE, boards[currentMove]);
5435 if (commentList[currentMove] != NULL) {
5436 DisplayComment(currentMove - 1, commentList[currentMove]);
5443 LoadGameOneMove(readAhead)
5444 ChessMove readAhead;
5446 int fromX = 0, fromY = 0, toX = 0, toY = 0, done;
5447 char promoChar = NULLCHAR;
5452 if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile &&
5453 gameMode != AnalyzeMode && gameMode != Training) {
5458 yyboardindex = forwardMostMove;
5459 if (readAhead != (ChessMove)0) {
5460 moveType = readAhead;
5462 if (gameFileFP == NULL)
5464 moveType = (ChessMove) yylex();
5470 if (appData.debugMode)
5471 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
5473 if (*p == '{' || *p == '[' || *p == '(') {
5474 p[strlen(p) - 1] = NULLCHAR;
5478 /* append the comment but don't display it */
5479 while (*p == '\n') p++;
5480 AppendComment(currentMove, p);
5483 case WhiteCapturesEnPassant:
5484 case BlackCapturesEnPassant:
5485 case WhitePromotionQueen:
5486 case BlackPromotionQueen:
5487 case WhitePromotionRook:
5488 case BlackPromotionRook:
5489 case WhitePromotionBishop:
5490 case BlackPromotionBishop:
5491 case WhitePromotionKnight:
5492 case BlackPromotionKnight:
5493 case WhitePromotionKing:
5494 case BlackPromotionKing:
5496 case WhiteKingSideCastle:
5497 case WhiteQueenSideCastle:
5498 case BlackKingSideCastle:
5499 case BlackQueenSideCastle:
5500 case WhiteKingSideCastleWild:
5501 case WhiteQueenSideCastleWild:
5502 case BlackKingSideCastleWild:
5503 case BlackQueenSideCastleWild:
5504 if (appData.debugMode)
5505 fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
5506 fromX = currentMoveString[0] - 'a';
5507 fromY = currentMoveString[1] - '1';
5508 toX = currentMoveString[2] - 'a';
5509 toY = currentMoveString[3] - '1';
5510 promoChar = currentMoveString[4];
5515 if (appData.debugMode)
5516 fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
5517 fromX = moveType == WhiteDrop ?
5518 (int) CharToPiece(ToUpper(currentMoveString[0])) :
5519 (int) CharToPiece(ToLower(currentMoveString[0]));
5521 toX = currentMoveString[2] - 'a';
5522 toY = currentMoveString[3] - '1';
5528 case GameUnfinished:
5529 if (appData.debugMode)
5530 fprintf(debugFP, "Parsed game end: %s\n", yy_text);
5531 p = strchr(yy_text, '{');
5532 if (p == NULL) p = strchr(yy_text, '(');
5535 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
5537 q = strchr(p, *p == '{' ? '}' : ')');
5538 if (q != NULL) *q = NULLCHAR;
5541 GameEnds(moveType, p, GE_FILE);
5543 if (cmailMsgLoaded) {
5545 flipView = WhiteOnMove(currentMove);
5546 if (moveType == GameUnfinished) flipView = !flipView;
5547 if (appData.debugMode)
5548 fprintf(debugFP, "Setting flipView to %d\n", flipView) ;
5552 case (ChessMove) 0: /* end of file */
5553 if (appData.debugMode)
5554 fprintf(debugFP, "Parser hit end of file\n");
5555 switch (MateTest(boards[currentMove], PosFlags(currentMove),
5561 if (WhiteOnMove(currentMove)) {
5562 GameEnds(BlackWins, "Black mates", GE_FILE);
5564 GameEnds(WhiteWins, "White mates", GE_FILE);
5568 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
5575 if (lastLoadGameStart == GNUChessGame) {
5576 /* GNUChessGames have numbers, but they aren't move numbers */
5577 if (appData.debugMode)
5578 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
5579 yy_text, (int) moveType);
5580 return LoadGameOneMove((ChessMove)0); /* tail recursion */
5582 /* else fall thru */
5587 /* Reached start of next game in file */
5588 if (appData.debugMode)
5589 fprintf(debugFP, "Parsed start of next game: %s\n", yy_text);
5590 switch (MateTest(boards[currentMove], PosFlags(currentMove),
5596 if (WhiteOnMove(currentMove)) {
5597 GameEnds(BlackWins, "Black mates", GE_FILE);
5599 GameEnds(WhiteWins, "White mates", GE_FILE);
5603 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
5609 case PositionDiagram: /* should not happen; ignore */
5610 case ElapsedTime: /* ignore */
5611 case NAG: /* ignore */
5612 if (appData.debugMode)
5613 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
5614 yy_text, (int) moveType);
5615 return LoadGameOneMove((ChessMove)0); /* tail recursion */
5618 if (appData.testLegality) {
5619 if (appData.debugMode)
5620 fprintf(debugFP, "Parsed IllegalMove: %s\n", yy_text);
5621 sprintf(move, _("Illegal move: %d.%s%s"),
5622 (forwardMostMove / 2) + 1,
5623 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
5624 DisplayError(move, 0);
5627 if (appData.debugMode)
5628 fprintf(debugFP, "Parsed %s into IllegalMove %s\n",
5629 yy_text, currentMoveString);
5630 fromX = currentMoveString[0] - 'a';
5631 fromY = currentMoveString[1] - '1';
5632 toX = currentMoveString[2] - 'a';
5633 toY = currentMoveString[3] - '1';
5634 promoChar = currentMoveString[4];
5639 if (appData.debugMode)
5640 fprintf(debugFP, "Parsed AmbiguousMove: %s\n", yy_text);
5641 sprintf(move, _("Ambiguous move: %d.%s%s"),
5642 (forwardMostMove / 2) + 1,
5643 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
5644 DisplayError(move, 0);
5649 case ImpossibleMove:
5650 if (appData.debugMode)
5651 fprintf(debugFP, "Parsed ImpossibleMove: %s\n", yy_text);
5652 sprintf(move, _("Illegal move: %d.%s%s"),
5653 (forwardMostMove / 2) + 1,
5654 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
5655 DisplayError(move, 0);
5661 if (appData.matchMode || (appData.timeDelay == 0 && !pausing)) {
5662 DrawPosition(FALSE, boards[currentMove]);
5663 DisplayBothClocks();
5664 if (!appData.matchMode && commentList[currentMove] != NULL)
5665 DisplayComment(currentMove - 1, commentList[currentMove]);
5667 (void) StopLoadGameTimer();
5669 cmailOldMove = forwardMostMove;
5672 /* currentMoveString is set as a side-effect of yylex */
5673 strcat(currentMoveString, "\n");
5674 strcpy(moveList[forwardMostMove], currentMoveString);
5676 thinkOutput[0] = NULLCHAR;
5677 MakeMove(fromX, fromY, toX, toY, promoChar);
5678 currentMove = forwardMostMove;
5683 /* Load the nth game from the given file */
5685 LoadGameFromFile(filename, n, title, useList)
5689 /*Boolean*/ int useList;
5694 if (strcmp(filename, "-") == 0) {
5698 f = fopen(filename, "rb");
5700 sprintf(buf, _("Can't open \"%s\""), filename);
5701 DisplayError(buf, errno);
5705 if (fseek(f, 0, 0) == -1) {
5706 /* f is not seekable; probably a pipe */
5709 if (useList && n == 0) {
5710 int error = GameListBuild(f);
5712 DisplayError(_("Cannot build game list"), error);
5713 } else if (!ListEmpty(&gameList) &&
5714 ((ListGame *) gameList.tailPred)->number > 1) {
5715 GameListPopUp(f, title);
5722 return LoadGame(f, n, title, FALSE);
5727 MakeRegisteredMove()
5729 int fromX, fromY, toX, toY;
5731 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
5732 switch (cmailMoveType[lastLoadGameNumber - 1]) {
5735 if (appData.debugMode)
5736 fprintf(debugFP, "Restoring %s for game %d\n",
5737 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
5739 thinkOutput[0] = NULLCHAR;
5740 strcpy(moveList[currentMove], cmailMove[lastLoadGameNumber - 1]);
5741 fromX = cmailMove[lastLoadGameNumber - 1][0] - 'a';
5742 fromY = cmailMove[lastLoadGameNumber - 1][1] - '1';
5743 toX = cmailMove[lastLoadGameNumber - 1][2] - 'a';
5744 toY = cmailMove[lastLoadGameNumber - 1][3] - '1';
5745 promoChar = cmailMove[lastLoadGameNumber - 1][4];
5746 MakeMove(fromX, fromY, toX, toY, promoChar);
5747 ShowMove(fromX, fromY, toX, toY);
5749 switch (MateTest(boards[currentMove], PosFlags(currentMove),
5756 if (WhiteOnMove(currentMove)) {
5757 GameEnds(BlackWins, "Black mates", GE_PLAYER);
5759 GameEnds(WhiteWins, "White mates", GE_PLAYER);
5764 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
5771 if (WhiteOnMove(currentMove)) {
5772 GameEnds(BlackWins, "White resigns", GE_PLAYER);
5774 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
5779 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
5790 /* Wrapper around LoadGame for use when a Cmail message is loaded */
5792 CmailLoadGame(f, gameNumber, title, useList)
5800 if (gameNumber > nCmailGames) {
5801 DisplayError(_("No more games in this message"), 0);
5804 if (f == lastLoadGameFP) {
5805 int offset = gameNumber - lastLoadGameNumber;
5807 cmailMsg[0] = NULLCHAR;
5808 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
5809 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
5810 nCmailMovesRegistered--;
5812 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
5813 if (cmailResult[lastLoadGameNumber - 1] == CMAIL_NEW_RESULT) {
5814 cmailResult[lastLoadGameNumber - 1] = CMAIL_NOT_RESULT;
5817 if (! RegisterMove()) return FALSE;
5821 retVal = LoadGame(f, gameNumber, title, useList);
5823 /* Make move registered during previous look at this game, if any */
5824 MakeRegisteredMove();
5826 if (cmailCommentList[lastLoadGameNumber - 1] != NULL) {
5827 commentList[currentMove]
5828 = StrSave(cmailCommentList[lastLoadGameNumber - 1]);
5829 DisplayComment(currentMove - 1, commentList[currentMove]);
5835 /* Support for LoadNextGame, LoadPreviousGame, ReloadSameGame */
5840 int gameNumber = lastLoadGameNumber + offset;
5841 if (lastLoadGameFP == NULL) {
5842 DisplayError(_("No game has been loaded yet"), 0);
5845 if (gameNumber <= 0) {
5846 DisplayError(_("Can't back up any further"), 0);
5849 if (cmailMsgLoaded) {
5850 return CmailLoadGame(lastLoadGameFP, gameNumber,
5851 lastLoadGameTitle, lastLoadGameUseList);
5853 return LoadGame(lastLoadGameFP, gameNumber,
5854 lastLoadGameTitle, lastLoadGameUseList);
5860 /* Load the nth game from open file f */
5862 LoadGame(f, gameNumber, title, useList)
5870 int gn = gameNumber;
5871 ListGame *lg = NULL;
5874 GameMode oldGameMode;
5876 if (appData.debugMode)
5877 fprintf(debugFP, "LoadGame(): on entry, gameMode %d\n", gameMode);
5879 if (gameMode == Training )
5880 SetTrainingModeOff();
5882 oldGameMode = gameMode;
5883 if (gameMode != BeginningOfGame) {
5888 if (lastLoadGameFP != NULL && lastLoadGameFP != f) {
5889 fclose(lastLoadGameFP);
5893 lg = (ListGame *) ListElem(&gameList, gameNumber-1);
5896 fseek(f, lg->offset, 0);
5897 GameListHighlight(gameNumber);
5901 DisplayError(_("Game number out of range"), 0);
5906 if (fseek(f, 0, 0) == -1) {
5907 if (f == lastLoadGameFP ?
5908 gameNumber == lastLoadGameNumber + 1 :
5912 DisplayError(_("Can't seek on game file"), 0);
5918 lastLoadGameNumber = gameNumber;
5919 strcpy(lastLoadGameTitle, title);
5920 lastLoadGameUseList = useList;
5925 if (lg && lg->gameInfo.white && lg->gameInfo.black) {
5926 sprintf(buf, "%s vs. %s", lg->gameInfo.white,
5927 lg->gameInfo.black);
5929 } else if (*title != NULLCHAR) {
5930 if (gameNumber > 1) {
5931 sprintf(buf, "%s %d", title, gameNumber);
5934 DisplayTitle(title);
5938 if (gameMode != AnalyzeFile && gameMode != AnalyzeMode) {
5939 gameMode = PlayFromGameFile;
5943 currentMove = forwardMostMove = backwardMostMove = 0;
5944 CopyBoard(boards[0], initialPosition);
5948 * Skip the first gn-1 games in the file.
5949 * Also skip over anything that precedes an identifiable
5950 * start of game marker, to avoid being confused by
5951 * garbage at the start of the file. Currently
5952 * recognized start of game markers are the move number "1",
5953 * the pattern "gnuchess .* game", the pattern
5954 * "^[#;%] [^ ]* game file", and a PGN tag block.
5955 * A game that starts with one of the latter two patterns
5956 * will also have a move number 1, possibly
5957 * following a position diagram.
5958 * 5-4-02: Let's try being more lenient and allowing a game to
5959 * start with an unnumbered move. Does that break anything?
5961 cm = lastLoadGameStart = (ChessMove) 0;
5963 yyboardindex = forwardMostMove;
5964 cm = (ChessMove) yylex();
5967 if (cmailMsgLoaded) {
5968 nCmailGames = CMAIL_MAX_GAMES - gn;
5971 DisplayError(_("Game not found in file"), 0);
5978 lastLoadGameStart = cm;
5982 switch (lastLoadGameStart) {
5989 gn--; /* count this game */
5990 lastLoadGameStart = cm;
5999 switch (lastLoadGameStart) {
6004 gn--; /* count this game */
6005 lastLoadGameStart = cm;
6008 lastLoadGameStart = cm; /* game counted already */
6016 yyboardindex = forwardMostMove;
6017 cm = (ChessMove) yylex();
6018 } while (cm == PGNTag || cm == Comment);
6025 if (cmailMsgLoaded && (CMAIL_MAX_GAMES == lastLoadGameNumber)) {
6026 if ( cmailResult[CMAIL_MAX_GAMES - gn - 1]
6027 != CMAIL_OLD_RESULT) {
6029 cmailResult[ CMAIL_MAX_GAMES
6030 - gn - 1] = CMAIL_OLD_RESULT;
6036 /* Only a NormalMove can be at the start of a game
6037 * without a position diagram. */
6038 if (lastLoadGameStart == (ChessMove) 0) {
6040 lastLoadGameStart = MoveNumberOne;
6049 if (appData.debugMode)
6050 fprintf(debugFP, "Parsed game start '%s' (%d)\n", yy_text, (int) cm);
6052 if (cm == XBoardGame) {
6053 /* Skip any header junk before position diagram and/or move 1 */
6055 yyboardindex = forwardMostMove;
6056 cm = (ChessMove) yylex();
6058 if (cm == (ChessMove) 0 ||
6059 cm == GNUChessGame || cm == XBoardGame) {
6060 /* Empty game; pretend end-of-file and handle later */
6065 if (cm == MoveNumberOne || cm == PositionDiagram ||
6066 cm == PGNTag || cm == Comment)
6069 } else if (cm == GNUChessGame) {
6070 if (gameInfo.event != NULL) {
6071 free(gameInfo.event);
6073 gameInfo.event = StrSave(yy_text);
6076 startedFromSetupPosition = FALSE;
6077 while (cm == PGNTag) {
6078 if (appData.debugMode)
6079 fprintf(debugFP, "Parsed PGNTag: %s\n", yy_text);
6080 err = ParsePGNTag(yy_text, &gameInfo);
6081 if (!err) numPGNTags++;
6083 if (gameInfo.fen != NULL) {
6084 Board initial_position;
6085 startedFromSetupPosition = TRUE;
6086 if (!ParseFEN(initial_position, &blackPlaysFirst, gameInfo.fen)) {
6088 DisplayError(_("Bad FEN position in file"), 0);
6091 CopyBoard(boards[0], initial_position);
6092 if (blackPlaysFirst) {
6093 currentMove = forwardMostMove = backwardMostMove = 1;
6094 CopyBoard(boards[1], initial_position);
6095 strcpy(moveList[0], "");
6096 strcpy(parseList[0], "");
6097 timeRemaining[0][1] = whiteTimeRemaining;
6098 timeRemaining[1][1] = blackTimeRemaining;
6099 if (commentList[0] != NULL) {
6100 commentList[1] = commentList[0];
6101 commentList[0] = NULL;
6104 currentMove = forwardMostMove = backwardMostMove = 0;
6106 yyboardindex = forwardMostMove;
6108 gameInfo.fen = NULL;
6111 yyboardindex = forwardMostMove;
6112 cm = (ChessMove) yylex();
6114 /* Handle comments interspersed among the tags */
6115 while (cm == Comment) {
6117 if (appData.debugMode)
6118 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
6120 if (*p == '{' || *p == '[' || *p == '(') {
6121 p[strlen(p) - 1] = NULLCHAR;
6124 while (*p == '\n') p++;
6125 AppendComment(currentMove, p);
6126 yyboardindex = forwardMostMove;
6127 cm = (ChessMove) yylex();
6131 /* don't rely on existence of Event tag since if game was
6132 * pasted from clipboard the Event tag may not exist
6134 if (numPGNTags > 0){
6136 if (gameInfo.variant == VariantNormal) {
6137 gameInfo.variant = StringToVariant(gameInfo.event);
6140 tags = PGNTags(&gameInfo);
6141 TagsPopUp(tags, CmailMsg());
6145 /* Make something up, but don't display it now */
6150 if (cm == PositionDiagram) {
6153 Board initial_position;
6155 if (appData.debugMode)
6156 fprintf(debugFP, "Parsed PositionDiagram: %s\n", yy_text);
6158 if (!startedFromSetupPosition) {
6160 for (i = BOARD_SIZE - 1; i >= 0; i--)
6161 for (j = 0; j < BOARD_SIZE; p++)
6171 initial_position[i][j++] = CharToPiece(*p);
6174 while (*p == ' ' || *p == '\t' ||
6175 *p == '\n' || *p == '\r') p++;
6177 if (strncmp(p, "black", strlen("black"))==0)
6178 blackPlaysFirst = TRUE;
6180 blackPlaysFirst = FALSE;
6181 startedFromSetupPosition = TRUE;
6183 CopyBoard(boards[0], initial_position);
6184 if (blackPlaysFirst) {
6185 currentMove = forwardMostMove = backwardMostMove = 1;
6186 CopyBoard(boards[1], initial_position);
6187 strcpy(moveList[0], "");
6188 strcpy(parseList[0], "");
6189 timeRemaining[0][1] = whiteTimeRemaining;
6190 timeRemaining[1][1] = blackTimeRemaining;
6191 if (commentList[0] != NULL) {
6192 commentList[1] = commentList[0];
6193 commentList[0] = NULL;
6196 currentMove = forwardMostMove = backwardMostMove = 0;
6199 yyboardindex = forwardMostMove;
6200 cm = (ChessMove) yylex();
6203 if (first.pr == NoProc) {
6204 StartChessProgram(&first);
6206 InitChessProgram(&first);
6207 SendToProgram("force\n", &first);
6208 if (startedFromSetupPosition) {
6209 SendBoard(&first, forwardMostMove);
6210 DisplayBothClocks();
6213 while (cm == Comment) {
6215 if (appData.debugMode)
6216 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
6218 if (*p == '{' || *p == '[' || *p == '(') {
6219 p[strlen(p) - 1] = NULLCHAR;
6222 while (*p == '\n') p++;
6223 AppendComment(currentMove, p);
6224 yyboardindex = forwardMostMove;
6225 cm = (ChessMove) yylex();
6228 if ((cm == (ChessMove) 0 && lastLoadGameStart != (ChessMove) 0) ||
6229 cm == WhiteWins || cm == BlackWins ||
6230 cm == GameIsDrawn || cm == GameUnfinished) {
6231 DisplayMessage("", _("No moves in game"));
6232 if (cmailMsgLoaded) {
6233 if (appData.debugMode)
6234 fprintf(debugFP, "Setting flipView to %d.\n", FALSE);
6238 DrawPosition(FALSE, boards[currentMove]);
6239 DisplayBothClocks();
6240 gameMode = EditGame;
6247 if (commentList[currentMove] != NULL) {
6248 if (!matchMode && (pausing || appData.timeDelay != 0)) {
6249 DisplayComment(currentMove - 1, commentList[currentMove]);
6252 if (!matchMode && appData.timeDelay != 0)
6253 DrawPosition(FALSE, boards[currentMove]);
6255 if (gameMode == AnalyzeFile || gameMode == AnalyzeMode) {
6256 programStats.ok_to_send = 1;
6259 /* if the first token after the PGN tags is a move
6260 * and not move number 1, retrieve it from the parser
6262 if (cm != MoveNumberOne)
6263 LoadGameOneMove(cm);
6265 /* load the remaining moves from the file */
6266 while (LoadGameOneMove((ChessMove)0)) {
6267 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
6268 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
6271 /* rewind to the start of the game */
6272 currentMove = backwardMostMove;
6274 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
6276 if (oldGameMode == AnalyzeFile ||
6277 oldGameMode == AnalyzeMode) {
6281 if (matchMode || appData.timeDelay == 0) {
6283 gameMode = EditGame;
6285 } else if (appData.timeDelay > 0) {
6289 if (appData.debugMode)
6290 fprintf(debugFP, "LoadGame(): on exit, gameMode %d\n", gameMode);
6294 /* Support for LoadNextPosition, LoadPreviousPosition, ReloadSamePosition */
6296 ReloadPosition(offset)
6299 int positionNumber = lastLoadPositionNumber + offset;
6300 if (lastLoadPositionFP == NULL) {
6301 DisplayError(_("No position has been loaded yet"), 0);
6304 if (positionNumber <= 0) {
6305 DisplayError(_("Can't back up any further"), 0);
6308 return LoadPosition(lastLoadPositionFP, positionNumber,
6309 lastLoadPositionTitle);
6312 /* Load the nth position from the given file */
6314 LoadPositionFromFile(filename, n, title)
6322 if (strcmp(filename, "-") == 0) {
6323 return LoadPosition(stdin, n, "stdin");
6325 f = fopen(filename, "rb");
6327 sprintf(buf, _("Can't open \"%s\""), filename);
6328 DisplayError(buf, errno);
6331 return LoadPosition(f, n, title);
6336 /* Load the nth position from the given open file, and close it */
6338 LoadPosition(f, positionNumber, title)
6343 char *p, line[MSG_SIZ];
6344 Board initial_position;
6345 int i, j, fenMode, pn;
6347 if (gameMode == Training )
6348 SetTrainingModeOff();
6350 if (gameMode != BeginningOfGame) {
6353 if (lastLoadPositionFP != NULL && lastLoadPositionFP != f) {
6354 fclose(lastLoadPositionFP);
6356 if (positionNumber == 0) positionNumber = 1;
6357 lastLoadPositionFP = f;
6358 lastLoadPositionNumber = positionNumber;
6359 strcpy(lastLoadPositionTitle, title);
6360 if (first.pr == NoProc) {
6361 StartChessProgram(&first);
6362 InitChessProgram(&first);
6364 pn = positionNumber;
6365 if (positionNumber < 0) {
6366 /* Negative position number means to seek to that byte offset */
6367 if (fseek(f, -positionNumber, 0) == -1) {
6368 DisplayError(_("Can't seek on position file"), 0);
6373 if (fseek(f, 0, 0) == -1) {
6374 if (f == lastLoadPositionFP ?
6375 positionNumber == lastLoadPositionNumber + 1 :
6376 positionNumber == 1) {
6379 DisplayError(_("Can't seek on position file"), 0);
6384 /* See if this file is FEN or old-style xboard */
6385 if (fgets(line, MSG_SIZ, f) == NULL) {
6386 DisplayError(_("Position not found in file"), 0);
6394 case 'p': case 'n': case 'b': case 'r': case 'q': case 'k':
6395 case 'P': case 'N': case 'B': case 'R': case 'Q': case 'K':
6396 case '1': case '2': case '3': case '4': case '5': case '6':
6403 if (fenMode || line[0] == '#') pn--;
6405 /* skip postions before number pn */
6406 if (fgets(line, MSG_SIZ, f) == NULL) {
6408 DisplayError(_("Position not found in file"), 0);
6411 if (fenMode || line[0] == '#') pn--;
6416 if (!ParseFEN(initial_position, &blackPlaysFirst, line)) {
6417 DisplayError(_("Bad FEN position in file"), 0);
6421 (void) fgets(line, MSG_SIZ, f);
6422 (void) fgets(line, MSG_SIZ, f);
6424 for (i = BOARD_SIZE - 1; i >= 0; i--) {
6425 (void) fgets(line, MSG_SIZ, f);
6426 for (p = line, j = 0; j < BOARD_SIZE; p++) {
6429 initial_position[i][j++] = CharToPiece(*p);
6433 blackPlaysFirst = FALSE;
6435 (void) fgets(line, MSG_SIZ, f);
6436 if (strncmp(line, "black", strlen("black"))==0)
6437 blackPlaysFirst = TRUE;
6440 startedFromSetupPosition = TRUE;
6442 SendToProgram("force\n", &first);
6443 CopyBoard(boards[0], initial_position);
6444 if (blackPlaysFirst) {
6445 currentMove = forwardMostMove = backwardMostMove = 1;
6446 strcpy(moveList[0], "");
6447 strcpy(parseList[0], "");
6448 CopyBoard(boards[1], initial_position);
6449 DisplayMessage("", _("Black to play"));
6451 currentMove = forwardMostMove = backwardMostMove = 0;
6452 DisplayMessage("", _("White to play"));
6454 SendBoard(&first, forwardMostMove);
6456 if (positionNumber > 1) {
6457 sprintf(line, "%s %d", title, positionNumber);
6460 DisplayTitle(title);
6462 gameMode = EditGame;
6465 timeRemaining[0][1] = whiteTimeRemaining;
6466 timeRemaining[1][1] = blackTimeRemaining;
6467 DrawPosition(FALSE, boards[currentMove]);
6474 CopyPlayerNameIntoFileName(dest, src)
6477 while (*src != NULLCHAR && *src != ',') {
6482 *(*dest)++ = *src++;
6487 char *DefaultFileName(ext)
6490 static char def[MSG_SIZ];
6493 if (gameInfo.white != NULL && gameInfo.white[0] != '-') {
6495 CopyPlayerNameIntoFileName(&p, gameInfo.white);
6497 CopyPlayerNameIntoFileName(&p, gameInfo.black);
6506 /* Save the current game to the given file */
6508 SaveGameToFile(filename, append)
6515 if (strcmp(filename, "-") == 0) {
6516 return SaveGame(stdout, 0, NULL);
6518 f = fopen(filename, append ? "a" : "w");
6520 sprintf(buf, _("Can't open \"%s\""), filename);
6521 DisplayError(buf, errno);
6524 return SaveGame(f, 0, NULL);
6533 static char buf[MSG_SIZ];
6536 p = strchr(str, ' ');
6537 if (p == NULL) return str;
6538 strncpy(buf, str, p - str);
6539 buf[p - str] = NULLCHAR;
6543 #define PGN_MAX_LINE 75
6545 /* Save game in PGN style and close the file */
6550 int i, offset, linelen, newblock;
6554 int movelen, numlen, blank;
6556 tm = time((time_t *) NULL);
6558 PrintPGNTags(f, &gameInfo);
6560 if (backwardMostMove > 0 || startedFromSetupPosition) {
6561 char *fen = PositionToFEN(backwardMostMove);
6562 fprintf(f, "[FEN \"%s\"]\n[SetUp \"1\"]\n", fen);
6563 fprintf(f, "\n{--------------\n");
6564 PrintPosition(f, backwardMostMove);
6565 fprintf(f, "--------------}\n");
6571 i = backwardMostMove;
6572 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
6576 while (i < forwardMostMove) {
6577 /* Print comments preceding this move */
6578 if (commentList[i] != NULL) {
6579 if (linelen > 0) fprintf(f, "\n");
6580 fprintf(f, "{\n%s}\n", commentList[i]);
6585 /* Format move number */
6587 sprintf(numtext, "%d.", (i - offset)/2 + 1);
6590 sprintf(numtext, "%d...", (i - offset)/2 + 1);
6592 numtext[0] = NULLCHAR;
6595 numlen = strlen(numtext);
6598 /* Print move number */
6599 blank = linelen > 0 && numlen > 0;
6600 if (linelen + (blank ? 1 : 0) + numlen > PGN_MAX_LINE) {
6609 fprintf(f, numtext);
6613 movetext = SavePart(parseList[i]);
6614 movelen = strlen(movetext);
6617 blank = linelen > 0 && movelen > 0;
6618 if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
6627 fprintf(f, movetext);
6633 /* Start a new line */
6634 if (linelen > 0) fprintf(f, "\n");
6636 /* Print comments after last move */
6637 if (commentList[i] != NULL) {
6638 fprintf(f, "{\n%s}\n", commentList[i]);
6642 if (gameInfo.resultDetails != NULL &&
6643 gameInfo.resultDetails[0] != NULLCHAR) {
6644 fprintf(f, "{%s} %s\n\n", gameInfo.resultDetails,
6645 PGNResult(gameInfo.result));
6647 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
6654 /* Save game in old style and close the file */
6662 tm = time((time_t *) NULL);
6664 fprintf(f, "# %s game file -- %s", programName, ctime(&tm));
6667 if (backwardMostMove > 0 || startedFromSetupPosition) {
6668 fprintf(f, "\n[--------------\n");
6669 PrintPosition(f, backwardMostMove);
6670 fprintf(f, "--------------]\n");
6675 i = backwardMostMove;
6676 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
6678 while (i < forwardMostMove) {
6679 if (commentList[i] != NULL) {
6680 fprintf(f, "[%s]\n", commentList[i]);
6684 fprintf(f, "%d. ... %s\n", (i - offset)/2 + 1, parseList[i]);
6687 fprintf(f, "%d. %s ", (i - offset)/2 + 1, parseList[i]);
6689 if (commentList[i] != NULL) {
6693 if (i >= forwardMostMove) {
6697 fprintf(f, "%s\n", parseList[i]);
6702 if (commentList[i] != NULL) {
6703 fprintf(f, "[%s]\n", commentList[i]);
6706 /* This isn't really the old style, but it's close enough */
6707 if (gameInfo.resultDetails != NULL &&
6708 gameInfo.resultDetails[0] != NULLCHAR) {
6709 fprintf(f, "%s (%s)\n\n", PGNResult(gameInfo.result),
6710 gameInfo.resultDetails);
6712 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
6719 /* Save the current game to open file f and close the file */
6721 SaveGame(f, dummy, dummy2)
6726 if (gameMode == EditPosition) EditPositionDone();
6727 if (appData.oldSaveStyle)
6728 return SaveGameOldStyle(f);
6730 return SaveGamePGN(f);
6733 /* Save the current position to the given file */
6735 SavePositionToFile(filename)
6741 if (strcmp(filename, "-") == 0) {
6742 return SavePosition(stdout, 0, NULL);
6744 f = fopen(filename, "a");
6746 sprintf(buf, _("Can't open \"%s\""), filename);
6747 DisplayError(buf, errno);
6750 SavePosition(f, 0, NULL);
6756 /* Save the current position to the given open file and close the file */
6758 SavePosition(f, dummy, dummy2)
6766 if (appData.oldSaveStyle) {
6767 tm = time((time_t *) NULL);
6769 fprintf(f, "# %s position file -- %s", programName, ctime(&tm));
6771 fprintf(f, "[--------------\n");
6772 PrintPosition(f, currentMove);
6773 fprintf(f, "--------------]\n");
6775 fen = PositionToFEN(currentMove);
6776 fprintf(f, "%s\n", fen);
6784 ReloadCmailMsgEvent(unregister)
6788 static char *inFilename = NULL;
6789 static char *outFilename;
6791 struct stat inbuf, outbuf;
6794 /* Any registered moves are unregistered if unregister is set, */
6795 /* i.e. invoked by the signal handler */
6797 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
6798 cmailMoveRegistered[i] = FALSE;
6799 if (cmailCommentList[i] != NULL) {
6800 free(cmailCommentList[i]);
6801 cmailCommentList[i] = NULL;
6804 nCmailMovesRegistered = 0;
6807 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
6808 cmailResult[i] = CMAIL_NOT_RESULT;
6812 if (inFilename == NULL) {
6813 /* Because the filenames are static they only get malloced once */
6814 /* and they never get freed */
6815 inFilename = (char *) malloc(strlen(appData.cmailGameName) + 9);
6816 sprintf(inFilename, "%s.game.in", appData.cmailGameName);
6818 outFilename = (char *) malloc(strlen(appData.cmailGameName) + 5);
6819 sprintf(outFilename, "%s.out", appData.cmailGameName);
6822 status = stat(outFilename, &outbuf);
6824 cmailMailedMove = FALSE;
6826 status = stat(inFilename, &inbuf);
6827 cmailMailedMove = (inbuf.st_mtime < outbuf.st_mtime);
6830 /* LoadGameFromFile(CMAIL_MAX_GAMES) with cmailMsgLoaded == TRUE
6831 counts the games, notes how each one terminated, etc.
6833 It would be nice to remove this kludge and instead gather all
6834 the information while building the game list. (And to keep it
6835 in the game list nodes instead of having a bunch of fixed-size
6836 parallel arrays.) Note this will require getting each game's
6837 termination from the PGN tags, as the game list builder does
6838 not process the game moves. --mann
6840 cmailMsgLoaded = TRUE;
6841 LoadGameFromFile(inFilename, CMAIL_MAX_GAMES, "", FALSE);
6843 /* Load first game in the file or popup game menu */
6844 LoadGameFromFile(inFilename, 0, appData.cmailGameName, TRUE);
6854 char string[MSG_SIZ];
6856 if ( cmailMailedMove
6857 || (cmailResult[lastLoadGameNumber - 1] == CMAIL_OLD_RESULT)) {
6858 return TRUE; /* Allow free viewing */
6861 /* Unregister move to ensure that we don't leave RegisterMove */
6862 /* with the move registered when the conditions for registering no */
6864 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
6865 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
6866 nCmailMovesRegistered --;
6868 if (cmailCommentList[lastLoadGameNumber - 1] != NULL)
6870 free(cmailCommentList[lastLoadGameNumber - 1]);
6871 cmailCommentList[lastLoadGameNumber - 1] = NULL;
6875 if (cmailOldMove == -1) {
6876 DisplayError(_("You have edited the game history.\nUse Reload Same Game and make your move again."), 0);
6880 if (currentMove > cmailOldMove + 1) {
6881 DisplayError(_("You have entered too many moves.\nBack up to the correct position and try again."), 0);
6885 if (currentMove < cmailOldMove) {
6886 DisplayError(_("Displayed position is not current.\nStep forward to the correct position and try again."), 0);
6890 if (forwardMostMove > currentMove) {
6891 /* Silently truncate extra moves */
6895 if ( (currentMove == cmailOldMove + 1)
6896 || ( (currentMove == cmailOldMove)
6897 && ( (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_ACCEPT)
6898 || (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_RESIGN)))) {
6899 if (gameInfo.result != GameUnfinished) {
6900 cmailResult[lastLoadGameNumber - 1] = CMAIL_NEW_RESULT;
6903 if (commentList[currentMove] != NULL) {
6904 cmailCommentList[lastLoadGameNumber - 1]
6905 = StrSave(commentList[currentMove]);
6907 strcpy(cmailMove[lastLoadGameNumber - 1], moveList[currentMove - 1]);
6909 if (appData.debugMode)
6910 fprintf(debugFP, "Saving %s for game %d\n",
6911 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
6914 "%s.game.out.%d", appData.cmailGameName, lastLoadGameNumber);
6916 f = fopen(string, "w");
6917 if (appData.oldSaveStyle) {
6918 SaveGameOldStyle(f); /* also closes the file */
6920 sprintf(string, "%s.pos.out", appData.cmailGameName);
6921 f = fopen(string, "w");
6922 SavePosition(f, 0, NULL); /* also closes the file */
6924 fprintf(f, "{--------------\n");
6925 PrintPosition(f, currentMove);
6926 fprintf(f, "--------------}\n\n");
6928 SaveGame(f, 0, NULL); /* also closes the file*/
6931 cmailMoveRegistered[lastLoadGameNumber - 1] = TRUE;
6932 nCmailMovesRegistered ++;
6933 } else if (nCmailGames == 1) {
6934 DisplayError(_("You have not made a move yet"), 0);
6945 static char *partCommandString = "cmail -xv%s -remail -game %s 2>&1";
6946 FILE *commandOutput;
6947 char buffer[MSG_SIZ], msg[MSG_SIZ], string[MSG_SIZ];
6948 int nBytes = 0; /* Suppress warnings on uninitialized variables */
6954 if (! cmailMsgLoaded) {
6955 DisplayError(_("The cmail message is not loaded.\nUse Reload CMail Message and make your move again."), 0);
6959 if (nCmailGames == nCmailResults) {
6960 DisplayError(_("No unfinished games"), 0);
6964 #if CMAIL_PROHIBIT_REMAIL
6965 if (cmailMailedMove) {
6966 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);
6967 DisplayError(msg, 0);
6972 if (! (cmailMailedMove || RegisterMove())) return;
6974 if ( cmailMailedMove
6975 || (nCmailMovesRegistered + nCmailResults == nCmailGames)) {
6976 sprintf(string, partCommandString,
6977 appData.debugMode ? " -v" : "", appData.cmailGameName);
6978 commandOutput = popen(string, "rb");
6980 if (commandOutput == NULL) {
6981 DisplayError(_("Failed to invoke cmail"), 0);
6983 for (nBuffers = 0; (! feof(commandOutput)); nBuffers ++) {
6984 nBytes = fread(buffer, 1, MSG_SIZ - 1, commandOutput);
6987 (void) memcpy(msg, buffer + nBytes, MSG_SIZ - nBytes - 1);
6988 (void) memcpy(msg + MSG_SIZ - nBytes - 1, buffer, nBytes);
6989 nBytes = MSG_SIZ - 1;
6991 (void) memcpy(msg, buffer, nBytes);
6993 *(msg + nBytes) = '\0'; /* \0 for end-of-string*/
6995 if(StrStr(msg, "Mailed cmail message to ") != NULL) {
6996 cmailMailedMove = TRUE; /* Prevent >1 moves */
6999 for (i = 0; i < nCmailGames; i ++) {
7000 if (cmailResult[i] == CMAIL_NOT_RESULT) {
7005 && ( (arcDir = (char *) getenv("CMAIL_ARCDIR"))
7007 sprintf(buffer, "%s/%s.%s.archive",
7009 appData.cmailGameName,
7011 LoadGameFromFile(buffer, 1, buffer, FALSE);
7012 cmailMsgLoaded = FALSE;
7016 DisplayInformation(msg);
7017 pclose(commandOutput);
7020 if ((*cmailMsg) != '\0') {
7021 DisplayInformation(cmailMsg);
7035 int prependComma = 0;
7037 char string[MSG_SIZ]; /* Space for game-list */
7040 if (!cmailMsgLoaded) return "";
7042 if (cmailMailedMove) {
7043 sprintf(cmailMsg, _("Waiting for reply from opponent\n"));
7045 /* Create a list of games left */
7046 sprintf(string, "[");
7047 for (i = 0; i < nCmailGames; i ++) {
7048 if (! ( cmailMoveRegistered[i]
7049 || (cmailResult[i] == CMAIL_OLD_RESULT))) {
7051 sprintf(number, ",%d", i + 1);
7053 sprintf(number, "%d", i + 1);
7057 strcat(string, number);
7060 strcat(string, "]");
7062 if (nCmailMovesRegistered + nCmailResults == 0) {
7063 switch (nCmailGames) {
7066 _("Still need to make move for game\n"));
7071 _("Still need to make moves for both games\n"));
7076 _("Still need to make moves for all %d games\n"),
7081 switch (nCmailGames - nCmailMovesRegistered - nCmailResults) {
7084 _("Still need to make a move for game %s\n"),
7089 if (nCmailResults == nCmailGames) {
7090 sprintf(cmailMsg, _("No unfinished games\n"));
7092 sprintf(cmailMsg, _("Ready to send mail\n"));
7098 _("Still need to make moves for games %s\n"),
7110 if (gameMode == Training)
7111 SetTrainingModeOff();
7114 cmailMsgLoaded = FALSE;
7115 if (appData.icsActive) {
7116 SendToICS(ics_prefix);
7117 SendToICS("refresh\n");
7121 static int exiting = 0;
7129 /* Give up on clean exit */
7133 /* Keep trying for clean exit */
7137 if (appData.icsActive && appData.colorize) Colorize(ColorNone, FALSE);
7139 if (telnetISR != NULL) {
7140 RemoveInputSource(telnetISR);
7142 if (icsPR != NoProc) {
7143 DestroyChildProcess(icsPR, TRUE);
7145 /* Save game if resource set and not already saved by GameEnds() */
7146 if (gameInfo.resultDetails == NULL && forwardMostMove > 0) {
7147 if (*appData.saveGameFile != NULLCHAR) {
7148 SaveGameToFile(appData.saveGameFile, TRUE);
7149 } else if (appData.autoSaveGames) {
7152 if (*appData.savePositionFile != NULLCHAR) {
7153 SavePositionToFile(appData.savePositionFile);
7156 GameEnds((ChessMove) 0, NULL, GE_PLAYER);
7158 /* Kill off chess programs */
7159 if (first.pr != NoProc) {
7161 SendToProgram("quit\n", &first);
7162 DestroyChildProcess(first.pr, first.useSigterm);
7164 if (second.pr != NoProc) {
7165 SendToProgram("quit\n", &second);
7166 DestroyChildProcess(second.pr, second.useSigterm);
7168 if (first.isr != NULL) {
7169 RemoveInputSource(first.isr);
7171 if (second.isr != NULL) {
7172 RemoveInputSource(second.isr);
7182 if (appData.debugMode)
7183 fprintf(debugFP, "PauseEvent(): pausing %d\n", pausing);
7187 if (gameMode == MachinePlaysWhite ||
7188 gameMode == MachinePlaysBlack) {
7191 DisplayBothClocks();
7193 if (gameMode == PlayFromGameFile) {
7194 if (appData.timeDelay >= 0)
7196 } else if (gameMode == IcsExamining && pauseExamInvalid) {
7198 SendToICS(ics_prefix);
7199 SendToICS("refresh\n");
7200 } else if (currentMove < forwardMostMove) {
7201 ForwardInner(forwardMostMove);
7203 pauseExamInvalid = FALSE;
7209 pauseExamForwardMostMove = forwardMostMove;
7210 pauseExamInvalid = FALSE;
7213 case IcsPlayingWhite:
7214 case IcsPlayingBlack:
7218 case PlayFromGameFile:
7219 (void) StopLoadGameTimer();
7223 case BeginningOfGame:
7224 if (appData.icsActive) return;
7225 /* else fall through */
7226 case MachinePlaysWhite:
7227 case MachinePlaysBlack:
7228 case TwoMachinesPlay:
7229 if (forwardMostMove == 0)
7230 return; /* don't pause if no one has moved */
7231 if ((gameMode == MachinePlaysWhite &&
7232 !WhiteOnMove(forwardMostMove)) ||
7233 (gameMode == MachinePlaysBlack &&
7234 WhiteOnMove(forwardMostMove))) {
7247 char title[MSG_SIZ];
7249 if (currentMove < 1 || parseList[currentMove - 1][0] == NULLCHAR) {
7250 strcpy(title, _("Edit comment"));
7252 sprintf(title, _("Edit comment on %d.%s%s"), (currentMove - 1) / 2 + 1,
7253 WhiteOnMove(currentMove - 1) ? " " : ".. ",
7254 parseList[currentMove - 1]);
7257 EditCommentPopUp(currentMove, title, commentList[currentMove]);
7264 char *tags = PGNTags(&gameInfo);
7265 EditTagsPopUp(tags);
7272 if (appData.noChessProgram || gameMode == AnalyzeMode)
7275 if (gameMode != AnalyzeFile) {
7277 if (gameMode != EditGame) return;
7278 ResurrectChessProgram();
7279 SendToProgram("analyze\n", &first);
7280 first.analyzing = TRUE;
7281 /*first.maybeThinking = TRUE;*/
7282 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
7283 AnalysisPopUp(_("Analysis"),
7284 _("Starting analysis mode...\nIf this message stays up, your chess program does not support analysis."));
7286 gameMode = AnalyzeMode;
7291 StartAnalysisClock();
7292 GetTimeMark(&lastNodeCountTime);
7299 if (appData.noChessProgram || gameMode == AnalyzeFile)
7302 if (gameMode != AnalyzeMode) {
7304 if (gameMode != EditGame) return;
7305 ResurrectChessProgram();
7306 SendToProgram("analyze\n", &first);
7307 first.analyzing = TRUE;
7308 /*first.maybeThinking = TRUE;*/
7309 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
7310 AnalysisPopUp(_("Analysis"),
7311 _("Starting analysis mode...\nIf this message stays up, your chess program does not support analysis."));
7313 gameMode = AnalyzeFile;
7318 StartAnalysisClock();
7319 GetTimeMark(&lastNodeCountTime);
7328 if (appData.noChessProgram || (gameMode == MachinePlaysWhite))
7332 if (gameMode == PlayFromGameFile ||
7333 gameMode == TwoMachinesPlay ||
7334 gameMode == Training ||
7335 gameMode == AnalyzeMode ||
7336 gameMode == EndOfGame)
7339 if (gameMode == EditPosition)
7342 if (!WhiteOnMove(currentMove)) {
7343 DisplayError(_("It is not White's turn"), 0);
7347 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
7350 if (gameMode == EditGame || gameMode == AnalyzeMode ||
7351 gameMode == AnalyzeFile)
7354 ResurrectChessProgram(); /* in case it isn't running */
7355 gameMode = MachinePlaysWhite;
7359 sprintf(buf, "%s vs. %s", gameInfo.white, gameInfo.black);
7361 if (first.sendName) {
7362 sprintf(buf, "name %s\n", gameInfo.black);
7363 SendToProgram(buf, &first);
7365 if (first.sendTime) {
7366 if (first.useColors) {
7367 SendToProgram("black\n", &first); /*gnu kludge*/
7369 SendTimeRemaining(&first, TRUE);
7371 if (first.useColors) {
7372 SendToProgram("white\ngo\n", &first);
7374 SendToProgram("go\n", &first);
7376 SetMachineThinkingEnables();
7377 first.maybeThinking = TRUE;
7380 if (appData.autoFlipView && !flipView) {
7381 flipView = !flipView;
7382 DrawPosition(FALSE, NULL);
7391 if (appData.noChessProgram || (gameMode == MachinePlaysBlack))
7395 if (gameMode == PlayFromGameFile ||
7396 gameMode == TwoMachinesPlay ||
7397 gameMode == Training ||
7398 gameMode == AnalyzeMode ||
7399 gameMode == EndOfGame)
7402 if (gameMode == EditPosition)
7405 if (WhiteOnMove(currentMove)) {
7406 DisplayError(_("It is not Black's turn"), 0);
7410 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
7413 if (gameMode == EditGame || gameMode == AnalyzeMode ||
7414 gameMode == AnalyzeFile)
7417 ResurrectChessProgram(); /* in case it isn't running */
7418 gameMode = MachinePlaysBlack;
7422 sprintf(buf, "%s vs. %s", gameInfo.white, gameInfo.black);
7424 if (first.sendName) {
7425 sprintf(buf, "name %s\n", gameInfo.white);
7426 SendToProgram(buf, &first);
7428 if (first.sendTime) {
7429 if (first.useColors) {
7430 SendToProgram("white\n", &first); /*gnu kludge*/
7432 SendTimeRemaining(&first, FALSE);
7434 if (first.useColors) {
7435 SendToProgram("black\ngo\n", &first);
7437 SendToProgram("go\n", &first);
7439 SetMachineThinkingEnables();
7440 first.maybeThinking = TRUE;
7443 if (appData.autoFlipView && flipView) {
7444 flipView = !flipView;
7445 DrawPosition(FALSE, NULL);
7451 DisplayTwoMachinesTitle()
7454 if (appData.matchGames > 0) {
7455 if (first.twoMachinesColor[0] == 'w') {
7456 sprintf(buf, "%s vs. %s (%d-%d-%d)",
7457 gameInfo.white, gameInfo.black,
7458 first.matchWins, second.matchWins,
7459 matchGame - 1 - (first.matchWins + second.matchWins));
7461 sprintf(buf, "%s vs. %s (%d-%d-%d)",
7462 gameInfo.white, gameInfo.black,
7463 second.matchWins, first.matchWins,
7464 matchGame - 1 - (first.matchWins + second.matchWins));
7467 sprintf(buf, "%s vs. %s", gameInfo.white, gameInfo.black);
7473 TwoMachinesEvent P((void))
7477 ChessProgramState *onmove;
7479 if (appData.noChessProgram) return;
7482 case TwoMachinesPlay:
7484 case MachinePlaysWhite:
7485 case MachinePlaysBlack:
7486 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
7487 DisplayError(_("Wait until your turn,\nor select Move Now"), 0);
7491 case BeginningOfGame:
7492 case PlayFromGameFile:
7495 if (gameMode != EditGame) return;
7509 forwardMostMove = currentMove;
7510 ResurrectChessProgram(); /* in case first program isn't running */
7512 if (second.pr == NULL) {
7513 StartChessProgram(&second);
7514 if (second.protocolVersion == 1) {
7515 TwoMachinesEventIfReady();
7517 /* kludge: allow timeout for initial "feature" command */
7519 DisplayMessage("", _("Starting second chess program"));
7520 ScheduleDelayedEvent(TwoMachinesEventIfReady, FEATURE_TIMEOUT);
7524 DisplayMessage("", "");
7525 InitChessProgram(&second);
7526 SendToProgram("force\n", &second);
7527 if (startedFromSetupPosition) {
7528 SendBoard(&second, backwardMostMove);
7530 for (i = backwardMostMove; i < forwardMostMove; i++) {
7531 SendMoveToProgram(i, &second);
7534 gameMode = TwoMachinesPlay;
7538 DisplayTwoMachinesTitle();
7540 if ((first.twoMachinesColor[0] == 'w') == WhiteOnMove(forwardMostMove)) {
7546 SendToProgram(first.computerString, &first);
7547 if (first.sendName) {
7548 sprintf(buf, "name %s\n", second.tidy);
7549 SendToProgram(buf, &first);
7551 SendToProgram(second.computerString, &second);
7552 if (second.sendName) {
7553 sprintf(buf, "name %s\n", first.tidy);
7554 SendToProgram(buf, &second);
7557 if (!first.sendTime || !second.sendTime) {
7559 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
7560 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
7562 if (onmove->sendTime) {
7563 if (onmove->useColors) {
7564 SendToProgram(onmove->other->twoMachinesColor, onmove); /*gnu kludge*/
7566 SendTimeRemaining(onmove, WhiteOnMove(forwardMostMove));
7568 if (onmove->useColors) {
7569 SendToProgram(onmove->twoMachinesColor, onmove);
7571 SendToProgram("go\n", onmove);
7572 onmove->maybeThinking = TRUE;
7573 SetMachineThinkingEnables();
7581 if (gameMode == Training) {
7582 SetTrainingModeOff();
7583 gameMode = PlayFromGameFile;
7584 DisplayMessage("", _("Training mode off"));
7586 gameMode = Training;
7587 animateTraining = appData.animate;
7589 /* make sure we are not already at the end of the game */
7590 if (currentMove < forwardMostMove) {
7591 SetTrainingModeOn();
7592 DisplayMessage("", _("Training mode on"));
7594 gameMode = PlayFromGameFile;
7595 DisplayError(_("Already at end of game"), 0);
7604 if (!appData.icsActive) return;
7606 case IcsPlayingWhite:
7607 case IcsPlayingBlack:
7610 case BeginningOfGame:
7644 SetTrainingModeOff();
7646 case MachinePlaysWhite:
7647 case MachinePlaysBlack:
7648 case BeginningOfGame:
7649 SendToProgram("force\n", &first);
7650 SetUserThinkingEnables();
7652 case PlayFromGameFile:
7653 (void) StopLoadGameTimer();
7654 if (gameFileFP != NULL) {
7664 SendToProgram("force\n", &first);
7666 case TwoMachinesPlay:
7667 GameEnds((ChessMove) 0, NULL, GE_PLAYER);
7668 ResurrectChessProgram();
7669 SetUserThinkingEnables();
7672 ResurrectChessProgram();
7674 case IcsPlayingBlack:
7675 case IcsPlayingWhite:
7676 DisplayError(_("Warning: You are still playing a game"), 0);
7679 DisplayError(_("Warning: You are still observing a game"), 0);
7682 DisplayError(_("Warning: You are still examining a game"), 0);
7693 first.offeredDraw = second.offeredDraw = 0;
7695 if (gameMode == PlayFromGameFile) {
7696 whiteTimeRemaining = timeRemaining[0][currentMove];
7697 blackTimeRemaining = timeRemaining[1][currentMove];
7701 if (gameMode == MachinePlaysWhite ||
7702 gameMode == MachinePlaysBlack ||
7703 gameMode == TwoMachinesPlay ||
7704 gameMode == EndOfGame) {
7705 i = forwardMostMove;
7706 while (i > currentMove) {
7707 SendToProgram("undo\n", &first);
7710 whiteTimeRemaining = timeRemaining[0][currentMove];
7711 blackTimeRemaining = timeRemaining[1][currentMove];
7712 DisplayBothClocks();
7713 if (whiteFlag || blackFlag) {
7714 whiteFlag = blackFlag = 0;
7719 gameMode = EditGame;
7728 if (gameMode == EditPosition) {
7734 if (gameMode != EditGame) return;
7736 gameMode = EditPosition;
7739 if (currentMove > 0)
7740 CopyBoard(boards[0], boards[currentMove]);
7742 blackPlaysFirst = !WhiteOnMove(currentMove);
7744 currentMove = forwardMostMove = backwardMostMove = 0;
7745 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
7752 if (first.analysisSupport && first.analyzing) {
7753 SendToProgram("exit\n", &first);
7754 first.analyzing = FALSE;
7757 thinkOutput[0] = NULLCHAR;
7763 startedFromSetupPosition = TRUE;
7764 InitChessProgram(&first);
7765 SendToProgram("force\n", &first);
7766 if (blackPlaysFirst) {
7767 strcpy(moveList[0], "");
7768 strcpy(parseList[0], "");
7769 currentMove = forwardMostMove = backwardMostMove = 1;
7770 CopyBoard(boards[1], boards[0]);
7772 currentMove = forwardMostMove = backwardMostMove = 0;
7774 SendBoard(&first, forwardMostMove);
7776 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
7777 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
7778 gameMode = EditGame;
7780 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
7783 /* Pause for `ms' milliseconds */
7784 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
7794 } while (SubtractTimeMarks(&m2, &m1) < ms);
7797 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
7799 SendMultiLineToICS(buf)
7802 char temp[MSG_SIZ+1], *p;
7809 strncpy(temp, buf, len);
7814 if (*p == '\n' || *p == '\r')
7821 SendToPlayer(temp, strlen(temp));
7825 SetWhiteToPlayEvent()
7827 if (gameMode == EditPosition) {
7828 blackPlaysFirst = FALSE;
7829 DisplayBothClocks(); /* works because currentMove is 0 */
7830 } else if (gameMode == IcsExamining) {
7831 SendToICS(ics_prefix);
7832 SendToICS("tomove white\n");
7837 SetBlackToPlayEvent()
7839 if (gameMode == EditPosition) {
7840 blackPlaysFirst = TRUE;
7841 currentMove = 1; /* kludge */
7842 DisplayBothClocks();
7844 } else if (gameMode == IcsExamining) {
7845 SendToICS(ics_prefix);
7846 SendToICS("tomove black\n");
7851 EditPositionMenuEvent(selection, x, y)
7852 ChessSquare selection;
7857 if (gameMode != EditPosition && gameMode != IcsExamining) return;
7859 switch (selection) {
7861 if (gameMode == IcsExamining && ics_type == ICS_FICS) {
7862 SendToICS(ics_prefix);
7863 SendToICS("bsetup clear\n");
7864 } else if (gameMode == IcsExamining && ics_type == ICS_ICC) {
7865 SendToICS(ics_prefix);
7866 SendToICS("clearboard\n");
7868 for (x = 0; x < BOARD_SIZE; x++) {
7869 for (y = 0; y < BOARD_SIZE; y++) {
7870 if (gameMode == IcsExamining) {
7871 if (boards[currentMove][y][x] != EmptySquare) {
7872 sprintf(buf, "%sx@%c%c\n", ics_prefix,
7877 boards[0][y][x] = EmptySquare;
7882 if (gameMode == EditPosition) {
7883 DrawPosition(FALSE, boards[0]);
7888 SetWhiteToPlayEvent();
7892 SetBlackToPlayEvent();
7896 if (gameMode == IcsExamining) {
7897 sprintf(buf, "%sx@%c%c\n", ics_prefix, 'a' + x, '1' + y);
7900 boards[0][y][x] = EmptySquare;
7901 DrawPosition(FALSE, boards[0]);
7906 if (gameMode == IcsExamining) {
7907 sprintf(buf, "%s%c@%c%c\n", ics_prefix,
7908 PieceToChar(selection), 'a' + x, '1' + y);
7911 boards[0][y][x] = selection;
7912 DrawPosition(FALSE, boards[0]);
7920 DropMenuEvent(selection, x, y)
7921 ChessSquare selection;
7927 case IcsPlayingWhite:
7928 case MachinePlaysBlack:
7929 if (!WhiteOnMove(currentMove)) {
7930 DisplayMoveError(_("It is Black's turn"));
7933 moveType = WhiteDrop;
7935 case IcsPlayingBlack:
7936 case MachinePlaysWhite:
7937 if (WhiteOnMove(currentMove)) {
7938 DisplayMoveError(_("It is White's turn"));
7941 moveType = BlackDrop;
7944 moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
7950 if (moveType == BlackDrop && selection < BlackPawn) {
7951 selection = (ChessSquare) ((int) selection
7952 + (int) BlackPawn - (int) WhitePawn);
7954 if (boards[currentMove][y][x] != EmptySquare) {
7955 DisplayMoveError(_("That square is occupied"));
7959 FinishMove(moveType, (int) selection, DROP_RANK, x, y, NULLCHAR);
7965 /* Accept a pending offer of any kind from opponent */
7967 if (appData.icsActive) {
7968 SendToICS(ics_prefix);
7969 SendToICS("accept\n");
7970 } else if (cmailMsgLoaded) {
7971 if (currentMove == cmailOldMove &&
7972 commentList[cmailOldMove] != NULL &&
7973 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
7974 "Black offers a draw" : "White offers a draw")) {
7976 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
7977 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
7979 DisplayError(_("There is no pending offer on this move"), 0);
7980 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
7983 /* Not used for offers from chess program */
7990 /* Decline a pending offer of any kind from opponent */
7992 if (appData.icsActive) {
7993 SendToICS(ics_prefix);
7994 SendToICS("decline\n");
7995 } else if (cmailMsgLoaded) {
7996 if (currentMove == cmailOldMove &&
7997 commentList[cmailOldMove] != NULL &&
7998 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
7999 "Black offers a draw" : "White offers a draw")) {
8001 AppendComment(cmailOldMove, "Draw declined");
8002 DisplayComment(cmailOldMove - 1, "Draw declined");
8005 DisplayError(_("There is no pending offer on this move"), 0);
8008 /* Not used for offers from chess program */
8015 /* Issue ICS rematch command */
8016 if (appData.icsActive) {
8017 SendToICS(ics_prefix);
8018 SendToICS("rematch\n");
8025 /* Call your opponent's flag (claim a win on time) */
8026 if (appData.icsActive) {
8027 SendToICS(ics_prefix);
8028 SendToICS("flag\n");
8033 case MachinePlaysWhite:
8036 GameEnds(GameIsDrawn, "Both players ran out of time",
8039 GameEnds(BlackWins, "Black wins on time", GE_PLAYER);
8041 DisplayError(_("Your opponent is not out of time"), 0);
8044 case MachinePlaysBlack:
8047 GameEnds(GameIsDrawn, "Both players ran out of time",
8050 GameEnds(WhiteWins, "White wins on time", GE_PLAYER);
8052 DisplayError(_("Your opponent is not out of time"), 0);
8062 /* Offer draw or accept pending draw offer from opponent */
8064 if (appData.icsActive) {
8065 /* Note: tournament rules require draw offers to be
8066 made after you make your move but before you punch
8067 your clock. Currently ICS doesn't let you do that;
8068 instead, you immediately punch your clock after making
8069 a move, but you can offer a draw at any time. */
8071 SendToICS(ics_prefix);
8072 SendToICS("draw\n");
8073 } else if (cmailMsgLoaded) {
8074 if (currentMove == cmailOldMove &&
8075 commentList[cmailOldMove] != NULL &&
8076 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
8077 "Black offers a draw" : "White offers a draw")) {
8078 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
8079 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
8080 } else if (currentMove == cmailOldMove + 1) {
8081 char *offer = WhiteOnMove(cmailOldMove) ?
8082 "White offers a draw" : "Black offers a draw";
8083 AppendComment(currentMove, offer);
8084 DisplayComment(currentMove - 1, offer);
8085 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_DRAW;
8087 DisplayError(_("You must make your move before offering a draw"), 0);
8088 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
8090 } else if (first.offeredDraw) {
8091 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
8093 if (first.sendDrawOffers) {
8094 SendToProgram("draw\n", &first);
8095 userOfferedDraw = TRUE;
8103 /* Offer Adjourn or accept pending Adjourn offer from opponent */
8105 if (appData.icsActive) {
8106 SendToICS(ics_prefix);
8107 SendToICS("adjourn\n");
8109 /* Currently GNU Chess doesn't offer or accept Adjourns */
8117 /* Offer Abort or accept pending Abort offer from opponent */
8119 if (appData.icsActive) {
8120 SendToICS(ics_prefix);
8121 SendToICS("abort\n");
8123 GameEnds(GameUnfinished, "Game aborted", GE_PLAYER);
8130 /* Resign. You can do this even if it's not your turn. */
8132 if (appData.icsActive) {
8133 SendToICS(ics_prefix);
8134 SendToICS("resign\n");
8137 case MachinePlaysWhite:
8138 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
8140 case MachinePlaysBlack:
8141 GameEnds(BlackWins, "White resigns", GE_PLAYER);
8144 if (cmailMsgLoaded) {
8146 if (WhiteOnMove(cmailOldMove)) {
8147 GameEnds(BlackWins, "White resigns", GE_PLAYER);
8149 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
8151 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_RESIGN;
8162 StopObservingEvent()
8164 /* Stop observing current games */
8165 SendToICS(ics_prefix);
8166 SendToICS("unobserve\n");
8170 StopExaminingEvent()
8172 /* Stop observing current game */
8173 SendToICS(ics_prefix);
8174 SendToICS("unexamine\n");
8178 ForwardInner(target)
8183 if (appData.debugMode)
8184 fprintf(debugFP, "ForwardInner(%d), current %d, forward %d\n",
8185 target, currentMove, forwardMostMove);
8187 if (gameMode == EditPosition)
8190 if (gameMode == PlayFromGameFile && !pausing)
8193 if (gameMode == IcsExamining && pausing)
8194 limit = pauseExamForwardMostMove;
8196 limit = forwardMostMove;
8198 if (target > limit) target = limit;
8200 if (target > 0 && moveList[target - 1][0]) {
8201 int fromX, fromY, toX, toY;
8202 toX = moveList[target - 1][2] - 'a';
8203 toY = moveList[target - 1][3] - '1';
8204 if (moveList[target - 1][1] == '@') {
8205 if (appData.highlightLastMove) {
8206 SetHighlights(-1, -1, toX, toY);
8209 fromX = moveList[target - 1][0] - 'a';
8210 fromY = moveList[target - 1][1] - '1';
8211 if (target == currentMove + 1) {
8212 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
8214 if (appData.highlightLastMove) {
8215 SetHighlights(fromX, fromY, toX, toY);
8219 if (gameMode == EditGame || gameMode == AnalyzeMode ||
8220 gameMode == Training || gameMode == PlayFromGameFile ||
8221 gameMode == AnalyzeFile) {
8222 while (currentMove < target) {
8223 SendMoveToProgram(currentMove++, &first);
8226 currentMove = target;
8229 if (gameMode == EditGame || gameMode == EndOfGame) {
8230 whiteTimeRemaining = timeRemaining[0][currentMove];
8231 blackTimeRemaining = timeRemaining[1][currentMove];
8233 DisplayBothClocks();
8234 DisplayMove(currentMove - 1);
8235 DrawPosition(FALSE, boards[currentMove]);
8236 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
8237 if (commentList[currentMove] && !matchMode && gameMode != Training) {
8238 DisplayComment(currentMove - 1, commentList[currentMove]);
8246 if (gameMode == IcsExamining && !pausing) {
8247 SendToICS(ics_prefix);
8248 SendToICS("forward\n");
8250 ForwardInner(currentMove + 1);
8257 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
8258 /* to optimze, we temporarily turn off analysis mode while we feed
8259 * the remaining moves to the engine. Otherwise we get analysis output
8262 if (first.analysisSupport) {
8263 SendToProgram("exit\nforce\n", &first);
8264 first.analyzing = FALSE;
8268 if (gameMode == IcsExamining && !pausing) {
8269 SendToICS(ics_prefix);
8270 SendToICS("forward 999999\n");
8272 ForwardInner(forwardMostMove);
8275 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
8276 /* we have fed all the moves, so reactivate analysis mode */
8277 SendToProgram("analyze\n", &first);
8278 first.analyzing = TRUE;
8279 /*first.maybeThinking = TRUE;*/
8280 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
8285 BackwardInner(target)
8288 if (appData.debugMode)
8289 fprintf(debugFP, "BackwardInner(%d), current %d, forward %d\n",
8290 target, currentMove, forwardMostMove);
8292 if (gameMode == EditPosition) return;
8293 if (currentMove <= backwardMostMove) {
8295 DrawPosition(FALSE, boards[currentMove]);
8298 if (gameMode == PlayFromGameFile && !pausing)
8301 if (moveList[target][0]) {
8302 int fromX, fromY, toX, toY;
8303 toX = moveList[target][2] - 'a';
8304 toY = moveList[target][3] - '1';
8305 if (moveList[target][1] == '@') {
8306 if (appData.highlightLastMove) {
8307 SetHighlights(-1, -1, toX, toY);
8310 fromX = moveList[target][0] - 'a';
8311 fromY = moveList[target][1] - '1';
8312 if (target == currentMove - 1) {
8313 AnimateMove(boards[currentMove], toX, toY, fromX, fromY);
8315 if (appData.highlightLastMove) {
8316 SetHighlights(fromX, fromY, toX, toY);
8320 if (gameMode == EditGame || gameMode==AnalyzeMode ||
8321 gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
8322 while (currentMove > target) {
8323 SendToProgram("undo\n", &first);
8327 currentMove = target;
8330 if (gameMode == EditGame || gameMode == EndOfGame) {
8331 whiteTimeRemaining = timeRemaining[0][currentMove];
8332 blackTimeRemaining = timeRemaining[1][currentMove];
8334 DisplayBothClocks();
8335 DisplayMove(currentMove - 1);
8336 DrawPosition(FALSE, boards[currentMove]);
8337 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
8338 if (commentList[currentMove] != NULL) {
8339 DisplayComment(currentMove - 1, commentList[currentMove]);
8346 if (gameMode == IcsExamining && !pausing) {
8347 SendToICS(ics_prefix);
8348 SendToICS("backward\n");
8350 BackwardInner(currentMove - 1);
8357 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
8358 /* to optimze, we temporarily turn off analysis mode while we undo
8359 * all the moves. Otherwise we get analysis output after each undo.
8361 if (first.analysisSupport) {
8362 SendToProgram("exit\nforce\n", &first);
8363 first.analyzing = FALSE;
8367 if (gameMode == IcsExamining && !pausing) {
8368 SendToICS(ics_prefix);
8369 SendToICS("backward 999999\n");
8371 BackwardInner(backwardMostMove);
8374 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
8375 /* we have fed all the moves, so reactivate analysis mode */
8376 SendToProgram("analyze\n", &first);
8377 first.analyzing = TRUE;
8378 /*first.maybeThinking = TRUE;*/
8379 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
8386 if (gameMode == PlayFromGameFile && !pausing) PauseEvent();
8387 if (to >= forwardMostMove) to = forwardMostMove;
8388 if (to <= backwardMostMove) to = backwardMostMove;
8389 if (to < currentMove) {
8399 if (gameMode != IcsExamining) {
8400 DisplayError(_("You are not examining a game"), 0);
8404 DisplayError(_("You can't revert while pausing"), 0);
8407 SendToICS(ics_prefix);
8408 SendToICS("revert\n");
8415 case MachinePlaysWhite:
8416 case MachinePlaysBlack:
8417 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
8418 DisplayError(_("Wait until your turn,\nor select Move Now"), 0);
8421 if (forwardMostMove < 2) return;
8422 currentMove = forwardMostMove = forwardMostMove - 2;
8423 whiteTimeRemaining = timeRemaining[0][currentMove];
8424 blackTimeRemaining = timeRemaining[1][currentMove];
8425 DisplayBothClocks();
8426 DisplayMove(currentMove - 1);
8427 ClearHighlights();/*!! could figure this out*/
8428 DrawPosition(FALSE, boards[currentMove]);
8429 SendToProgram("remove\n", &first);
8430 /*first.maybeThinking = TRUE;*/ /* GNU Chess does not ponder here */
8433 case BeginningOfGame:
8437 case IcsPlayingWhite:
8438 case IcsPlayingBlack:
8439 if (WhiteOnMove(forwardMostMove) == (gameMode == IcsPlayingWhite)) {
8440 SendToICS(ics_prefix);
8441 SendToICS("takeback 2\n");
8443 SendToICS(ics_prefix);
8444 SendToICS("takeback 1\n");
8453 ChessProgramState *cps;
8456 case MachinePlaysWhite:
8457 if (!WhiteOnMove(forwardMostMove)) {
8458 DisplayError(_("It is your turn"), 0);
8463 case MachinePlaysBlack:
8464 if (WhiteOnMove(forwardMostMove)) {
8465 DisplayError(_("It is your turn"), 0);
8470 case TwoMachinesPlay:
8471 if (WhiteOnMove(forwardMostMove) ==
8472 (first.twoMachinesColor[0] == 'w')) {
8478 case BeginningOfGame:
8482 SendToProgram("?\n", cps);
8489 if (gameMode != EditGame) return;
8496 if (forwardMostMove > currentMove) {
8497 if (gameInfo.resultDetails != NULL) {
8498 free(gameInfo.resultDetails);
8499 gameInfo.resultDetails = NULL;
8500 gameInfo.result = GameUnfinished;
8502 forwardMostMove = currentMove;
8503 HistorySet(parseList, backwardMostMove, forwardMostMove,
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);
8527 DisplayError(_("No hint available"), 0);
8530 SendToProgram("hint\n", &first);
8531 hintRequested = TRUE;
8537 if (appData.noChessProgram) return;
8539 case MachinePlaysWhite:
8540 if (WhiteOnMove(forwardMostMove)) {
8541 DisplayError(_("Wait until your turn"), 0);
8545 case BeginningOfGame:
8546 case MachinePlaysBlack:
8547 if (!WhiteOnMove(forwardMostMove)) {
8548 DisplayError(_("Wait until your turn"), 0);
8555 case TwoMachinesPlay:
8560 SendToProgram("bk\n", &first);
8561 bookOutput[0] = NULLCHAR;
8562 bookRequested = TRUE;
8568 char *tags = PGNTags(&gameInfo);
8569 TagsPopUp(tags, CmailMsg());
8573 /* end button procedures */
8576 PrintPosition(fp, move)
8582 for (i = BOARD_SIZE - 1; i >= 0; i--) {
8583 for (j = 0; j < BOARD_SIZE; j++) {
8584 char c = PieceToChar(boards[move][i][j]);
8585 fputc(c == 'x' ? '.' : c, fp);
8586 fputc(j == BOARD_SIZE - 1 ? '\n' : ' ', fp);
8589 if ((gameMode == EditPosition) ? !blackPlaysFirst : (move % 2 == 0))
8590 fprintf(fp, "white to play\n");
8592 fprintf(fp, "black to play\n");
8599 if (gameInfo.white != NULL) {
8600 fprintf(fp, "\t%s vs. %s\n", gameInfo.white, gameInfo.black);
8606 /* Find last component of program's own name, using some heuristics */
8608 TidyProgramName(prog, host, buf)
8609 char *prog, *host, buf[MSG_SIZ];
8612 int local = (strcmp(host, "localhost") == 0);
8613 while (!local && (p = strchr(prog, ';')) != NULL) {
8615 while (*p == ' ') p++;
8618 if (*prog == '"' || *prog == '\'') {
8619 q = strchr(prog + 1, *prog);
8621 q = strchr(prog, ' ');
8623 if (q == NULL) q = prog + strlen(prog);
8625 while (p >= prog && *p != '/' && *p != '\\') p--;
8627 if (q - p >= 4 && StrCaseCmp(q - 4, ".exe") == 0) q -= 4;
8628 memcpy(buf, p, q - p);
8629 buf[q - p] = NULLCHAR;
8637 TimeControlTagValue()
8640 if (!appData.clockMode) {
8642 } else if (movesPerSession > 0) {
8643 sprintf(buf, "%d/%ld", movesPerSession, timeControl/1000);
8644 } else if (timeIncrement == 0) {
8645 sprintf(buf, "%ld", timeControl/1000);
8647 sprintf(buf, "%ld+%ld", timeControl/1000, timeIncrement/1000);
8649 return StrSave(buf);
8655 /* This routine is used only for certain modes */
8656 VariantClass v = gameInfo.variant;
8657 ClearGameInfo(&gameInfo);
8658 gameInfo.variant = v;
8661 case MachinePlaysWhite:
8662 gameInfo.event = StrSave("Computer chess game");
8663 gameInfo.site = StrSave(HostName());
8664 gameInfo.date = PGNDate();
8665 gameInfo.round = StrSave("-");
8666 gameInfo.white = StrSave(first.tidy);
8667 gameInfo.black = StrSave(UserName());
8668 gameInfo.timeControl = TimeControlTagValue();
8671 case MachinePlaysBlack:
8672 gameInfo.event = StrSave("Computer chess game");
8673 gameInfo.site = StrSave(HostName());
8674 gameInfo.date = PGNDate();
8675 gameInfo.round = StrSave("-");
8676 gameInfo.white = StrSave(UserName());
8677 gameInfo.black = StrSave(first.tidy);
8678 gameInfo.timeControl = TimeControlTagValue();
8681 case TwoMachinesPlay:
8682 gameInfo.event = StrSave("Computer chess game");
8683 gameInfo.site = StrSave(HostName());
8684 gameInfo.date = PGNDate();
8685 if (matchGame > 0) {
8687 sprintf(buf, "%d", matchGame);
8688 gameInfo.round = StrSave(buf);
8690 gameInfo.round = StrSave("-");
8692 if (first.twoMachinesColor[0] == 'w') {
8693 gameInfo.white = StrSave(first.tidy);
8694 gameInfo.black = StrSave(second.tidy);
8696 gameInfo.white = StrSave(second.tidy);
8697 gameInfo.black = StrSave(first.tidy);
8699 gameInfo.timeControl = TimeControlTagValue();
8703 gameInfo.event = StrSave("Edited game");
8704 gameInfo.site = StrSave(HostName());
8705 gameInfo.date = PGNDate();
8706 gameInfo.round = StrSave("-");
8707 gameInfo.white = StrSave("-");
8708 gameInfo.black = StrSave("-");
8712 gameInfo.event = StrSave("Edited position");
8713 gameInfo.site = StrSave(HostName());
8714 gameInfo.date = PGNDate();
8715 gameInfo.round = StrSave("-");
8716 gameInfo.white = StrSave("-");
8717 gameInfo.black = StrSave("-");
8720 case IcsPlayingWhite:
8721 case IcsPlayingBlack:
8726 case PlayFromGameFile:
8727 gameInfo.event = StrSave("Game from non-PGN file");
8728 gameInfo.site = StrSave(HostName());
8729 gameInfo.date = PGNDate();
8730 gameInfo.round = StrSave("-");
8731 gameInfo.white = StrSave("?");
8732 gameInfo.black = StrSave("?");
8741 ReplaceComment(index, text)
8747 while (*text == '\n') text++;
8749 while (len > 0 && text[len - 1] == '\n') len--;
8751 if (commentList[index] != NULL)
8752 free(commentList[index]);
8755 commentList[index] = NULL;
8758 commentList[index] = (char *) malloc(len + 2);
8759 strncpy(commentList[index], text, len);
8760 commentList[index][len] = '\n';
8761 commentList[index][len + 1] = NULLCHAR;
8774 if (ch == '\r') continue;
8776 } while (ch != '\0');
8780 AppendComment(index, text)
8788 while (*text == '\n') text++;
8790 while (len > 0 && text[len - 1] == '\n') len--;
8792 if (len == 0) return;
8794 if (commentList[index] != NULL) {
8795 old = commentList[index];
8796 oldlen = strlen(old);
8797 commentList[index] = (char *) malloc(oldlen + len + 2);
8798 strcpy(commentList[index], old);
8800 strncpy(&commentList[index][oldlen], text, len);
8801 commentList[index][oldlen + len] = '\n';
8802 commentList[index][oldlen + len + 1] = NULLCHAR;
8804 commentList[index] = (char *) malloc(len + 2);
8805 strncpy(commentList[index], text, len);
8806 commentList[index][len] = '\n';
8807 commentList[index][len + 1] = NULLCHAR;
8812 SendToProgram(message, cps)
8814 ChessProgramState *cps;
8816 int count, outCount, error;
8819 if (cps->pr == NULL) return;
8822 if (appData.debugMode) {
8825 fprintf(debugFP, "%ld >%-6s: %s",
8826 SubtractTimeMarks(&now, &programStartTime),
8827 cps->which, message);
8830 count = strlen(message);
8831 outCount = OutputToProcess(cps->pr, message, count, &error);
8832 if (outCount < count && !exiting) {
8833 sprintf(buf, _("Error writing to %s chess program"), cps->which);
8834 DisplayFatalError(buf, error, 1);
8839 ReceiveFromProgram(isr, closure, message, count, error)
8848 ChessProgramState *cps = (ChessProgramState *)closure;
8850 if (isr != cps->isr) return; /* Killed intentionally */
8854 _("Error: %s chess program (%s) exited unexpectedly"),
8855 cps->which, cps->program);
8856 RemoveInputSource(cps->isr);
8857 DisplayFatalError(buf, 0, 1);
8860 _("Error reading from %s chess program (%s)"),
8861 cps->which, cps->program);
8862 RemoveInputSource(cps->isr);
8863 DisplayFatalError(buf, error, 1);
8865 GameEnds((ChessMove) 0, NULL, GE_PLAYER);
8869 if ((end_str = strchr(message, '\r')) != NULL)
8870 *end_str = NULLCHAR;
8871 if ((end_str = strchr(message, '\n')) != NULL)
8872 *end_str = NULLCHAR;
8874 if (appData.debugMode) {
8877 fprintf(debugFP, "%ld <%-6s: %s\n",
8878 SubtractTimeMarks(&now, &programStartTime),
8879 cps->which, message);
8881 HandleMachineMove(message, cps);
8886 SendTimeControl(cps, mps, tc, inc, sd, st)
8887 ChessProgramState *cps;
8888 int mps, inc, sd, st;
8892 int seconds = (tc / 1000) % 60;
8895 /* Set exact time per move, normally using st command */
8896 if (cps->stKludge) {
8897 /* GNU Chess 4 has no st command; uses level in a nonstandard way */
8900 sprintf(buf, "level 1 %d\n", st/60);
8902 sprintf(buf, "level 1 %d:%02d\n", st/60, seconds);
8905 sprintf(buf, "st %d\n", st);
8908 /* Set conventional or incremental time control, using level command */
8910 /* Note old gnuchess bug -- minutes:seconds used to not work.
8911 Fixed in later versions, but still avoid :seconds
8912 when seconds is 0. */
8913 sprintf(buf, "level %d %ld %d\n", mps, tc/60000, inc/1000);
8915 sprintf(buf, "level %d %ld:%02d %d\n", mps, tc/60000,
8919 SendToProgram(buf, cps);
8921 /* Orthoganally (except for GNU Chess 4), limit time to st seconds */
8922 /* Orthogonally, limit search to given depth */
8924 if (cps->sdKludge) {
8925 sprintf(buf, "depth\n%d\n", sd);
8927 sprintf(buf, "sd %d\n", sd);
8929 SendToProgram(buf, cps);
8934 SendTimeRemaining(cps, machineWhite)
8935 ChessProgramState *cps;
8936 int /*boolean*/ machineWhite;
8938 char message[MSG_SIZ];
8941 /* Note: this routine must be called when the clocks are stopped
8942 or when they have *just* been set or switched; otherwise
8943 it will be off by the time since the current tick started.
8946 time = whiteTimeRemaining / 10;
8947 otime = blackTimeRemaining / 10;
8949 time = blackTimeRemaining / 10;
8950 otime = whiteTimeRemaining / 10;
8952 if (time <= 0) time = 1;
8953 if (otime <= 0) otime = 1;
8955 sprintf(message, "time %ld\notim %ld\n", time, otime);
8956 SendToProgram(message, cps);
8960 BoolFeature(p, name, loc, cps)
8964 ChessProgramState *cps;
8967 int len = strlen(name);
8969 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
8971 sscanf(*p, "%d", &val);
8973 while (**p && **p != ' ') (*p)++;
8974 sprintf(buf, "accepted %s\n", name);
8975 SendToProgram(buf, cps);
8982 IntFeature(p, name, loc, cps)
8986 ChessProgramState *cps;
8989 int len = strlen(name);
8990 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
8992 sscanf(*p, "%d", loc);
8993 while (**p && **p != ' ') (*p)++;
8994 sprintf(buf, "accepted %s\n", name);
8995 SendToProgram(buf, cps);
9002 StringFeature(p, name, loc, cps)
9006 ChessProgramState *cps;
9009 int len = strlen(name);
9010 if (strncmp((*p), name, len) == 0
9011 && (*p)[len] == '=' && (*p)[len+1] == '\"') {
9013 sscanf(*p, "%[^\"]", loc);
9014 while (**p && **p != '\"') (*p)++;
9015 if (**p == '\"') (*p)++;
9016 sprintf(buf, "accepted %s\n", name);
9017 SendToProgram(buf, cps);
9024 FeatureDone(cps, val)
9025 ChessProgramState* cps;
9028 DelayedEventCallback cb = GetDelayedEvent();
9029 if ((cb == InitBackEnd3 && cps == &first) ||
9030 (cb == TwoMachinesEventIfReady && cps == &second)) {
9031 CancelDelayedEvent();
9032 ScheduleDelayedEvent(cb, val ? 1 : 3600000);
9034 cps->initDone = val;
9037 /* Parse feature command from engine */
9039 ParseFeatures(args, cps)
9041 ChessProgramState *cps;
9049 while (*p == ' ') p++;
9050 if (*p == NULLCHAR) return;
9052 if (BoolFeature(&p, "setboard", &cps->useSetboard, cps)) continue;
9053 if (BoolFeature(&p, "time", &cps->sendTime, cps)) continue;
9054 if (BoolFeature(&p, "draw", &cps->sendDrawOffers, cps)) continue;
9055 if (BoolFeature(&p, "sigint", &cps->useSigint, cps)) continue;
9056 if (BoolFeature(&p, "sigterm", &cps->useSigterm, cps)) continue;
9057 if (BoolFeature(&p, "reuse", &val, cps)) {
9058 /* Engine can disable reuse, but can't enable it if user said no */
9059 if (!val) cps->reuse = FALSE;
9062 if (BoolFeature(&p, "analyze", &cps->analysisSupport, cps)) continue;
9063 if (StringFeature(&p, "myname", &cps->tidy, cps)) {
9064 if (gameMode == TwoMachinesPlay) {
9065 DisplayTwoMachinesTitle();
9071 if (StringFeature(&p, "variants", &cps->variants, cps)) continue;
9072 if (BoolFeature(&p, "san", &cps->useSAN, cps)) continue;
9073 if (BoolFeature(&p, "ping", &cps->usePing, cps)) continue;
9074 if (BoolFeature(&p, "playother", &cps->usePlayother, cps)) continue;
9075 if (BoolFeature(&p, "colors", &cps->useColors, cps)) continue;
9076 if (BoolFeature(&p, "usermove", &cps->useUsermove, cps)) continue;
9077 if (BoolFeature(&p, "ics", &cps->sendICS, cps)) continue;
9078 if (BoolFeature(&p, "name", &cps->sendName, cps)) continue;
9079 if (BoolFeature(&p, "pause", &val, cps)) continue; /* unused at present */
9080 if (IntFeature(&p, "done", &val, cps)) {
9081 FeatureDone(cps, val);
9085 /* unknown feature: complain and skip */
9087 while (*q && *q != '=') q++;
9088 sprintf(buf, "rejected %.*s\n", q-p, p);
9089 SendToProgram(buf, cps);
9095 while (*p && *p != '\"') p++;
9096 if (*p == '\"') p++;
9098 while (*p && *p != ' ') p++;
9106 PeriodicUpdatesEvent(newState)
9109 if (newState == appData.periodicUpdates)
9112 appData.periodicUpdates=newState;
9114 /* Display type changes, so update it now */
9117 /* Get the ball rolling again... */
9119 AnalysisPeriodicEvent(1);
9120 StartAnalysisClock();
9125 PonderNextMoveEvent(newState)
9128 if (newState == appData.ponderNextMove) return;
9129 if (gameMode == EditPosition) EditPositionDone();
9131 SendToProgram("hard\n", &first);
9132 if (gameMode == TwoMachinesPlay) {
9133 SendToProgram("hard\n", &second);
9136 SendToProgram("easy\n", &first);
9137 thinkOutput[0] = NULLCHAR;
9138 if (gameMode == TwoMachinesPlay) {
9139 SendToProgram("easy\n", &second);
9142 appData.ponderNextMove = newState;
9146 ShowThinkingEvent(newState)
9149 if (newState == appData.showThinking) return;
9150 if (gameMode == EditPosition) EditPositionDone();
9152 SendToProgram("post\n", &first);
9153 if (gameMode == TwoMachinesPlay) {
9154 SendToProgram("post\n", &second);
9157 SendToProgram("nopost\n", &first);
9158 thinkOutput[0] = NULLCHAR;
9159 if (gameMode == TwoMachinesPlay) {
9160 SendToProgram("nopost\n", &second);
9163 appData.showThinking = newState;
9167 AskQuestionEvent(title, question, replyPrefix, which)
9168 char *title; char *question; char *replyPrefix; char *which;
9170 ProcRef pr = (which[0] == '1') ? first.pr : second.pr;
9171 if (pr == NoProc) return;
9172 AskQuestion(title, question, replyPrefix, pr);
9176 DisplayMove(moveNumber)
9179 char message[MSG_SIZ];
9181 char cpThinkOutput[MSG_SIZ];
9183 if (moveNumber == forwardMostMove - 1 ||
9184 gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
9186 strcpy(cpThinkOutput, thinkOutput);
9187 if (strchr(cpThinkOutput, '\n'))
9188 *strchr(cpThinkOutput, '\n') = NULLCHAR;
9190 *cpThinkOutput = NULLCHAR;
9193 if (moveNumber == forwardMostMove - 1 &&
9194 gameInfo.resultDetails != NULL) {
9195 if (gameInfo.resultDetails[0] == NULLCHAR) {
9196 sprintf(res, " %s", PGNResult(gameInfo.result));
9198 sprintf(res, " {%s} %s",
9199 gameInfo.resultDetails, PGNResult(gameInfo.result));
9205 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
9206 DisplayMessage(res, cpThinkOutput);
9208 sprintf(message, "%d.%s%s%s", moveNumber / 2 + 1,
9209 WhiteOnMove(moveNumber) ? " " : ".. ",
9210 parseList[moveNumber], res);
9211 DisplayMessage(message, cpThinkOutput);
9216 DisplayAnalysisText(text)
9221 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
9222 sprintf(buf, "Analysis (%s)", first.tidy);
9223 AnalysisPopUp(buf, text);
9231 while (*str && isspace(*str)) ++str;
9232 while (*str && !isspace(*str)) ++str;
9233 if (!*str) return 1;
9234 while (*str && isspace(*str)) ++str;
9235 if (!*str) return 1;
9244 static char *xtra[] = { "", " (--)", " (++)" };
9247 if (programStats.time == 0) {
9248 programStats.time = 1;
9251 if (programStats.got_only_move) {
9252 strcpy(buf, programStats.movelist);
9254 nps = (((u64)programStats.nodes) /
9255 (((double)programStats.time)/100.0));
9257 cs = programStats.time % 100;
9258 s = programStats.time / 100;
9264 if (programStats.moves_left > 0 && appData.periodicUpdates) {
9265 if (programStats.move_name[0] != NULLCHAR) {
9266 sprintf(buf, "depth=%d %d/%d(%s) %+.2f %s%s\nNodes: "u64Display" NPS: %d\nTime: %02d:%02d:%02d.%02d",
9268 programStats.nr_moves-programStats.moves_left,
9269 programStats.nr_moves, programStats.move_name,
9270 ((float)programStats.score)/100.0, programStats.movelist,
9271 only_one_move(programStats.movelist)?
9272 xtra[programStats.got_fail] : "",
9273 (u64)programStats.nodes, (int)nps, h, m, s, cs);
9275 sprintf(buf, "depth=%d %d/%d %+.2f %s%s\nNodes: "u64Display" NPS: %d\nTime: %02d:%02d:%02d.%02d",
9277 programStats.nr_moves-programStats.moves_left,
9278 programStats.nr_moves, ((float)programStats.score)/100.0,
9279 programStats.movelist,
9280 only_one_move(programStats.movelist)?
9281 xtra[programStats.got_fail] : "",
9282 (u64)programStats.nodes, (int)nps, h, m, s, cs);
9285 sprintf(buf, "depth=%d %+.2f %s%s\nNodes: "u64Display" NPS: %d\nTime: %02d:%02d:%02d.%02d",
9287 ((float)programStats.score)/100.0,
9288 programStats.movelist,
9289 only_one_move(programStats.movelist)?
9290 xtra[programStats.got_fail] : "",
9291 (u64)programStats.nodes, (int)nps, h, m, s, cs);
9294 DisplayAnalysisText(buf);
9298 DisplayComment(moveNumber, text)
9302 char title[MSG_SIZ];
9304 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
9305 strcpy(title, "Comment");
9307 sprintf(title, "Comment on %d.%s%s", moveNumber / 2 + 1,
9308 WhiteOnMove(moveNumber) ? " " : ".. ",
9309 parseList[moveNumber]);
9312 CommentPopUp(title, text);
9315 /* This routine sends a ^C interrupt to gnuchess, to awaken it if it
9316 * might be busy thinking or pondering. It can be omitted if your
9317 * gnuchess is configured to stop thinking immediately on any user
9318 * input. However, that gnuchess feature depends on the FIONREAD
9319 * ioctl, which does not work properly on some flavors of Unix.
9323 ChessProgramState *cps;
9326 if (!cps->useSigint) return;
9327 if (appData.noChessProgram || (cps->pr == NoProc)) return;
9329 case MachinePlaysWhite:
9330 case MachinePlaysBlack:
9331 case TwoMachinesPlay:
9332 case IcsPlayingWhite:
9333 case IcsPlayingBlack:
9336 /* Skip if we know it isn't thinking */
9337 if (!cps->maybeThinking) return;
9338 if (appData.debugMode)
9339 fprintf(debugFP, "Interrupting %s\n", cps->which);
9340 InterruptChildProcess(cps->pr);
9341 cps->maybeThinking = FALSE;
9346 #endif /*ATTENTION*/
9352 if (whiteTimeRemaining <= 0) {
9355 if (appData.icsActive) {
9356 if (appData.autoCallFlag &&
9357 gameMode == IcsPlayingBlack && !blackFlag) {
9358 SendToICS(ics_prefix);
9359 SendToICS("flag\n");
9363 DisplayTitle(_("Both flags fell"));
9365 DisplayTitle(_("White's flag fell"));
9366 if (appData.autoCallFlag) {
9367 GameEnds(BlackWins, "Black wins on time", GE_XBOARD);
9374 if (blackTimeRemaining <= 0) {
9377 if (appData.icsActive) {
9378 if (appData.autoCallFlag &&
9379 gameMode == IcsPlayingWhite && !whiteFlag) {
9380 SendToICS(ics_prefix);
9381 SendToICS("flag\n");
9385 DisplayTitle(_("Both flags fell"));
9387 DisplayTitle(_("Black's flag fell"));
9388 if (appData.autoCallFlag) {
9389 GameEnds(WhiteWins, "White wins on time", GE_XBOARD);
9402 if (!appData.clockMode || appData.icsActive ||
9403 gameMode == PlayFromGameFile || forwardMostMove == 0) return;
9405 if (timeIncrement >= 0) {
9406 if (WhiteOnMove(forwardMostMove)) {
9407 blackTimeRemaining += timeIncrement;
9409 whiteTimeRemaining += timeIncrement;
9413 * add time to clocks when time control is achieved
9415 if (movesPerSession) {
9416 switch ((forwardMostMove + 1) % (movesPerSession * 2)) {
9418 /* White made time control */
9419 whiteTimeRemaining += timeControl;
9422 /* Black made time control */
9423 blackTimeRemaining += timeControl;
9434 int wom = gameMode == EditPosition ?
9435 !blackPlaysFirst : WhiteOnMove(currentMove);
9436 DisplayWhiteClock(whiteTimeRemaining, wom);
9437 DisplayBlackClock(blackTimeRemaining, !wom);
9441 /* Timekeeping seems to be a portability nightmare. I think everyone
9442 has ftime(), but I'm really not sure, so I'm including some ifdefs
9443 to use other calls if you don't. Clocks will be less accurate if
9444 you have neither ftime nor gettimeofday.
9447 /* Get the current time as a TimeMark */
9452 #if HAVE_GETTIMEOFDAY
9454 struct timeval timeVal;
9455 struct timezone timeZone;
9457 gettimeofday(&timeVal, &timeZone);
9458 tm->sec = (long) timeVal.tv_sec;
9459 tm->ms = (int) (timeVal.tv_usec / 1000L);
9461 #else /*!HAVE_GETTIMEOFDAY*/
9464 #include <sys/timeb.h>
9468 tm->sec = (long) timeB.time;
9469 tm->ms = (int) timeB.millitm;
9471 #else /*!HAVE_FTIME && !HAVE_GETTIMEOFDAY*/
9472 tm->sec = (long) time(NULL);
9478 /* Return the difference in milliseconds between two
9479 time marks. We assume the difference will fit in a long!
9482 SubtractTimeMarks(tm2, tm1)
9483 TimeMark *tm2, *tm1;
9485 return 1000L*(tm2->sec - tm1->sec) +
9486 (long) (tm2->ms - tm1->ms);
9491 * Code to manage the game clocks.
9493 * In tournament play, black starts the clock and then white makes a move.
9494 * We give the human user a slight advantage if he is playing white---the
9495 * clocks don't run until he makes his first move, so it takes zero time.
9496 * Also, we don't account for network lag, so we could get out of sync
9497 * with GNU Chess's clock -- but then, referees are always right.
9500 static TimeMark tickStartTM;
9501 static long intendedTickLength;
9504 NextTickLength(timeRemaining)
9507 long nominalTickLength, nextTickLength;
9509 if (timeRemaining > 0L && timeRemaining <= 10000L)
9510 nominalTickLength = 100L;
9512 nominalTickLength = 1000L;
9513 nextTickLength = timeRemaining % nominalTickLength;
9514 if (nextTickLength <= 0) nextTickLength += nominalTickLength;
9516 return nextTickLength;
9519 /* Stop clocks and reset to a fresh time control */
9523 (void) StopClockTimer();
9524 if (appData.icsActive) {
9525 whiteTimeRemaining = blackTimeRemaining = 0;
9527 whiteTimeRemaining = blackTimeRemaining = timeControl;
9529 if (whiteFlag || blackFlag) {
9531 whiteFlag = blackFlag = FALSE;
9533 DisplayBothClocks();
9536 #define FUDGE 25 /* 25ms = 1/40 sec; should be plenty even for 50 Hz clocks */
9538 /* Decrement running clock by amount of time that has passed */
9543 long lastTickLength, fudge;
9546 if (!appData.clockMode) return;
9547 if (gameMode==AnalyzeMode || gameMode == AnalyzeFile) return;
9551 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
9553 /* Fudge if we woke up a little too soon */
9554 fudge = intendedTickLength - lastTickLength;
9555 if (fudge < 0 || fudge > FUDGE) fudge = 0;
9557 if (WhiteOnMove(forwardMostMove)) {
9558 timeRemaining = whiteTimeRemaining -= lastTickLength;
9559 DisplayWhiteClock(whiteTimeRemaining - fudge,
9560 WhiteOnMove(currentMove));
9562 timeRemaining = blackTimeRemaining -= lastTickLength;
9563 DisplayBlackClock(blackTimeRemaining - fudge,
9564 !WhiteOnMove(currentMove));
9567 if (CheckFlags()) return;
9570 intendedTickLength = NextTickLength(timeRemaining - fudge) + fudge;
9571 StartClockTimer(intendedTickLength);
9573 /* if the time remaining has fallen below the alarm threshold, sound the
9574 * alarm. if the alarm has sounded and (due to a takeback or time control
9575 * with increment) the time remaining has increased to a level above the
9576 * threshold, reset the alarm so it can sound again.
9579 if (appData.icsActive && appData.icsAlarm) {
9581 /* make sure we are dealing with the user's clock */
9582 if (!( ((gameMode == IcsPlayingWhite) && WhiteOnMove(currentMove)) ||
9583 ((gameMode == IcsPlayingBlack) && !WhiteOnMove(currentMove))
9586 if (alarmSounded && (timeRemaining > appData.icsAlarmTime)) {
9587 alarmSounded = FALSE;
9588 } else if (!alarmSounded && (timeRemaining <= appData.icsAlarmTime)) {
9590 alarmSounded = TRUE;
9596 /* A player has just moved, so stop the previously running
9597 clock and (if in clock mode) start the other one.
9598 We redisplay both clocks in case we're in ICS mode, because
9599 ICS gives us an update to both clocks after every move.
9600 Note that this routine is called *after* forwardMostMove
9601 is updated, so the last fractional tick must be subtracted
9602 from the color that is *not* on move now.
9607 long lastTickLength;
9609 int flagged = FALSE;
9613 if (StopClockTimer() && appData.clockMode) {
9614 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
9615 if (WhiteOnMove(forwardMostMove)) {
9616 blackTimeRemaining -= lastTickLength;
9618 whiteTimeRemaining -= lastTickLength;
9620 flagged = CheckFlags();
9624 if (flagged || !appData.clockMode) return;
9627 case MachinePlaysBlack:
9628 case MachinePlaysWhite:
9629 case BeginningOfGame:
9630 if (pausing) return;
9634 case PlayFromGameFile:
9643 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
9644 whiteTimeRemaining : blackTimeRemaining);
9645 StartClockTimer(intendedTickLength);
9649 /* Stop both clocks */
9653 long lastTickLength;
9656 if (!StopClockTimer()) return;
9657 if (!appData.clockMode) return;
9661 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
9662 if (WhiteOnMove(forwardMostMove)) {
9663 whiteTimeRemaining -= lastTickLength;
9664 DisplayWhiteClock(whiteTimeRemaining, WhiteOnMove(currentMove));
9666 blackTimeRemaining -= lastTickLength;
9667 DisplayBlackClock(blackTimeRemaining, !WhiteOnMove(currentMove));
9672 /* Start clock of player on move. Time may have been reset, so
9673 if clock is already running, stop and restart it. */
9677 (void) StopClockTimer(); /* in case it was running already */
9678 DisplayBothClocks();
9679 if (CheckFlags()) return;
9681 if (!appData.clockMode) return;
9682 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) return;
9684 GetTimeMark(&tickStartTM);
9685 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
9686 whiteTimeRemaining : blackTimeRemaining);
9687 StartClockTimer(intendedTickLength);
9694 long second, minute, hour, day;
9696 static char buf[32];
9698 if (ms > 0 && ms <= 9900) {
9699 /* convert milliseconds to tenths, rounding up */
9700 double tenths = floor( ((double)(ms + 99L)) / 100.00 );
9702 sprintf(buf, " %03.1f ", tenths/10.0);
9706 /* convert milliseconds to seconds, rounding up */
9707 /* use floating point to avoid strangeness of integer division
9708 with negative dividends on many machines */
9709 second = (long) floor(((double) (ms + 999L)) / 1000.0);
9716 day = second / (60 * 60 * 24);
9717 second = second % (60 * 60 * 24);
9718 hour = second / (60 * 60);
9719 second = second % (60 * 60);
9720 minute = second / 60;
9721 second = second % 60;
9724 sprintf(buf, " %s%ld:%02ld:%02ld:%02ld ",
9725 sign, day, hour, minute, second);
9727 sprintf(buf, " %s%ld:%02ld:%02ld ", sign, hour, minute, second);
9729 sprintf(buf, " %s%2ld:%02ld ", sign, minute, second);
9736 * This is necessary because some C libraries aren't ANSI C compliant yet.
9739 StrStr(string, match)
9740 char *string, *match;
9744 length = strlen(match);
9746 for (i = strlen(string) - length; i >= 0; i--, string++)
9747 if (!strncmp(match, string, length))
9754 StrCaseStr(string, match)
9755 char *string, *match;
9759 length = strlen(match);
9761 for (i = strlen(string) - length; i >= 0; i--, string++) {
9762 for (j = 0; j < length; j++) {
9763 if (ToLower(match[j]) != ToLower(string[j]))
9766 if (j == length) return string;
9780 c1 = ToLower(*s1++);
9781 c2 = ToLower(*s2++);
9782 if (c1 > c2) return 1;
9783 if (c1 < c2) return -1;
9784 if (c1 == NULLCHAR) return 0;
9793 return isupper(c) ? tolower(c) : c;
9801 return islower(c) ? toupper(c) : c;
9803 #endif /* !_amigados */
9811 if ((ret = (char *) malloc(strlen(s) + 1))) {
9818 StrSavePtr(s, savePtr)
9824 if ((*savePtr = (char *) malloc(strlen(s) + 1))) {
9825 strcpy(*savePtr, s);
9837 clock = time((time_t *)NULL);
9838 tm = localtime(&clock);
9839 sprintf(buf, "%04d.%02d.%02d",
9840 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday);
9841 return StrSave(buf);
9849 int i, j, fromX, fromY, toX, toY;
9855 whiteToPlay = (gameMode == EditPosition) ?
9856 !blackPlaysFirst : (move % 2 == 0);
9859 /* Piece placement data */
9860 for (i = BOARD_SIZE - 1; i >= 0; i--) {
9862 for (j = 0; j < BOARD_SIZE; j++) {
9863 if (boards[move][i][j] == EmptySquare) {
9866 if (emptycount > 0) {
9867 *p++ = '0' + emptycount;
9870 *p++ = PieceToChar(boards[move][i][j]);
9873 if (emptycount > 0) {
9874 *p++ = '0' + emptycount;
9882 *p++ = whiteToPlay ? 'w' : 'b';
9885 /* !!We don't keep track of castling availability, so fake it */
9887 if (boards[move][0][4] == WhiteKing) {
9888 if (boards[move][0][7] == WhiteRook) *p++ = 'K';
9889 if (boards[move][0][0] == WhiteRook) *p++ = 'Q';
9891 if (boards[move][7][4] == BlackKing) {
9892 if (boards[move][7][7] == BlackRook) *p++ = 'k';
9893 if (boards[move][7][0] == BlackRook) *p++ = 'q';
9895 if (q == p) *p++ = '-';
9898 /* En passant target square */
9899 if (move > backwardMostMove) {
9900 fromX = moveList[move - 1][0] - 'a';
9901 fromY = moveList[move - 1][1] - '1';
9902 toX = moveList[move - 1][2] - 'a';
9903 toY = moveList[move - 1][3] - '1';
9904 if (fromY == (whiteToPlay ? 6 : 1) &&
9905 toY == (whiteToPlay ? 4 : 3) &&
9906 boards[move][toY][toX] == (whiteToPlay ? BlackPawn : WhitePawn) &&
9908 /* 2-square pawn move just happened */
9910 *p++ = whiteToPlay ? '6' : '3';
9918 /* !!We don't keep track of halfmove clock for 50-move rule */
9922 /* Fullmove number */
9923 sprintf(p, "%d", (move / 2) + 1);
9925 return StrSave(buf);
9929 ParseFEN(board, blackPlaysFirst, fen)
9931 int *blackPlaysFirst;
9940 /* Piece placement data */
9941 for (i = BOARD_SIZE - 1; i >= 0; i--) {
9944 if (*p == '/' || *p == ' ') {
9946 emptycount = BOARD_SIZE - j;
9947 while (emptycount--) board[i][j++] = EmptySquare;
9949 } else if (isdigit(*p)) {
9950 emptycount = *p++ - '0';
9951 if (j + emptycount > BOARD_SIZE) return FALSE;
9952 while (emptycount--) board[i][j++] = EmptySquare;
9953 } else if (isalpha(*p)) {
9954 if (j >= BOARD_SIZE) return FALSE;
9955 board[i][j++] = CharToPiece(*p++);
9961 while (*p == '/' || *p == ' ') p++;
9966 *blackPlaysFirst = FALSE;
9969 *blackPlaysFirst = TRUE;
9974 /* !!We ignore the rest of the FEN notation */
9979 EditPositionPasteFEN(char *fen)
9982 Board initial_position;
9984 if (!ParseFEN(initial_position, &blackPlaysFirst, fen)) {
9985 DisplayError(_("Bad FEN position in clipboard"), 0);
9988 int savedBlackPlaysFirst = blackPlaysFirst;
9989 EditPositionEvent();
9990 blackPlaysFirst = savedBlackPlaysFirst;
9991 CopyBoard(boards[0], initial_position);
9993 DisplayBothClocks();
9994 DrawPosition(FALSE, boards[currentMove]);