2 * backend.c -- Common back end for X and Windows NT versions of
4 * Copyright 1991 by Digital Equipment Corporation, Maynard,
7 * Enhancements Copyright 1992-2001, 2002, 2003, 2004, 2005, 2006,
8 * 2007, 2008, 2009 Free Software Foundation, Inc.
10 * Enhancements Copyright 2005 Alessandro Scotti
12 * The following terms apply to Digital Equipment Corporation's copyright
14 * ------------------------------------------------------------------------
17 * Permission to use, copy, modify, and distribute this software and its
18 * documentation for any purpose and without fee is hereby granted,
19 * provided that the above copyright notice appear in all copies and that
20 * both that copyright notice and this permission notice appear in
21 * supporting documentation, and that the name of Digital not be
22 * used in advertising or publicity pertaining to distribution of the
23 * software without specific, written prior permission.
25 * DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
26 * ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
27 * DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
28 * ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
29 * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
30 * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
32 * ------------------------------------------------------------------------
34 * The following terms apply to the enhanced version of XBoard
35 * distributed by the Free Software Foundation:
36 * ------------------------------------------------------------------------
38 * GNU XBoard is free software: you can redistribute it and/or modify
39 * it under the terms of the GNU General Public License as published by
40 * the Free Software Foundation, either version 3 of the License, or (at
41 * your option) any later version.
43 * GNU XBoard is distributed in the hope that it will be useful, but
44 * WITHOUT ANY WARRANTY; without even the implied warranty of
45 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
46 * General Public License for more details.
48 * You should have received a copy of the GNU General Public License
49 * along with this program. If not, see http://www.gnu.org/licenses/. *
51 *------------------------------------------------------------------------
52 ** See the file ChangeLog for a revision history. */
54 /* [AS] Also useful here for debugging */
58 #define DoSleep( n ) if( (n) != 0 ) Sleep( (n) );
62 #define DoSleep( n ) if( (n) >= 0) sleep(n)
72 #include <sys/types.h>
80 #else /* not STDC_HEADERS */
83 # else /* not HAVE_STRING_H */
85 # endif /* not HAVE_STRING_H */
86 #endif /* not STDC_HEADERS */
89 # include <sys/fcntl.h>
90 #else /* not HAVE_SYS_FCNTL_H */
93 # endif /* HAVE_FCNTL_H */
94 #endif /* not HAVE_SYS_FCNTL_H */
96 #if TIME_WITH_SYS_TIME
97 # include <sys/time.h>
101 # include <sys/time.h>
107 #if defined(_amigados) && !defined(__GNUC__)
112 extern int gettimeofday(struct timeval *, struct timezone *);
120 #include "frontend.h"
127 #include "backendz.h"
131 # define _(s) gettext (s)
132 # define N_(s) gettext_noop (s)
139 /* A point in time */
141 long sec; /* Assuming this is >= 32 bits */
142 int ms; /* Assuming this is >= 16 bits */
145 int establish P((void));
146 void read_from_player P((InputSourceRef isr, VOIDSTAR closure,
147 char *buf, int count, int error));
148 void read_from_ics P((InputSourceRef isr, VOIDSTAR closure,
149 char *buf, int count, int error));
150 void ics_printf P((char *format, ...));
151 void SendToICS P((char *s));
152 void SendToICSDelayed P((char *s, long msdelay));
153 void SendMoveToICS P((ChessMove moveType, int fromX, int fromY,
155 void HandleMachineMove P((char *message, ChessProgramState *cps));
156 int AutoPlayOneMove P((void));
157 int LoadGameOneMove P((ChessMove readAhead));
158 int LoadGameFromFile P((char *filename, int n, char *title, int useList));
159 int LoadPositionFromFile P((char *filename, int n, char *title));
160 int SavePositionToFile P((char *filename));
161 void ApplyMove P((int fromX, int fromY, int toX, int toY, int promoChar,
162 Board board, char *castle, char *ep));
163 void MakeMove P((int fromX, int fromY, int toX, int toY, int promoChar));
164 void ShowMove P((int fromX, int fromY, int toX, int toY));
165 int FinishMove P((ChessMove moveType, int fromX, int fromY, int toX, int toY,
166 /*char*/int promoChar));
167 void BackwardInner P((int target));
168 void ForwardInner P((int target));
169 void GameEnds P((ChessMove result, char *resultDetails, int whosays));
170 void EditPositionDone P((void));
171 void PrintOpponents P((FILE *fp));
172 void PrintPosition P((FILE *fp, int move));
173 void StartChessProgram P((ChessProgramState *cps));
174 void SendToProgram P((char *message, ChessProgramState *cps));
175 void SendMoveToProgram P((int moveNum, ChessProgramState *cps));
176 void ReceiveFromProgram P((InputSourceRef isr, VOIDSTAR closure,
177 char *buf, int count, int error));
178 void SendTimeControl P((ChessProgramState *cps,
179 int mps, long tc, int inc, int sd, int st));
180 char *TimeControlTagValue P((void));
181 void Attention P((ChessProgramState *cps));
182 void FeedMovesToProgram P((ChessProgramState *cps, int upto));
183 void ResurrectChessProgram P((void));
184 void DisplayComment P((int moveNumber, char *text));
185 void DisplayMove P((int moveNumber));
186 void DisplayAnalysis P((void));
188 void ParseGameHistory P((char *game));
189 void ParseBoard12 P((char *string));
190 void StartClocks P((void));
191 void SwitchClocks P((void));
192 void StopClocks P((void));
193 void ResetClocks P((void));
194 char *PGNDate P((void));
195 void SetGameInfo P((void));
196 Boolean ParseFEN P((Board board, int *blackPlaysFirst, char *fen));
197 int RegisterMove P((void));
198 void MakeRegisteredMove P((void));
199 void TruncateGame P((void));
200 int looking_at P((char *, int *, char *));
201 void CopyPlayerNameIntoFileName P((char **, char *));
202 char *SavePart P((char *));
203 int SaveGameOldStyle P((FILE *));
204 int SaveGamePGN P((FILE *));
205 void GetTimeMark P((TimeMark *));
206 long SubtractTimeMarks P((TimeMark *, TimeMark *));
207 int CheckFlags P((void));
208 long NextTickLength P((long));
209 void CheckTimeControl P((void));
210 void show_bytes P((FILE *, char *, int));
211 int string_to_rating P((char *str));
212 void ParseFeatures P((char* args, ChessProgramState *cps));
213 void InitBackEnd3 P((void));
214 void FeatureDone P((ChessProgramState* cps, int val));
215 void InitChessProgram P((ChessProgramState *cps, int setup));
216 void OutputKibitz(int window, char *text);
217 int PerpetualChase(int first, int last);
218 int EngineOutputIsUp();
219 void InitDrawingSizes(int x, int y);
222 extern void ConsoleCreate();
225 ChessProgramState *WhitePlayer();
226 void InsertIntoMemo P((int which, char *text)); // [HGM] kibitz: in engineo.c
227 int VerifyDisplayMode P(());
229 char *GetInfoFromComment( int, char * ); // [HGM] PV time: returns stripped comment
230 void InitEngineUCI( const char * iniDir, ChessProgramState * cps ); // [HGM] moved here from winboard.c
231 char *ProbeBook P((int moveNr, char *book)); // [HGM] book: returns a book move
232 char *SendMoveToBookUser P((int nr, ChessProgramState *cps, int initial)); // [HGM] book
233 void ics_update_width P((int new_width));
234 extern char installDir[MSG_SIZ];
236 extern int tinyLayout, smallLayout;
237 ChessProgramStats programStats;
238 static int exiting = 0; /* [HGM] moved to top */
239 static int setboardSpoiledMachineBlack = 0 /*, errorExitFlag = 0*/;
240 int startedFromPositionFile = FALSE; Board filePosition; /* [HGM] loadPos */
241 char endingGame = 0; /* [HGM] crash: flag to prevent recursion of GameEnds() */
242 int whiteNPS, blackNPS; /* [HGM] nps: for easily making clocks aware of NPS */
243 VariantClass currentlyInitializedVariant; /* [HGM] variantswitch */
244 int lastIndex = 0; /* [HGM] autoinc: last game/position used in match mode */
245 int opponentKibitzes;
246 int lastSavedGame; /* [HGM] save: ID of game */
247 char chatPartner[MAX_CHAT][MSG_SIZ]; /* [HGM] chat: list of chatting partners */
248 extern int chatCount;
251 /* States for ics_getting_history */
253 #define H_REQUESTED 1
254 #define H_GOT_REQ_HEADER 2
255 #define H_GOT_UNREQ_HEADER 3
256 #define H_GETTING_MOVES 4
257 #define H_GOT_UNWANTED_HEADER 5
259 /* whosays values for GameEnds */
268 /* Maximum number of games in a cmail message */
269 #define CMAIL_MAX_GAMES 20
271 /* Different types of move when calling RegisterMove */
273 #define CMAIL_RESIGN 1
275 #define CMAIL_ACCEPT 3
277 /* Different types of result to remember for each game */
278 #define CMAIL_NOT_RESULT 0
279 #define CMAIL_OLD_RESULT 1
280 #define CMAIL_NEW_RESULT 2
282 /* Telnet protocol constants */
293 static char * safeStrCpy( char * dst, const char * src, size_t count )
295 assert( dst != NULL );
296 assert( src != NULL );
299 strncpy( dst, src, count );
300 dst[ count-1 ] = '\0';
304 /* Some compiler can't cast u64 to double
305 * This function do the job for us:
307 * We use the highest bit for cast, this only
308 * works if the highest bit is not
309 * in use (This should not happen)
311 * We used this for all compiler
314 u64ToDouble(u64 value)
317 u64 tmp = value & u64Const(0x7fffffffffffffff);
318 r = (double)(s64)tmp;
319 if (value & u64Const(0x8000000000000000))
320 r += 9.2233720368547758080e18; /* 2^63 */
324 /* Fake up flags for now, as we aren't keeping track of castling
325 availability yet. [HGM] Change of logic: the flag now only
326 indicates the type of castlings allowed by the rule of the game.
327 The actual rights themselves are maintained in the array
328 castlingRights, as part of the game history, and are not probed
334 int flags = F_ALL_CASTLE_OK;
335 if ((index % 2) == 0) flags |= F_WHITE_ON_MOVE;
336 switch (gameInfo.variant) {
338 flags &= ~F_ALL_CASTLE_OK;
339 case VariantGiveaway: // [HGM] moved this case label one down: seems Giveaway does have castling on ICC!
340 flags |= F_IGNORE_CHECK;
342 flags |= F_MANDATORY_CAPTURE; //[HGM] losers: sets flag so TestLegality rejects non-capts if capts exist
345 flags |= F_IGNORE_CHECK | F_ATOMIC_CAPTURE;
347 case VariantKriegspiel:
348 flags |= F_KRIEGSPIEL_CAPTURE;
350 case VariantCapaRandom:
351 case VariantFischeRandom:
352 flags |= F_FRC_TYPE_CASTLING; /* [HGM] enable this through flag */
353 case VariantNoCastle:
354 case VariantShatranj:
356 flags &= ~F_ALL_CASTLE_OK;
364 FILE *gameFileFP, *debugFP;
367 [AS] Note: sometimes, the sscanf() function is used to parse the input
368 into a fixed-size buffer. Because of this, we must be prepared to
369 receive strings as long as the size of the input buffer, which is currently
370 set to 4K for Windows and 8K for the rest.
371 So, we must either allocate sufficiently large buffers here, or
372 reduce the size of the input buffer in the input reading part.
375 char cmailMove[CMAIL_MAX_GAMES][MOVE_LEN], cmailMsg[MSG_SIZ];
376 char bookOutput[MSG_SIZ*10], thinkOutput[MSG_SIZ*10], lastHint[MSG_SIZ];
377 char thinkOutput1[MSG_SIZ*10];
379 ChessProgramState first, second;
381 /* premove variables */
384 int premoveFromX = 0;
385 int premoveFromY = 0;
386 int premovePromoChar = 0;
388 Boolean alarmSounded;
389 /* end premove variables */
391 char *ics_prefix = "$";
392 int ics_type = ICS_GENERIC;
394 int currentMove = 0, forwardMostMove = 0, backwardMostMove = 0;
395 int pauseExamForwardMostMove = 0;
396 int nCmailGames = 0, nCmailResults = 0, nCmailMovesRegistered = 0;
397 int cmailMoveRegistered[CMAIL_MAX_GAMES], cmailResult[CMAIL_MAX_GAMES];
398 int cmailMsgLoaded = FALSE, cmailMailedMove = FALSE;
399 int cmailOldMove = -1, firstMove = TRUE, flipView = FALSE;
400 int blackPlaysFirst = FALSE, startedFromSetupPosition = FALSE;
401 int searchTime = 0, pausing = FALSE, pauseExamInvalid = FALSE;
402 int whiteFlag = FALSE, blackFlag = FALSE;
403 int userOfferedDraw = FALSE;
404 int ics_user_moved = 0, ics_gamenum = -1, ics_getting_history = H_FALSE;
405 int matchMode = FALSE, hintRequested = FALSE, bookRequested = FALSE;
406 int cmailMoveType[CMAIL_MAX_GAMES];
407 long ics_clock_paused = 0;
408 ProcRef icsPR = NoProc, cmailPR = NoProc;
409 InputSourceRef telnetISR = NULL, fromUserISR = NULL, cmailISR = NULL;
410 GameMode gameMode = BeginningOfGame;
411 char moveList[MAX_MOVES][MOVE_LEN], parseList[MAX_MOVES][MOVE_LEN * 2];
412 char *commentList[MAX_MOVES], *cmailCommentList[CMAIL_MAX_GAMES];
413 ChessProgramStats_Move pvInfoList[MAX_MOVES]; /* [AS] Info about engine thinking */
414 int hiddenThinkOutputState = 0; /* [AS] */
415 int adjudicateLossThreshold = 0; /* [AS] Automatic adjudication */
416 int adjudicateLossPlies = 6;
417 char white_holding[64], black_holding[64];
418 TimeMark lastNodeCountTime;
419 long lastNodeCount=0;
420 int have_sent_ICS_logon = 0;
422 long whiteTimeRemaining, blackTimeRemaining, timeControl, timeIncrement;
423 long timeControl_2; /* [AS] Allow separate time controls */
424 char *fullTimeControlString = NULL; /* [HGM] secondary TC: merge of MPS, TC and inc */
425 long timeRemaining[2][MAX_MOVES];
427 TimeMark programStartTime;
428 char ics_handle[MSG_SIZ];
429 int have_set_title = 0;
431 /* animateTraining preserves the state of appData.animate
432 * when Training mode is activated. This allows the
433 * response to be animated when appData.animate == TRUE and
434 * appData.animateDragging == TRUE.
436 Boolean animateTraining;
442 Board boards[MAX_MOVES];
443 /* [HGM] Following 7 needed for accurate legality tests: */
444 signed char epStatus[MAX_MOVES];
445 signed char castlingRights[MAX_MOVES][BOARD_SIZE]; // stores files for pieces with castling rights or -1
446 signed char castlingRank[BOARD_SIZE]; // and corresponding ranks
447 signed char initialRights[BOARD_SIZE], FENcastlingRights[BOARD_SIZE], fileRights[BOARD_SIZE];
448 int nrCastlingRights; // For TwoKings, or to implement castling-unknown status
449 int initialRulePlies, FENrulePlies;
451 FILE *serverMoves = NULL; // next two for broadcasting (/serverMoves option)
454 int mute; // mute all sounds
456 ChessSquare FIDEArray[2][BOARD_SIZE] = {
457 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
458 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
459 { BlackRook, BlackKnight, BlackBishop, BlackQueen,
460 BlackKing, BlackBishop, BlackKnight, BlackRook }
463 ChessSquare twoKingsArray[2][BOARD_SIZE] = {
464 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
465 WhiteKing, WhiteKing, WhiteKnight, WhiteRook },
466 { BlackRook, BlackKnight, BlackBishop, BlackQueen,
467 BlackKing, BlackKing, BlackKnight, BlackRook }
470 ChessSquare KnightmateArray[2][BOARD_SIZE] = {
471 { WhiteRook, WhiteMan, WhiteBishop, WhiteQueen,
472 WhiteUnicorn, WhiteBishop, WhiteMan, WhiteRook },
473 { BlackRook, BlackMan, BlackBishop, BlackQueen,
474 BlackUnicorn, BlackBishop, BlackMan, BlackRook }
477 ChessSquare fairyArray[2][BOARD_SIZE] = { /* [HGM] Queen side differs from King side */
478 { WhiteCannon, WhiteNightrider, WhiteAlfil, WhiteQueen,
479 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
480 { BlackCannon, BlackNightrider, BlackAlfil, BlackQueen,
481 BlackKing, BlackBishop, BlackKnight, BlackRook }
484 ChessSquare ShatranjArray[2][BOARD_SIZE] = { /* [HGM] (movGen knows about Shatranj Q and P) */
485 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteKing,
486 WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
487 { BlackRook, BlackKnight, BlackAlfil, BlackKing,
488 BlackFerz, BlackAlfil, BlackKnight, BlackRook }
493 ChessSquare ShogiArray[2][BOARD_SIZE] = {
494 { WhiteQueen, WhiteKnight, WhiteFerz, WhiteWazir,
495 WhiteKing, WhiteWazir, WhiteFerz, WhiteKnight, WhiteQueen },
496 { BlackQueen, BlackKnight, BlackFerz, BlackWazir,
497 BlackKing, BlackWazir, BlackFerz, BlackKnight, BlackQueen }
500 ChessSquare XiangqiArray[2][BOARD_SIZE] = {
501 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteFerz,
502 WhiteWazir, WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
503 { BlackRook, BlackKnight, BlackAlfil, BlackFerz,
504 BlackWazir, BlackFerz, BlackAlfil, BlackKnight, BlackRook }
507 ChessSquare CapablancaArray[2][BOARD_SIZE] = {
508 { WhiteRook, WhiteKnight, WhiteAngel, WhiteBishop, WhiteQueen,
509 WhiteKing, WhiteBishop, WhiteMarshall, WhiteKnight, WhiteRook },
510 { BlackRook, BlackKnight, BlackAngel, BlackBishop, BlackQueen,
511 BlackKing, BlackBishop, BlackMarshall, BlackKnight, BlackRook }
514 ChessSquare GreatArray[2][BOARD_SIZE] = {
515 { WhiteDragon, WhiteKnight, WhiteAlfil, WhiteGrasshopper, WhiteKing,
516 WhiteSilver, WhiteCardinal, WhiteAlfil, WhiteKnight, WhiteDragon },
517 { BlackDragon, BlackKnight, BlackAlfil, BlackGrasshopper, BlackKing,
518 BlackSilver, BlackCardinal, BlackAlfil, BlackKnight, BlackDragon },
521 ChessSquare JanusArray[2][BOARD_SIZE] = {
522 { WhiteRook, WhiteAngel, WhiteKnight, WhiteBishop, WhiteKing,
523 WhiteQueen, WhiteBishop, WhiteKnight, WhiteAngel, WhiteRook },
524 { BlackRook, BlackAngel, BlackKnight, BlackBishop, BlackKing,
525 BlackQueen, BlackBishop, BlackKnight, BlackAngel, BlackRook }
529 ChessSquare GothicArray[2][BOARD_SIZE] = {
530 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen, WhiteMarshall,
531 WhiteKing, WhiteAngel, WhiteBishop, WhiteKnight, WhiteRook },
532 { BlackRook, BlackKnight, BlackBishop, BlackQueen, BlackMarshall,
533 BlackKing, BlackAngel, BlackBishop, BlackKnight, BlackRook }
536 #define GothicArray CapablancaArray
540 ChessSquare FalconArray[2][BOARD_SIZE] = {
541 { WhiteRook, WhiteKnight, WhiteBishop, WhiteLance, WhiteQueen,
542 WhiteKing, WhiteLance, WhiteBishop, WhiteKnight, WhiteRook },
543 { BlackRook, BlackKnight, BlackBishop, BlackLance, BlackQueen,
544 BlackKing, BlackLance, BlackBishop, BlackKnight, BlackRook }
547 #define FalconArray CapablancaArray
550 #else // !(BOARD_SIZE>=10)
551 #define XiangqiPosition FIDEArray
552 #define CapablancaArray FIDEArray
553 #define GothicArray FIDEArray
554 #define GreatArray FIDEArray
555 #endif // !(BOARD_SIZE>=10)
558 ChessSquare CourierArray[2][BOARD_SIZE] = {
559 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteBishop, WhiteMan, WhiteKing,
560 WhiteFerz, WhiteWazir, WhiteBishop, WhiteAlfil, WhiteKnight, WhiteRook },
561 { BlackRook, BlackKnight, BlackAlfil, BlackBishop, BlackMan, BlackKing,
562 BlackFerz, BlackWazir, BlackBishop, BlackAlfil, BlackKnight, BlackRook }
564 #else // !(BOARD_SIZE>=12)
565 #define CourierArray CapablancaArray
566 #endif // !(BOARD_SIZE>=12)
569 Board initialPosition;
572 /* Convert str to a rating. Checks for special cases of "----",
574 "++++", etc. Also strips ()'s */
576 string_to_rating(str)
579 while(*str && !isdigit(*str)) ++str;
581 return 0; /* One of the special "no rating" cases */
589 /* Init programStats */
590 programStats.movelist[0] = 0;
591 programStats.depth = 0;
592 programStats.nr_moves = 0;
593 programStats.moves_left = 0;
594 programStats.nodes = 0;
595 programStats.time = -1; // [HGM] PGNtime: make invalid to recognize engine output
596 programStats.score = 0;
597 programStats.got_only_move = 0;
598 programStats.got_fail = 0;
599 programStats.line_is_book = 0;
605 int matched, min, sec;
607 ShowThinkingEvent(); // [HGM] thinking: make sure post/nopost state is set according to options
609 GetTimeMark(&programStartTime);
610 srand(programStartTime.ms); // [HGM] book: makes sure random is unpredictabe to msec level
613 programStats.ok_to_send = 1;
614 programStats.seen_stat = 0;
617 * Initialize game list
623 * Internet chess server status
625 if (appData.icsActive) {
626 appData.matchMode = FALSE;
627 appData.matchGames = 0;
629 appData.noChessProgram = !appData.zippyPlay;
631 appData.zippyPlay = FALSE;
632 appData.zippyTalk = FALSE;
633 appData.noChessProgram = TRUE;
635 if (*appData.icsHelper != NULLCHAR) {
636 appData.useTelnet = TRUE;
637 appData.telnetProgram = appData.icsHelper;
640 appData.zippyTalk = appData.zippyPlay = FALSE;
643 /* [AS] Initialize pv info list [HGM] and game state */
647 for( i=0; i<MAX_MOVES; i++ ) {
648 pvInfoList[i].depth = -1;
650 for( j=0; j<BOARD_SIZE; j++ ) castlingRights[i][j] = -1;
655 * Parse timeControl resource
657 if (!ParseTimeControl(appData.timeControl, appData.timeIncrement,
658 appData.movesPerSession)) {
660 snprintf(buf, sizeof(buf), _("bad timeControl option %s"), appData.timeControl);
661 DisplayFatalError(buf, 0, 2);
665 * Parse searchTime resource
667 if (*appData.searchTime != NULLCHAR) {
668 matched = sscanf(appData.searchTime, "%d:%d", &min, &sec);
670 searchTime = min * 60;
671 } else if (matched == 2) {
672 searchTime = min * 60 + sec;
675 snprintf(buf, sizeof(buf), _("bad searchTime option %s"), appData.searchTime);
676 DisplayFatalError(buf, 0, 2);
680 /* [AS] Adjudication threshold */
681 adjudicateLossThreshold = appData.adjudicateLossThreshold;
683 first.which = "first";
684 second.which = "second";
685 first.maybeThinking = second.maybeThinking = FALSE;
686 first.pr = second.pr = NoProc;
687 first.isr = second.isr = NULL;
688 first.sendTime = second.sendTime = 2;
689 first.sendDrawOffers = 1;
690 if (appData.firstPlaysBlack) {
691 first.twoMachinesColor = "black\n";
692 second.twoMachinesColor = "white\n";
694 first.twoMachinesColor = "white\n";
695 second.twoMachinesColor = "black\n";
697 first.program = appData.firstChessProgram;
698 second.program = appData.secondChessProgram;
699 first.host = appData.firstHost;
700 second.host = appData.secondHost;
701 first.dir = appData.firstDirectory;
702 second.dir = appData.secondDirectory;
703 first.other = &second;
704 second.other = &first;
705 first.initString = appData.initString;
706 second.initString = appData.secondInitString;
707 first.computerString = appData.firstComputerString;
708 second.computerString = appData.secondComputerString;
709 first.useSigint = second.useSigint = TRUE;
710 first.useSigterm = second.useSigterm = TRUE;
711 first.reuse = appData.reuseFirst;
712 second.reuse = appData.reuseSecond;
713 first.nps = appData.firstNPS; // [HGM] nps: copy nodes per second
714 second.nps = appData.secondNPS;
715 first.useSetboard = second.useSetboard = FALSE;
716 first.useSAN = second.useSAN = FALSE;
717 first.usePing = second.usePing = FALSE;
718 first.lastPing = second.lastPing = 0;
719 first.lastPong = second.lastPong = 0;
720 first.usePlayother = second.usePlayother = FALSE;
721 first.useColors = second.useColors = TRUE;
722 first.useUsermove = second.useUsermove = FALSE;
723 first.sendICS = second.sendICS = FALSE;
724 first.sendName = second.sendName = appData.icsActive;
725 first.sdKludge = second.sdKludge = FALSE;
726 first.stKludge = second.stKludge = FALSE;
727 TidyProgramName(first.program, first.host, first.tidy);
728 TidyProgramName(second.program, second.host, second.tidy);
729 first.matchWins = second.matchWins = 0;
730 strcpy(first.variants, appData.variant);
731 strcpy(second.variants, appData.variant);
732 first.analysisSupport = second.analysisSupport = 2; /* detect */
733 first.analyzing = second.analyzing = FALSE;
734 first.initDone = second.initDone = FALSE;
736 /* New features added by Tord: */
737 first.useFEN960 = FALSE; second.useFEN960 = FALSE;
738 first.useOOCastle = TRUE; second.useOOCastle = TRUE;
739 /* End of new features added by Tord. */
740 first.fenOverride = appData.fenOverride1;
741 second.fenOverride = appData.fenOverride2;
743 /* [HGM] time odds: set factor for each machine */
744 first.timeOdds = appData.firstTimeOdds;
745 second.timeOdds = appData.secondTimeOdds;
747 if(appData.timeOddsMode) {
748 norm = first.timeOdds;
749 if(norm > second.timeOdds) norm = second.timeOdds;
751 first.timeOdds /= norm;
752 second.timeOdds /= norm;
755 /* [HGM] secondary TC: how to handle sessions that do not fit in 'level'*/
756 first.accumulateTC = appData.firstAccumulateTC;
757 second.accumulateTC = appData.secondAccumulateTC;
758 first.maxNrOfSessions = second.maxNrOfSessions = 1;
761 first.debug = second.debug = FALSE;
762 first.supportsNPS = second.supportsNPS = UNKNOWN;
765 first.optionSettings = appData.firstOptions;
766 second.optionSettings = appData.secondOptions;
768 first.scoreIsAbsolute = appData.firstScoreIsAbsolute; /* [AS] */
769 second.scoreIsAbsolute = appData.secondScoreIsAbsolute; /* [AS] */
770 first.isUCI = appData.firstIsUCI; /* [AS] */
771 second.isUCI = appData.secondIsUCI; /* [AS] */
772 first.hasOwnBookUCI = appData.firstHasOwnBookUCI; /* [AS] */
773 second.hasOwnBookUCI = appData.secondHasOwnBookUCI; /* [AS] */
775 if (appData.firstProtocolVersion > PROTOVER ||
776 appData.firstProtocolVersion < 1) {
778 sprintf(buf, _("protocol version %d not supported"),
779 appData.firstProtocolVersion);
780 DisplayFatalError(buf, 0, 2);
782 first.protocolVersion = appData.firstProtocolVersion;
785 if (appData.secondProtocolVersion > PROTOVER ||
786 appData.secondProtocolVersion < 1) {
788 sprintf(buf, _("protocol version %d not supported"),
789 appData.secondProtocolVersion);
790 DisplayFatalError(buf, 0, 2);
792 second.protocolVersion = appData.secondProtocolVersion;
795 if (appData.icsActive) {
796 appData.clockMode = TRUE; /* changes dynamically in ICS mode */
797 } else if (*appData.searchTime != NULLCHAR || appData.noChessProgram) {
798 appData.clockMode = FALSE;
799 first.sendTime = second.sendTime = 0;
803 /* Override some settings from environment variables, for backward
804 compatibility. Unfortunately it's not feasible to have the env
805 vars just set defaults, at least in xboard. Ugh.
807 if (appData.icsActive && (appData.zippyPlay || appData.zippyTalk)) {
812 if (appData.noChessProgram) {
813 programVersion = (char*) malloc(5 + strlen(PACKAGE_STRING));
814 sprintf(programVersion, "%s", PACKAGE_STRING);
816 /* [HGM] tidy: use tidy name, in stead of full pathname (which was probably a bug due to / vs \ ) */
817 programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING) + strlen(first.tidy));
818 sprintf(programVersion, "%s + %s", PACKAGE_STRING, first.tidy);
821 if (!appData.icsActive) {
823 /* Check for variants that are supported only in ICS mode,
824 or not at all. Some that are accepted here nevertheless
825 have bugs; see comments below.
827 VariantClass variant = StringToVariant(appData.variant);
829 case VariantBughouse: /* need four players and two boards */
830 case VariantKriegspiel: /* need to hide pieces and move details */
831 /* case VariantFischeRandom: (Fabien: moved below) */
832 sprintf(buf, _("Variant %s supported only in ICS mode"), appData.variant);
833 DisplayFatalError(buf, 0, 2);
837 case VariantLoadable:
847 sprintf(buf, _("Unknown variant name %s"), appData.variant);
848 DisplayFatalError(buf, 0, 2);
851 case VariantXiangqi: /* [HGM] repetition rules not implemented */
852 case VariantFairy: /* [HGM] TestLegality definitely off! */
853 case VariantGothic: /* [HGM] should work */
854 case VariantCapablanca: /* [HGM] should work */
855 case VariantCourier: /* [HGM] initial forced moves not implemented */
856 case VariantShogi: /* [HGM] drops not tested for legality */
857 case VariantKnightmate: /* [HGM] should work */
858 case VariantCylinder: /* [HGM] untested */
859 case VariantFalcon: /* [HGM] untested */
860 case VariantCrazyhouse: /* holdings not shown, ([HGM] fixed that!)
861 offboard interposition not understood */
862 case VariantNormal: /* definitely works! */
863 case VariantWildCastle: /* pieces not automatically shuffled */
864 case VariantNoCastle: /* pieces not automatically shuffled */
865 case VariantFischeRandom: /* [HGM] works and shuffles pieces */
866 case VariantLosers: /* should work except for win condition,
867 and doesn't know captures are mandatory */
868 case VariantSuicide: /* should work except for win condition,
869 and doesn't know captures are mandatory */
870 case VariantGiveaway: /* should work except for win condition,
871 and doesn't know captures are mandatory */
872 case VariantTwoKings: /* should work */
873 case VariantAtomic: /* should work except for win condition */
874 case Variant3Check: /* should work except for win condition */
875 case VariantShatranj: /* should work except for all win conditions */
876 case VariantBerolina: /* might work if TestLegality is off */
877 case VariantCapaRandom: /* should work */
878 case VariantJanus: /* should work */
879 case VariantSuper: /* experimental */
880 case VariantGreat: /* experimental, requires legality testing to be off */
885 InitEngineUCI( installDir, &first ); // [HGM] moved here from winboard.c, to make available in xboard
886 InitEngineUCI( installDir, &second );
889 int NextIntegerFromString( char ** str, long * value )
894 while( *s == ' ' || *s == '\t' ) {
900 if( *s >= '0' && *s <= '9' ) {
901 while( *s >= '0' && *s <= '9' ) {
902 *value = *value * 10 + (*s - '0');
914 int NextTimeControlFromString( char ** str, long * value )
917 int result = NextIntegerFromString( str, &temp );
920 *value = temp * 60; /* Minutes */
923 result = NextIntegerFromString( str, &temp );
924 *value += temp; /* Seconds */
931 int NextSessionFromString( char ** str, int *moves, long * tc, long *inc)
932 { /* [HGM] routine added to read '+moves/time' for secondary time control */
933 int result = -1; long temp, temp2;
935 if(**str != '+') return -1; // old params remain in force!
937 if( NextTimeControlFromString( str, &temp ) ) return -1;
940 /* time only: incremental or sudden-death time control */
941 if(**str == '+') { /* increment follows; read it */
943 if(result = NextIntegerFromString( str, &temp2)) return -1;
946 *moves = 0; *tc = temp * 1000;
948 } else if(temp % 60 != 0) return -1; /* moves was given as min:sec */
950 (*str)++; /* classical time control */
951 result = NextTimeControlFromString( str, &temp2);
960 int GetTimeQuota(int movenr)
961 { /* [HGM] get time to add from the multi-session time-control string */
962 int moves=1; /* kludge to force reading of first session */
963 long time, increment;
964 char *s = fullTimeControlString;
966 if(appData.debugMode) fprintf(debugFP, "TC string = '%s'\n", fullTimeControlString);
968 if(moves) NextSessionFromString(&s, &moves, &time, &increment);
969 if(appData.debugMode) fprintf(debugFP, "mps=%d tc=%d inc=%d\n", moves, (int) time, (int) increment);
970 if(movenr == -1) return time; /* last move before new session */
971 if(!moves) return increment; /* current session is incremental */
972 if(movenr >= 0) movenr -= moves; /* we already finished this session */
973 } while(movenr >= -1); /* try again for next session */
975 return 0; // no new time quota on this move
979 ParseTimeControl(tc, ti, mps)
988 if(ti >= 0 && !strchr(tc, '+') && !strchr(tc, '/') ) mps = 0;
991 sprintf(buf, "+%d/%s+%d", mps, tc, ti);
992 else sprintf(buf, "+%s+%d", tc, ti);
995 sprintf(buf, "+%d/%s", mps, tc);
996 else sprintf(buf, "+%s", tc);
998 fullTimeControlString = StrSave(buf);
1000 if( NextTimeControlFromString( &tc, &tc1 ) != 0 ) {
1005 /* Parse second time control */
1008 if( NextTimeControlFromString( &tc, &tc2 ) != 0 ) {
1016 timeControl_2 = tc2 * 1000;
1026 timeControl = tc1 * 1000;
1029 timeIncrement = ti * 1000; /* convert to ms */
1030 movesPerSession = 0;
1033 movesPerSession = mps;
1041 if (appData.debugMode) {
1042 fprintf(debugFP, "%s\n", programVersion);
1045 if (appData.matchGames > 0) {
1046 appData.matchMode = TRUE;
1047 } else if (appData.matchMode) {
1048 appData.matchGames = 1;
1050 if(appData.matchMode && appData.sameColorGames > 0) /* [HGM] alternate: overrule matchGames */
1051 appData.matchGames = appData.sameColorGames;
1052 if(appData.rewindIndex > 1) { /* [HGM] autoinc: rewind implies auto-increment and overrules given index */
1053 if(appData.loadPositionIndex >= 0) appData.loadPositionIndex = -1;
1054 if(appData.loadGameIndex >= 0) appData.loadGameIndex = -1;
1057 if (appData.noChessProgram || first.protocolVersion == 1) {
1060 /* kludge: allow timeout for initial "feature" commands */
1062 DisplayMessage("", _("Starting chess program"));
1063 ScheduleDelayedEvent(InitBackEnd3, FEATURE_TIMEOUT);
1068 InitBackEnd3 P((void))
1070 GameMode initialMode;
1074 InitChessProgram(&first, startedFromSetupPosition);
1077 if (appData.icsActive) {
1079 /* [DM] Make a console window if needed [HGM] merged ifs */
1084 if (*appData.icsCommPort != NULLCHAR) {
1085 sprintf(buf, _("Could not open comm port %s"),
1086 appData.icsCommPort);
1088 snprintf(buf, sizeof(buf), _("Could not connect to host %s, port %s"),
1089 appData.icsHost, appData.icsPort);
1091 DisplayFatalError(buf, err, 1);
1096 AddInputSource(icsPR, FALSE, read_from_ics, &telnetISR);
1098 AddInputSource(NoProc, FALSE, read_from_player, &fromUserISR);
1099 } else if (appData.noChessProgram) {
1105 if (*appData.cmailGameName != NULLCHAR) {
1107 OpenLoopback(&cmailPR);
1109 AddInputSource(cmailPR, FALSE, CmailSigHandlerCallBack, &cmailISR);
1113 DisplayMessage("", "");
1114 if (StrCaseCmp(appData.initialMode, "") == 0) {
1115 initialMode = BeginningOfGame;
1116 } else if (StrCaseCmp(appData.initialMode, "TwoMachines") == 0) {
1117 initialMode = TwoMachinesPlay;
1118 } else if (StrCaseCmp(appData.initialMode, "AnalyzeFile") == 0) {
1119 initialMode = AnalyzeFile;
1120 } else if (StrCaseCmp(appData.initialMode, "Analysis") == 0) {
1121 initialMode = AnalyzeMode;
1122 } else if (StrCaseCmp(appData.initialMode, "MachineWhite") == 0) {
1123 initialMode = MachinePlaysWhite;
1124 } else if (StrCaseCmp(appData.initialMode, "MachineBlack") == 0) {
1125 initialMode = MachinePlaysBlack;
1126 } else if (StrCaseCmp(appData.initialMode, "EditGame") == 0) {
1127 initialMode = EditGame;
1128 } else if (StrCaseCmp(appData.initialMode, "EditPosition") == 0) {
1129 initialMode = EditPosition;
1130 } else if (StrCaseCmp(appData.initialMode, "Training") == 0) {
1131 initialMode = Training;
1133 sprintf(buf, _("Unknown initialMode %s"), appData.initialMode);
1134 DisplayFatalError(buf, 0, 2);
1138 if (appData.matchMode) {
1139 /* Set up machine vs. machine match */
1140 if (appData.noChessProgram) {
1141 DisplayFatalError(_("Can't have a match with no chess programs"),
1147 if (*appData.loadGameFile != NULLCHAR) {
1148 int index = appData.loadGameIndex; // [HGM] autoinc
1149 if(index<0) lastIndex = index = 1;
1150 if (!LoadGameFromFile(appData.loadGameFile,
1152 appData.loadGameFile, FALSE)) {
1153 DisplayFatalError(_("Bad game file"), 0, 1);
1156 } else if (*appData.loadPositionFile != NULLCHAR) {
1157 int index = appData.loadPositionIndex; // [HGM] autoinc
1158 if(index<0) lastIndex = index = 1;
1159 if (!LoadPositionFromFile(appData.loadPositionFile,
1161 appData.loadPositionFile)) {
1162 DisplayFatalError(_("Bad position file"), 0, 1);
1167 } else if (*appData.cmailGameName != NULLCHAR) {
1168 /* Set up cmail mode */
1169 ReloadCmailMsgEvent(TRUE);
1171 /* Set up other modes */
1172 if (initialMode == AnalyzeFile) {
1173 if (*appData.loadGameFile == NULLCHAR) {
1174 DisplayFatalError(_("AnalyzeFile mode requires a game file"), 0, 1);
1178 if (*appData.loadGameFile != NULLCHAR) {
1179 (void) LoadGameFromFile(appData.loadGameFile,
1180 appData.loadGameIndex,
1181 appData.loadGameFile, TRUE);
1182 } else if (*appData.loadPositionFile != NULLCHAR) {
1183 (void) LoadPositionFromFile(appData.loadPositionFile,
1184 appData.loadPositionIndex,
1185 appData.loadPositionFile);
1186 /* [HGM] try to make self-starting even after FEN load */
1187 /* to allow automatic setup of fairy variants with wtm */
1188 if(initialMode == BeginningOfGame && !blackPlaysFirst) {
1189 gameMode = BeginningOfGame;
1190 setboardSpoiledMachineBlack = 1;
1192 /* [HGM] loadPos: make that every new game uses the setup */
1193 /* from file as long as we do not switch variant */
1194 if(!blackPlaysFirst) { int i;
1195 startedFromPositionFile = TRUE;
1196 CopyBoard(filePosition, boards[0]);
1197 for(i=0; i<BOARD_SIZE; i++) fileRights[i] = castlingRights[0][i];
1200 if (initialMode == AnalyzeMode) {
1201 if (appData.noChessProgram) {
1202 DisplayFatalError(_("Analysis mode requires a chess engine"), 0, 2);
1205 if (appData.icsActive) {
1206 DisplayFatalError(_("Analysis mode does not work with ICS mode"),0,2);
1210 } else if (initialMode == AnalyzeFile) {
1211 appData.showThinking = TRUE; // [HGM] thinking: moved out of ShowThinkingEvent
1212 ShowThinkingEvent();
1214 AnalysisPeriodicEvent(1);
1215 } else if (initialMode == MachinePlaysWhite) {
1216 if (appData.noChessProgram) {
1217 DisplayFatalError(_("MachineWhite mode requires a chess engine"),
1221 if (appData.icsActive) {
1222 DisplayFatalError(_("MachineWhite mode does not work with ICS mode"),
1226 MachineWhiteEvent();
1227 } else if (initialMode == MachinePlaysBlack) {
1228 if (appData.noChessProgram) {
1229 DisplayFatalError(_("MachineBlack mode requires a chess engine"),
1233 if (appData.icsActive) {
1234 DisplayFatalError(_("MachineBlack mode does not work with ICS mode"),
1238 MachineBlackEvent();
1239 } else if (initialMode == TwoMachinesPlay) {
1240 if (appData.noChessProgram) {
1241 DisplayFatalError(_("TwoMachines mode requires a chess engine"),
1245 if (appData.icsActive) {
1246 DisplayFatalError(_("TwoMachines mode does not work with ICS mode"),
1251 } else if (initialMode == EditGame) {
1253 } else if (initialMode == EditPosition) {
1254 EditPositionEvent();
1255 } else if (initialMode == Training) {
1256 if (*appData.loadGameFile == NULLCHAR) {
1257 DisplayFatalError(_("Training mode requires a game file"), 0, 2);
1266 * Establish will establish a contact to a remote host.port.
1267 * Sets icsPR to a ProcRef for a process (or pseudo-process)
1268 * used to talk to the host.
1269 * Returns 0 if okay, error code if not.
1276 if (*appData.icsCommPort != NULLCHAR) {
1277 /* Talk to the host through a serial comm port */
1278 return OpenCommPort(appData.icsCommPort, &icsPR);
1280 } else if (*appData.gateway != NULLCHAR) {
1281 if (*appData.remoteShell == NULLCHAR) {
1282 /* Use the rcmd protocol to run telnet program on a gateway host */
1283 snprintf(buf, sizeof(buf), "%s %s %s",
1284 appData.telnetProgram, appData.icsHost, appData.icsPort);
1285 return OpenRcmd(appData.gateway, appData.remoteUser, buf, &icsPR);
1288 /* Use the rsh program to run telnet program on a gateway host */
1289 if (*appData.remoteUser == NULLCHAR) {
1290 snprintf(buf, sizeof(buf), "%s %s %s %s %s", appData.remoteShell,
1291 appData.gateway, appData.telnetProgram,
1292 appData.icsHost, appData.icsPort);
1294 snprintf(buf, sizeof(buf), "%s %s -l %s %s %s %s",
1295 appData.remoteShell, appData.gateway,
1296 appData.remoteUser, appData.telnetProgram,
1297 appData.icsHost, appData.icsPort);
1299 return StartChildProcess(buf, "", &icsPR);
1302 } else if (appData.useTelnet) {
1303 return OpenTelnet(appData.icsHost, appData.icsPort, &icsPR);
1306 /* TCP socket interface differs somewhat between
1307 Unix and NT; handle details in the front end.
1309 return OpenTCP(appData.icsHost, appData.icsPort, &icsPR);
1314 show_bytes(fp, buf, count)
1320 if (*buf < 040 || *(unsigned char *) buf > 0177) {
1321 fprintf(fp, "\\%03o", *buf & 0xff);
1330 /* Returns an errno value */
1332 OutputMaybeTelnet(pr, message, count, outError)
1338 char buf[8192], *p, *q, *buflim;
1339 int left, newcount, outcount;
1341 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet ||
1342 *appData.gateway != NULLCHAR) {
1343 if (appData.debugMode) {
1344 fprintf(debugFP, ">ICS: ");
1345 show_bytes(debugFP, message, count);
1346 fprintf(debugFP, "\n");
1348 return OutputToProcess(pr, message, count, outError);
1351 buflim = &buf[sizeof(buf)-1]; /* allow 1 byte for expanding last char */
1358 if (appData.debugMode) {
1359 fprintf(debugFP, ">ICS: ");
1360 show_bytes(debugFP, buf, newcount);
1361 fprintf(debugFP, "\n");
1363 outcount = OutputToProcess(pr, buf, newcount, outError);
1364 if (outcount < newcount) return -1; /* to be sure */
1371 } else if (((unsigned char) *p) == TN_IAC) {
1372 *q++ = (char) TN_IAC;
1379 if (appData.debugMode) {
1380 fprintf(debugFP, ">ICS: ");
1381 show_bytes(debugFP, buf, newcount);
1382 fprintf(debugFP, "\n");
1384 outcount = OutputToProcess(pr, buf, newcount, outError);
1385 if (outcount < newcount) return -1; /* to be sure */
1390 read_from_player(isr, closure, message, count, error)
1397 int outError, outCount;
1398 static int gotEof = 0;
1400 /* Pass data read from player on to ICS */
1403 outCount = OutputMaybeTelnet(icsPR, message, count, &outError);
1404 if (outCount < count) {
1405 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1407 } else if (count < 0) {
1408 RemoveInputSource(isr);
1409 DisplayFatalError(_("Error reading from keyboard"), error, 1);
1410 } else if (gotEof++ > 0) {
1411 RemoveInputSource(isr);
1412 DisplayFatalError(_("Got end of file from keyboard"), 0, 0);
1418 { // [HGM] alive: periodically send dummy (date) command to ICS to prevent time-out
1419 SendToICS("date\n");
1420 if(appData.keepAlive) ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
1423 /* added routine for printf style output to ics */
1424 void ics_printf(char *format, ...)
1426 char buffer[MSG_SIZ], *args;
1428 args = (char *)&format + sizeof(format);
1429 vsnprintf(buffer, sizeof(buffer), format, args);
1430 buffer[sizeof(buffer)-1] = '\0';
1438 int count, outCount, outError;
1440 if (icsPR == NULL) return;
1443 outCount = OutputMaybeTelnet(icsPR, s, count, &outError);
1444 if (outCount < count) {
1445 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1449 /* This is used for sending logon scripts to the ICS. Sending
1450 without a delay causes problems when using timestamp on ICC
1451 (at least on my machine). */
1453 SendToICSDelayed(s,msdelay)
1457 int count, outCount, outError;
1459 if (icsPR == NULL) return;
1462 if (appData.debugMode) {
1463 fprintf(debugFP, ">ICS: ");
1464 show_bytes(debugFP, s, count);
1465 fprintf(debugFP, "\n");
1467 outCount = OutputToProcessDelayed(icsPR, s, count, &outError,
1469 if (outCount < count) {
1470 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1475 /* Remove all highlighting escape sequences in s
1476 Also deletes any suffix starting with '('
1479 StripHighlightAndTitle(s)
1482 static char retbuf[MSG_SIZ];
1485 while (*s != NULLCHAR) {
1486 while (*s == '\033') {
1487 while (*s != NULLCHAR && !isalpha(*s)) s++;
1488 if (*s != NULLCHAR) s++;
1490 while (*s != NULLCHAR && *s != '\033') {
1491 if (*s == '(' || *s == '[') {
1502 /* Remove all highlighting escape sequences in s */
1507 static char retbuf[MSG_SIZ];
1510 while (*s != NULLCHAR) {
1511 while (*s == '\033') {
1512 while (*s != NULLCHAR && !isalpha(*s)) s++;
1513 if (*s != NULLCHAR) s++;
1515 while (*s != NULLCHAR && *s != '\033') {
1523 char *variantNames[] = VARIANT_NAMES;
1528 return variantNames[v];
1532 /* Identify a variant from the strings the chess servers use or the
1533 PGN Variant tag names we use. */
1540 VariantClass v = VariantNormal;
1541 int i, found = FALSE;
1546 /* [HGM] skip over optional board-size prefixes */
1547 if( sscanf(e, "%dx%d_", &i, &i) == 2 ||
1548 sscanf(e, "%dx%d+%d_", &i, &i, &i) == 3 ) {
1549 while( *e++ != '_');
1552 if(StrCaseStr(e, "misc/")) { // [HGM] on FICS, misc/shogi is not shogi
1556 for (i=0; i<sizeof(variantNames)/sizeof(char*); i++) {
1557 if (StrCaseStr(e, variantNames[i])) {
1558 v = (VariantClass) i;
1565 if ((StrCaseStr(e, "fischer") && StrCaseStr(e, "random"))
1566 || StrCaseStr(e, "wild/fr")
1567 || StrCaseStr(e, "frc") || StrCaseStr(e, "960")) {
1568 v = VariantFischeRandom;
1569 } else if ((i = 4, p = StrCaseStr(e, "wild")) ||
1570 (i = 1, p = StrCaseStr(e, "w"))) {
1572 while (*p && (isspace(*p) || *p == '(' || *p == '/')) p++;
1579 case 0: /* FICS only, actually */
1581 /* Castling legal even if K starts on d-file */
1582 v = VariantWildCastle;
1587 /* Castling illegal even if K & R happen to start in
1588 normal positions. */
1589 v = VariantNoCastle;
1602 /* Castling legal iff K & R start in normal positions */
1608 /* Special wilds for position setup; unclear what to do here */
1609 v = VariantLoadable;
1612 /* Bizarre ICC game */
1613 v = VariantTwoKings;
1616 v = VariantKriegspiel;
1622 v = VariantFischeRandom;
1625 v = VariantCrazyhouse;
1628 v = VariantBughouse;
1634 /* Not quite the same as FICS suicide! */
1635 v = VariantGiveaway;
1641 v = VariantShatranj;
1644 /* Temporary names for future ICC types. The name *will* change in
1645 the next xboard/WinBoard release after ICC defines it. */
1683 v = VariantCapablanca;
1686 v = VariantKnightmate;
1692 v = VariantCylinder;
1698 v = VariantCapaRandom;
1701 v = VariantBerolina;
1713 /* Found "wild" or "w" in the string but no number;
1714 must assume it's normal chess. */
1718 sprintf(buf, _("Unknown wild type %d"), wnum);
1719 DisplayError(buf, 0);
1725 if (appData.debugMode) {
1726 fprintf(debugFP, _("recognized '%s' (%d) as variant %s\n"),
1727 e, wnum, VariantName(v));
1732 static int leftover_start = 0, leftover_len = 0;
1733 char star_match[STAR_MATCH_N][MSG_SIZ];
1735 /* Test whether pattern is present at &buf[*index]; if so, return TRUE,
1736 advance *index beyond it, and set leftover_start to the new value of
1737 *index; else return FALSE. If pattern contains the character '*', it
1738 matches any sequence of characters not containing '\r', '\n', or the
1739 character following the '*' (if any), and the matched sequence(s) are
1740 copied into star_match.
1743 looking_at(buf, index, pattern)
1748 char *bufp = &buf[*index], *patternp = pattern;
1750 char *matchp = star_match[0];
1753 if (*patternp == NULLCHAR) {
1754 *index = leftover_start = bufp - buf;
1758 if (*bufp == NULLCHAR) return FALSE;
1759 if (*patternp == '*') {
1760 if (*bufp == *(patternp + 1)) {
1762 matchp = star_match[++star_count];
1766 } else if (*bufp == '\n' || *bufp == '\r') {
1768 if (*patternp == NULLCHAR)
1773 *matchp++ = *bufp++;
1777 if (*patternp != *bufp) return FALSE;
1784 SendToPlayer(data, length)
1788 int error, outCount;
1789 outCount = OutputToProcess(NoProc, data, length, &error);
1790 if (outCount < length) {
1791 DisplayFatalError(_("Error writing to display"), error, 1);
1796 PackHolding(packed, holding)
1808 switch (runlength) {
1819 sprintf(q, "%d", runlength);
1831 /* Telnet protocol requests from the front end */
1833 TelnetRequest(ddww, option)
1834 unsigned char ddww, option;
1836 unsigned char msg[3];
1837 int outCount, outError;
1839 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet) return;
1841 if (appData.debugMode) {
1842 char buf1[8], buf2[8], *ddwwStr, *optionStr;
1858 sprintf(buf1, "%d", ddww);
1867 sprintf(buf2, "%d", option);
1870 fprintf(debugFP, ">%s %s ", ddwwStr, optionStr);
1875 outCount = OutputToProcess(icsPR, (char *)msg, 3, &outError);
1877 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1884 if (!appData.icsActive) return;
1885 TelnetRequest(TN_DO, TN_ECHO);
1891 if (!appData.icsActive) return;
1892 TelnetRequest(TN_DONT, TN_ECHO);
1896 CopyHoldings(Board board, char *holdings, ChessSquare lowestPiece)
1898 /* put the holdings sent to us by the server on the board holdings area */
1899 int i, j, holdingsColumn, holdingsStartRow, direction, countsColumn;
1903 if(gameInfo.holdingsWidth < 2) return;
1905 if( (int)lowestPiece >= BlackPawn ) {
1908 holdingsStartRow = BOARD_HEIGHT-1;
1911 holdingsColumn = BOARD_WIDTH-1;
1912 countsColumn = BOARD_WIDTH-2;
1913 holdingsStartRow = 0;
1917 for(i=0; i<BOARD_HEIGHT; i++) { /* clear holdings */
1918 board[i][holdingsColumn] = EmptySquare;
1919 board[i][countsColumn] = (ChessSquare) 0;
1921 while( (p=*holdings++) != NULLCHAR ) {
1922 piece = CharToPiece( ToUpper(p) );
1923 if(piece == EmptySquare) continue;
1924 /*j = (int) piece - (int) WhitePawn;*/
1925 j = PieceToNumber(piece);
1926 if(j >= gameInfo.holdingsSize) continue; /* ignore pieces that do not fit */
1927 if(j < 0) continue; /* should not happen */
1928 piece = (ChessSquare) ( (int)piece + (int)lowestPiece );
1929 board[holdingsStartRow+j*direction][holdingsColumn] = piece;
1930 board[holdingsStartRow+j*direction][countsColumn]++;
1937 VariantSwitch(Board board, VariantClass newVariant)
1939 int newHoldingsWidth, newWidth = 8, newHeight = 8, i, j;
1940 int oldCurrentMove = currentMove, oldForwardMostMove = forwardMostMove, oldBackwardMostMove = backwardMostMove;
1941 // Board tempBoard; int saveCastling[BOARD_SIZE], saveEP;
1943 startedFromPositionFile = FALSE;
1944 if(gameInfo.variant == newVariant) return;
1946 /* [HGM] This routine is called each time an assignment is made to
1947 * gameInfo.variant during a game, to make sure the board sizes
1948 * are set to match the new variant. If that means adding or deleting
1949 * holdings, we shift the playing board accordingly
1950 * This kludge is needed because in ICS observe mode, we get boards
1951 * of an ongoing game without knowing the variant, and learn about the
1952 * latter only later. This can be because of the move list we requested,
1953 * in which case the game history is refilled from the beginning anyway,
1954 * but also when receiving holdings of a crazyhouse game. In the latter
1955 * case we want to add those holdings to the already received position.
1959 if (appData.debugMode) {
1960 fprintf(debugFP, "Switch board from %s to %s\n",
1961 VariantName(gameInfo.variant), VariantName(newVariant));
1962 setbuf(debugFP, NULL);
1964 shuffleOpenings = 0; /* [HGM] shuffle */
1965 gameInfo.holdingsSize = 5; /* [HGM] prepare holdings */
1966 switch(newVariant) {
1968 newWidth = 9; newHeight = 9;
1969 gameInfo.holdingsSize = 7;
1970 case VariantBughouse:
1971 case VariantCrazyhouse:
1972 newHoldingsWidth = 2; break;
1974 newHoldingsWidth = gameInfo.holdingsSize = 0;
1977 if(newWidth != gameInfo.boardWidth ||
1978 newHeight != gameInfo.boardHeight ||
1979 newHoldingsWidth != gameInfo.holdingsWidth ) {
1981 /* shift position to new playing area, if needed */
1982 if(newHoldingsWidth > gameInfo.holdingsWidth) {
1983 for(i=0; i<BOARD_HEIGHT; i++)
1984 for(j=BOARD_RGHT-1; j>=BOARD_LEFT; j--)
1985 board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
1987 for(i=0; i<newHeight; i++) {
1988 board[i][0] = board[i][newWidth+2*newHoldingsWidth-1] = EmptySquare;
1989 board[i][1] = board[i][newWidth+2*newHoldingsWidth-2] = (ChessSquare) 0;
1991 } else if(newHoldingsWidth < gameInfo.holdingsWidth) {
1992 for(i=0; i<BOARD_HEIGHT; i++)
1993 for(j=BOARD_LEFT; j<BOARD_RGHT; j++)
1994 board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
1998 gameInfo.boardWidth = newWidth;
1999 gameInfo.boardHeight = newHeight;
2000 gameInfo.holdingsWidth = newHoldingsWidth;
2001 gameInfo.variant = newVariant;
2002 InitDrawingSizes(-2, 0);
2004 /* [HGM] The following should definitely be solved in a better way */
2005 InitPosition(FALSE); /* this sets up board[0], but also other stuff */
2006 } else { gameInfo.variant = newVariant; InitPosition(FALSE); }
2008 forwardMostMove = oldForwardMostMove;
2009 backwardMostMove = oldBackwardMostMove;
2010 currentMove = oldCurrentMove; /* InitPos reset these, but we need still to redraw the position */
2013 static int loggedOn = FALSE;
2015 /*-- Game start info cache: --*/
2017 char gs_kind[MSG_SIZ];
2018 static char player1Name[128] = "";
2019 static char player2Name[128] = "";
2020 static int player1Rating = -1;
2021 static int player2Rating = -1;
2022 /*----------------------------*/
2024 ColorClass curColor = ColorNormal;
2025 int suppressKibitz = 0;
2028 read_from_ics(isr, closure, data, count, error)
2035 #define BUF_SIZE 8192
2036 #define STARTED_NONE 0
2037 #define STARTED_MOVES 1
2038 #define STARTED_BOARD 2
2039 #define STARTED_OBSERVE 3
2040 #define STARTED_HOLDINGS 4
2041 #define STARTED_CHATTER 5
2042 #define STARTED_COMMENT 6
2043 #define STARTED_MOVES_NOHIDE 7
2045 static int started = STARTED_NONE;
2046 static char parse[20000];
2047 static int parse_pos = 0;
2048 static char buf[BUF_SIZE + 1];
2049 static int firstTime = TRUE, intfSet = FALSE;
2050 static ColorClass prevColor = ColorNormal;
2051 static int savingComment = FALSE;
2057 int backup; /* [DM] For zippy color lines */
2059 char talker[MSG_SIZ]; // [HGM] chat
2062 if (appData.debugMode) {
2064 fprintf(debugFP, "<ICS: ");
2065 show_bytes(debugFP, data, count);
2066 fprintf(debugFP, "\n");
2070 if (appData.debugMode) { int f = forwardMostMove;
2071 fprintf(debugFP, "ics input %d, castling = %d %d %d %d %d %d\n", f,
2072 castlingRights[f][0],castlingRights[f][1],castlingRights[f][2],castlingRights[f][3],castlingRights[f][4],castlingRights[f][5]);
2075 /* If last read ended with a partial line that we couldn't parse,
2076 prepend it to the new read and try again. */
2077 if (leftover_len > 0) {
2078 for (i=0; i<leftover_len; i++)
2079 buf[i] = buf[leftover_start + i];
2082 /* Copy in new characters, removing nulls and \r's */
2083 buf_len = leftover_len;
2084 for (i = 0; i < count; i++) {
2085 if (data[i] != NULLCHAR && data[i] != '\r')
2086 buf[buf_len++] = data[i];
2087 if(!appData.noJoin && buf_len >= 5 && buf[buf_len-5]=='\n' && buf[buf_len-4]=='\\' &&
2088 buf[buf_len-3]==' ' && buf[buf_len-2]==' ' && buf[buf_len-1]==' ') {
2089 buf_len -= 5; // [HGM] ICS: join continuation line of Lasker 2.2.3 server with previous
2090 if(buf_len == 0 || buf[buf_len-1] != ' ')
2091 buf[buf_len++] = ' '; // add space (assumes ICS does not break lines within word)
2095 buf[buf_len] = NULLCHAR;
2096 next_out = leftover_len;
2100 while (i < buf_len) {
2101 /* Deal with part of the TELNET option negotiation
2102 protocol. We refuse to do anything beyond the
2103 defaults, except that we allow the WILL ECHO option,
2104 which ICS uses to turn off password echoing when we are
2105 directly connected to it. We reject this option
2106 if localLineEditing mode is on (always on in xboard)
2107 and we are talking to port 23, which might be a real
2108 telnet server that will try to keep WILL ECHO on permanently.
2110 if (buf_len - i >= 3 && (unsigned char) buf[i] == TN_IAC) {
2111 static int remoteEchoOption = FALSE; /* telnet ECHO option */
2112 unsigned char option;
2114 switch ((unsigned char) buf[++i]) {
2116 if (appData.debugMode)
2117 fprintf(debugFP, "\n<WILL ");
2118 switch (option = (unsigned char) buf[++i]) {
2120 if (appData.debugMode)
2121 fprintf(debugFP, "ECHO ");
2122 /* Reply only if this is a change, according
2123 to the protocol rules. */
2124 if (remoteEchoOption) break;
2125 if (appData.localLineEditing &&
2126 atoi(appData.icsPort) == TN_PORT) {
2127 TelnetRequest(TN_DONT, TN_ECHO);
2130 TelnetRequest(TN_DO, TN_ECHO);
2131 remoteEchoOption = TRUE;
2135 if (appData.debugMode)
2136 fprintf(debugFP, "%d ", option);
2137 /* Whatever this is, we don't want it. */
2138 TelnetRequest(TN_DONT, option);
2143 if (appData.debugMode)
2144 fprintf(debugFP, "\n<WONT ");
2145 switch (option = (unsigned char) buf[++i]) {
2147 if (appData.debugMode)
2148 fprintf(debugFP, "ECHO ");
2149 /* Reply only if this is a change, according
2150 to the protocol rules. */
2151 if (!remoteEchoOption) break;
2153 TelnetRequest(TN_DONT, TN_ECHO);
2154 remoteEchoOption = FALSE;
2157 if (appData.debugMode)
2158 fprintf(debugFP, "%d ", (unsigned char) option);
2159 /* Whatever this is, it must already be turned
2160 off, because we never agree to turn on
2161 anything non-default, so according to the
2162 protocol rules, we don't reply. */
2167 if (appData.debugMode)
2168 fprintf(debugFP, "\n<DO ");
2169 switch (option = (unsigned char) buf[++i]) {
2171 /* Whatever this is, we refuse to do it. */
2172 if (appData.debugMode)
2173 fprintf(debugFP, "%d ", option);
2174 TelnetRequest(TN_WONT, option);
2179 if (appData.debugMode)
2180 fprintf(debugFP, "\n<DONT ");
2181 switch (option = (unsigned char) buf[++i]) {
2183 if (appData.debugMode)
2184 fprintf(debugFP, "%d ", option);
2185 /* Whatever this is, we are already not doing
2186 it, because we never agree to do anything
2187 non-default, so according to the protocol
2188 rules, we don't reply. */
2193 if (appData.debugMode)
2194 fprintf(debugFP, "\n<IAC ");
2195 /* Doubled IAC; pass it through */
2199 if (appData.debugMode)
2200 fprintf(debugFP, "\n<%d ", (unsigned char) buf[i]);
2201 /* Drop all other telnet commands on the floor */
2204 if (oldi > next_out)
2205 SendToPlayer(&buf[next_out], oldi - next_out);
2211 /* OK, this at least will *usually* work */
2212 if (!loggedOn && looking_at(buf, &i, "ics%")) {
2216 if (loggedOn && !intfSet) {
2217 if (ics_type == ICS_ICC) {
2219 "/set-quietly interface %s\n/set-quietly style 12\n",
2221 strcat(str, "/set-quietly wrap 0\n");
2223 } else if (ics_type == ICS_CHESSNET) {
2224 sprintf(str, "/style 12\n");
2226 strcpy(str, "alias $ @\n$set interface ");
2227 strcat(str, programVersion);
2228 strcat(str, "\n$iset startpos 1\n$iset ms 1\n");
2230 strcat(str, "$iset nohighlight 1\n");
2232 strcat(str, "$iset nowrap 1\n");
2233 strcat(str, "$iset lock 1\n$style 12\n");
2236 NotifyFrontendLogin();
2240 if (started == STARTED_COMMENT) {
2241 /* Accumulate characters in comment */
2242 parse[parse_pos++] = buf[i];
2243 if (buf[i] == '\n') {
2244 parse[parse_pos] = NULLCHAR;
2245 if(chattingPartner>=0) {
2247 sprintf(mess, "%s%s", talker, parse);
2248 OutputChatMessage(chattingPartner, mess);
2249 chattingPartner = -1;
2251 if(!suppressKibitz) // [HGM] kibitz
2252 AppendComment(forwardMostMove, StripHighlight(parse));
2253 else { // [HGM kibitz: divert memorized engine kibitz to engine-output window
2254 int nrDigit = 0, nrAlph = 0, i;
2255 if(parse_pos > MSG_SIZ - 30) // defuse unreasonably long input
2256 { parse_pos = MSG_SIZ-30; parse[parse_pos - 1] = '\n'; }
2257 parse[parse_pos] = NULLCHAR;
2258 // try to be smart: if it does not look like search info, it should go to
2259 // ICS interaction window after all, not to engine-output window.
2260 for(i=0; i<parse_pos; i++) { // count letters and digits
2261 nrDigit += (parse[i] >= '0' && parse[i] <= '9');
2262 nrAlph += (parse[i] >= 'a' && parse[i] <= 'z');
2263 nrAlph += (parse[i] >= 'A' && parse[i] <= 'Z');
2265 if(nrAlph < 9*nrDigit) { // if more than 10% digit we assume search info
2266 int depth=0; float score;
2267 if(sscanf(parse, "!!! %f/%d", &score, &depth) == 2 && depth>0) {
2268 // [HGM] kibitz: save kibitzed opponent info for PGN and eval graph
2269 pvInfoList[forwardMostMove-1].depth = depth;
2270 pvInfoList[forwardMostMove-1].score = 100*score;
2272 OutputKibitz(suppressKibitz, parse);
2275 sprintf(tmp, _("your opponent kibitzes: %s"), parse);
2276 SendToPlayer(tmp, strlen(tmp));
2279 started = STARTED_NONE;
2281 /* Don't match patterns against characters in chatter */
2286 if (started == STARTED_CHATTER) {
2287 if (buf[i] != '\n') {
2288 /* Don't match patterns against characters in chatter */
2292 started = STARTED_NONE;
2295 /* Kludge to deal with rcmd protocol */
2296 if (firstTime && looking_at(buf, &i, "\001*")) {
2297 DisplayFatalError(&buf[1], 0, 1);
2303 if (!loggedOn && looking_at(buf, &i, "chessclub.com")) {
2306 if (appData.debugMode)
2307 fprintf(debugFP, "ics_type %d\n", ics_type);
2310 if (!loggedOn && looking_at(buf, &i, "freechess.org")) {
2311 ics_type = ICS_FICS;
2313 if (appData.debugMode)
2314 fprintf(debugFP, "ics_type %d\n", ics_type);
2317 if (!loggedOn && looking_at(buf, &i, "chess.net")) {
2318 ics_type = ICS_CHESSNET;
2320 if (appData.debugMode)
2321 fprintf(debugFP, "ics_type %d\n", ics_type);
2326 (looking_at(buf, &i, "\"*\" is *a registered name") ||
2327 looking_at(buf, &i, "Logging you in as \"*\"") ||
2328 looking_at(buf, &i, "will be \"*\""))) {
2329 strcpy(ics_handle, star_match[0]);
2333 if (loggedOn && !have_set_title && ics_handle[0] != NULLCHAR) {
2335 snprintf(buf, sizeof(buf), "%s@%s", ics_handle, appData.icsHost);
2336 DisplayIcsInteractionTitle(buf);
2337 have_set_title = TRUE;
2340 /* skip finger notes */
2341 if (started == STARTED_NONE &&
2342 ((buf[i] == ' ' && isdigit(buf[i+1])) ||
2343 (buf[i] == '1' && buf[i+1] == '0')) &&
2344 buf[i+2] == ':' && buf[i+3] == ' ') {
2345 started = STARTED_CHATTER;
2350 /* skip formula vars */
2351 if (started == STARTED_NONE &&
2352 buf[i] == 'f' && isdigit(buf[i+1]) && buf[i+2] == ':') {
2353 started = STARTED_CHATTER;
2359 // [HGM] kibitz: try to recognize opponent engine-score kibitzes, to divert them to engine-output window
2360 if (appData.autoKibitz && started == STARTED_NONE &&
2361 !appData.icsEngineAnalyze && // [HGM] [DM] ICS analyze
2362 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack || gameMode == IcsObserving)) {
2363 if(looking_at(buf, &i, "* kibitzes: ") &&
2364 (StrStr(star_match[0], gameInfo.white) == star_match[0] ||
2365 StrStr(star_match[0], gameInfo.black) == star_match[0] )) { // kibitz of self or opponent
2366 suppressKibitz = TRUE;
2367 if((StrStr(star_match[0], gameInfo.white) == star_match[0]
2368 && (gameMode == IcsPlayingWhite)) ||
2369 (StrStr(star_match[0], gameInfo.black) == star_match[0]
2370 && (gameMode == IcsPlayingBlack)) ) // opponent kibitz
2371 started = STARTED_CHATTER; // own kibitz we simply discard
2373 started = STARTED_COMMENT; // make sure it will be collected in parse[]
2374 parse_pos = 0; parse[0] = NULLCHAR;
2375 savingComment = TRUE;
2376 suppressKibitz = gameMode != IcsObserving ? 2 :
2377 (StrStr(star_match[0], gameInfo.white) == NULL) + 1;
2381 if(looking_at(buf, &i, "kibitzed to")) { // suppress the acknowledgements of our own autoKibitz
2382 started = STARTED_CHATTER;
2383 suppressKibitz = TRUE;
2385 } // [HGM] kibitz: end of patch
2387 //if(appData.debugMode) fprintf(debugFP, "hunt for tell, buf = %s\n", buf+i);
2389 // [HGM] chat: intercept tells by users for which we have an open chat window
2391 if(started == STARTED_NONE && (looking_at(buf, &i, "* tells you:") || looking_at(buf, &i, "* says:") ||
2392 looking_at(buf, &i, "* whispers:") ||
2393 looking_at(buf, &i, "*(*):") && (sscanf(star_match[1], "%d", &channel),1) ||
2394 looking_at(buf, &i, "*(*)(*):") && sscanf(star_match[2], "%d", &channel) == 1 )) {
2396 sscanf(star_match[0], "%[^(]", talker+1); // strip (C) or (U) off ICS handle
2397 chattingPartner = -1;
2399 if(channel >= 0) // channel broadcast; look if there is a chatbox for this channel
2400 for(p=0; p<MAX_CHAT; p++) {
2401 if(channel == atoi(chatPartner[p])) {
2402 talker[0] = '['; strcat(talker, "]");
2403 chattingPartner = p; break;
2406 if(buf[i-3] == 'r') // whisper; look if there is a WHISPER chatbox
2407 for(p=0; p<MAX_CHAT; p++) {
2408 if(!strcmp("WHISPER", chatPartner[p])) {
2409 talker[0] = '['; strcat(talker, "]");
2410 chattingPartner = p; break;
2413 if(chattingPartner<0) // if not, look if there is a chatbox for this indivdual
2414 for(p=0; p<MAX_CHAT; p++) if(!StrCaseCmp(talker+1, chatPartner[p])) {
2416 chattingPartner = p; break;
2418 if(chattingPartner<0) i = oldi; else {
2419 started = STARTED_COMMENT;
2420 parse_pos = 0; parse[0] = NULLCHAR;
2421 savingComment = TRUE;
2422 suppressKibitz = TRUE;
2424 } // [HGM] chat: end of patch
2426 if (appData.zippyTalk || appData.zippyPlay) {
2427 /* [DM] Backup address for color zippy lines */
2431 if (loggedOn == TRUE)
2432 if (ZippyControl(buf, &backup) || ZippyConverse(buf, &backup) ||
2433 (appData.zippyPlay && ZippyMatch(buf, &backup)));
2435 if (ZippyControl(buf, &i) ||
2436 ZippyConverse(buf, &i) ||
2437 (appData.zippyPlay && ZippyMatch(buf, &i))) {
2439 if (!appData.colorize) continue;
2443 } // [DM] 'else { ' deleted
2445 /* Regular tells and says */
2446 (tkind = 1, looking_at(buf, &i, "* tells you: ")) ||
2447 looking_at(buf, &i, "* (your partner) tells you: ") ||
2448 looking_at(buf, &i, "* says: ") ||
2449 /* Don't color "message" or "messages" output */
2450 (tkind = 5, looking_at(buf, &i, "*. * (*:*): ")) ||
2451 looking_at(buf, &i, "*. * at *:*: ") ||
2452 looking_at(buf, &i, "--* (*:*): ") ||
2453 /* Message notifications (same color as tells) */
2454 looking_at(buf, &i, "* has left a message ") ||
2455 looking_at(buf, &i, "* just sent you a message:\n") ||
2456 /* Whispers and kibitzes */
2457 (tkind = 2, looking_at(buf, &i, "* whispers: ")) ||
2458 looking_at(buf, &i, "* kibitzes: ") ||
2460 (tkind = 3, looking_at(buf, &i, "*(*: "))) {
2462 if (tkind == 1 && strchr(star_match[0], ':')) {
2463 /* Avoid "tells you:" spoofs in channels */
2466 if (star_match[0][0] == NULLCHAR ||
2467 strchr(star_match[0], ' ') ||
2468 (tkind == 3 && strchr(star_match[1], ' '))) {
2469 /* Reject bogus matches */
2472 if (appData.colorize) {
2473 if (oldi > next_out) {
2474 SendToPlayer(&buf[next_out], oldi - next_out);
2479 Colorize(ColorTell, FALSE);
2480 curColor = ColorTell;
2483 Colorize(ColorKibitz, FALSE);
2484 curColor = ColorKibitz;
2487 p = strrchr(star_match[1], '(');
2494 Colorize(ColorChannel1, FALSE);
2495 curColor = ColorChannel1;
2497 Colorize(ColorChannel, FALSE);
2498 curColor = ColorChannel;
2502 curColor = ColorNormal;
2506 if (started == STARTED_NONE && appData.autoComment &&
2507 (gameMode == IcsObserving ||
2508 gameMode == IcsPlayingWhite ||
2509 gameMode == IcsPlayingBlack)) {
2510 parse_pos = i - oldi;
2511 memcpy(parse, &buf[oldi], parse_pos);
2512 parse[parse_pos] = NULLCHAR;
2513 started = STARTED_COMMENT;
2514 savingComment = TRUE;
2516 started = STARTED_CHATTER;
2517 savingComment = FALSE;
2524 if (looking_at(buf, &i, "* s-shouts: ") ||
2525 looking_at(buf, &i, "* c-shouts: ")) {
2526 if (appData.colorize) {
2527 if (oldi > next_out) {
2528 SendToPlayer(&buf[next_out], oldi - next_out);
2531 Colorize(ColorSShout, FALSE);
2532 curColor = ColorSShout;
2535 started = STARTED_CHATTER;
2539 if (looking_at(buf, &i, "--->")) {
2544 if (looking_at(buf, &i, "* shouts: ") ||
2545 looking_at(buf, &i, "--> ")) {
2546 if (appData.colorize) {
2547 if (oldi > next_out) {
2548 SendToPlayer(&buf[next_out], oldi - next_out);
2551 Colorize(ColorShout, FALSE);
2552 curColor = ColorShout;
2555 started = STARTED_CHATTER;
2559 if (looking_at( buf, &i, "Challenge:")) {
2560 if (appData.colorize) {
2561 if (oldi > next_out) {
2562 SendToPlayer(&buf[next_out], oldi - next_out);
2565 Colorize(ColorChallenge, FALSE);
2566 curColor = ColorChallenge;
2572 if (looking_at(buf, &i, "* offers you") ||
2573 looking_at(buf, &i, "* offers to be") ||
2574 looking_at(buf, &i, "* would like to") ||
2575 looking_at(buf, &i, "* requests to") ||
2576 looking_at(buf, &i, "Your opponent offers") ||
2577 looking_at(buf, &i, "Your opponent requests")) {
2579 if (appData.colorize) {
2580 if (oldi > next_out) {
2581 SendToPlayer(&buf[next_out], oldi - next_out);
2584 Colorize(ColorRequest, FALSE);
2585 curColor = ColorRequest;
2590 if (looking_at(buf, &i, "* (*) seeking")) {
2591 if (appData.colorize) {
2592 if (oldi > next_out) {
2593 SendToPlayer(&buf[next_out], oldi - next_out);
2596 Colorize(ColorSeek, FALSE);
2597 curColor = ColorSeek;
2602 if (looking_at(buf, &i, "\\ ")) {
2603 if (prevColor != ColorNormal) {
2604 if (oldi > next_out) {
2605 SendToPlayer(&buf[next_out], oldi - next_out);
2608 Colorize(prevColor, TRUE);
2609 curColor = prevColor;
2611 if (savingComment) {
2612 parse_pos = i - oldi;
2613 memcpy(parse, &buf[oldi], parse_pos);
2614 parse[parse_pos] = NULLCHAR;
2615 started = STARTED_COMMENT;
2617 started = STARTED_CHATTER;
2622 if (looking_at(buf, &i, "Black Strength :") ||
2623 looking_at(buf, &i, "<<< style 10 board >>>") ||
2624 looking_at(buf, &i, "<10>") ||
2625 looking_at(buf, &i, "#@#")) {
2626 /* Wrong board style */
2628 SendToICS(ics_prefix);
2629 SendToICS("set style 12\n");
2630 SendToICS(ics_prefix);
2631 SendToICS("refresh\n");
2635 if (!have_sent_ICS_logon && looking_at(buf, &i, "login:")) {
2637 have_sent_ICS_logon = 1;
2641 if (ics_getting_history != H_GETTING_MOVES /*smpos kludge*/ &&
2642 (looking_at(buf, &i, "\n<12> ") ||
2643 looking_at(buf, &i, "<12> "))) {
2645 if (oldi > next_out) {
2646 SendToPlayer(&buf[next_out], oldi - next_out);
2649 started = STARTED_BOARD;
2654 if ((started == STARTED_NONE && looking_at(buf, &i, "\n<b1> ")) ||
2655 looking_at(buf, &i, "<b1> ")) {
2656 if (oldi > next_out) {
2657 SendToPlayer(&buf[next_out], oldi - next_out);
2660 started = STARTED_HOLDINGS;
2665 if (looking_at(buf, &i, "* *vs. * *--- *")) {
2667 /* Header for a move list -- first line */
2669 switch (ics_getting_history) {
2673 case BeginningOfGame:
2674 /* User typed "moves" or "oldmoves" while we
2675 were idle. Pretend we asked for these
2676 moves and soak them up so user can step
2677 through them and/or save them.
2680 gameMode = IcsObserving;
2683 ics_getting_history = H_GOT_UNREQ_HEADER;
2685 case EditGame: /*?*/
2686 case EditPosition: /*?*/
2687 /* Should above feature work in these modes too? */
2688 /* For now it doesn't */
2689 ics_getting_history = H_GOT_UNWANTED_HEADER;
2692 ics_getting_history = H_GOT_UNWANTED_HEADER;
2697 /* Is this the right one? */
2698 if (gameInfo.white && gameInfo.black &&
2699 strcmp(gameInfo.white, star_match[0]) == 0 &&
2700 strcmp(gameInfo.black, star_match[2]) == 0) {
2702 ics_getting_history = H_GOT_REQ_HEADER;
2705 case H_GOT_REQ_HEADER:
2706 case H_GOT_UNREQ_HEADER:
2707 case H_GOT_UNWANTED_HEADER:
2708 case H_GETTING_MOVES:
2709 /* Should not happen */
2710 DisplayError(_("Error gathering move list: two headers"), 0);
2711 ics_getting_history = H_FALSE;
2715 /* Save player ratings into gameInfo if needed */
2716 if ((ics_getting_history == H_GOT_REQ_HEADER ||
2717 ics_getting_history == H_GOT_UNREQ_HEADER) &&
2718 (gameInfo.whiteRating == -1 ||
2719 gameInfo.blackRating == -1)) {
2721 gameInfo.whiteRating = string_to_rating(star_match[1]);
2722 gameInfo.blackRating = string_to_rating(star_match[3]);
2723 if (appData.debugMode)
2724 fprintf(debugFP, _("Ratings from header: W %d, B %d\n"),
2725 gameInfo.whiteRating, gameInfo.blackRating);
2730 if (looking_at(buf, &i,
2731 "* * match, initial time: * minute*, increment: * second")) {
2732 /* Header for a move list -- second line */
2733 /* Initial board will follow if this is a wild game */
2734 if (gameInfo.event != NULL) free(gameInfo.event);
2735 sprintf(str, "ICS %s %s match", star_match[0], star_match[1]);
2736 gameInfo.event = StrSave(str);
2737 /* [HGM] we switched variant. Translate boards if needed. */
2738 VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event));
2742 if (looking_at(buf, &i, "Move ")) {
2743 /* Beginning of a move list */
2744 switch (ics_getting_history) {
2746 /* Normally should not happen */
2747 /* Maybe user hit reset while we were parsing */
2750 /* Happens if we are ignoring a move list that is not
2751 * the one we just requested. Common if the user
2752 * tries to observe two games without turning off
2755 case H_GETTING_MOVES:
2756 /* Should not happen */
2757 DisplayError(_("Error gathering move list: nested"), 0);
2758 ics_getting_history = H_FALSE;
2760 case H_GOT_REQ_HEADER:
2761 ics_getting_history = H_GETTING_MOVES;
2762 started = STARTED_MOVES;
2764 if (oldi > next_out) {
2765 SendToPlayer(&buf[next_out], oldi - next_out);
2768 case H_GOT_UNREQ_HEADER:
2769 ics_getting_history = H_GETTING_MOVES;
2770 started = STARTED_MOVES_NOHIDE;
2773 case H_GOT_UNWANTED_HEADER:
2774 ics_getting_history = H_FALSE;
2780 if (looking_at(buf, &i, "% ") ||
2781 ((started == STARTED_MOVES || started == STARTED_MOVES_NOHIDE)
2782 && looking_at(buf, &i, "}*"))) { char *bookHit = NULL; // [HGM] book
2783 savingComment = FALSE;
2786 case STARTED_MOVES_NOHIDE:
2787 memcpy(&parse[parse_pos], &buf[oldi], i - oldi);
2788 parse[parse_pos + i - oldi] = NULLCHAR;
2789 ParseGameHistory(parse);
2791 if (appData.zippyPlay && first.initDone) {
2792 FeedMovesToProgram(&first, forwardMostMove);
2793 if (gameMode == IcsPlayingWhite) {
2794 if (WhiteOnMove(forwardMostMove)) {
2795 if (first.sendTime) {
2796 if (first.useColors) {
2797 SendToProgram("black\n", &first);
2799 SendTimeRemaining(&first, TRUE);
2801 if (first.useColors) {
2802 SendToProgram("white\n", &first); // [HGM] book: made sending of "go\n" book dependent
2804 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: probe book for initial pos
2805 first.maybeThinking = TRUE;
2807 if (first.usePlayother) {
2808 if (first.sendTime) {
2809 SendTimeRemaining(&first, TRUE);
2811 SendToProgram("playother\n", &first);
2817 } else if (gameMode == IcsPlayingBlack) {
2818 if (!WhiteOnMove(forwardMostMove)) {
2819 if (first.sendTime) {
2820 if (first.useColors) {
2821 SendToProgram("white\n", &first);
2823 SendTimeRemaining(&first, FALSE);
2825 if (first.useColors) {
2826 SendToProgram("black\n", &first);
2828 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE);
2829 first.maybeThinking = TRUE;
2831 if (first.usePlayother) {
2832 if (first.sendTime) {
2833 SendTimeRemaining(&first, FALSE);
2835 SendToProgram("playother\n", &first);
2844 if (gameMode == IcsObserving && ics_gamenum == -1) {
2845 /* Moves came from oldmoves or moves command
2846 while we weren't doing anything else.
2848 currentMove = forwardMostMove;
2849 ClearHighlights();/*!!could figure this out*/
2850 flipView = appData.flipView;
2851 DrawPosition(FALSE, boards[currentMove]);
2852 DisplayBothClocks();
2853 sprintf(str, "%s vs. %s",
2854 gameInfo.white, gameInfo.black);
2858 /* Moves were history of an active game */
2859 if (gameInfo.resultDetails != NULL) {
2860 free(gameInfo.resultDetails);
2861 gameInfo.resultDetails = NULL;
2864 HistorySet(parseList, backwardMostMove,
2865 forwardMostMove, currentMove-1);
2866 DisplayMove(currentMove - 1);
2867 if (started == STARTED_MOVES) next_out = i;
2868 started = STARTED_NONE;
2869 ics_getting_history = H_FALSE;
2872 case STARTED_OBSERVE:
2873 started = STARTED_NONE;
2874 SendToICS(ics_prefix);
2875 SendToICS("refresh\n");
2881 if(bookHit) { // [HGM] book: simulate book reply
2882 static char bookMove[MSG_SIZ]; // a bit generous?
2884 programStats.nodes = programStats.depth = programStats.time =
2885 programStats.score = programStats.got_only_move = 0;
2886 sprintf(programStats.movelist, "%s (xbook)", bookHit);
2888 strcpy(bookMove, "move ");
2889 strcat(bookMove, bookHit);
2890 HandleMachineMove(bookMove, &first);
2895 if ((started == STARTED_MOVES || started == STARTED_BOARD ||
2896 started == STARTED_HOLDINGS ||
2897 started == STARTED_MOVES_NOHIDE) && i >= leftover_len) {
2898 /* Accumulate characters in move list or board */
2899 parse[parse_pos++] = buf[i];
2902 /* Start of game messages. Mostly we detect start of game
2903 when the first board image arrives. On some versions
2904 of the ICS, though, we need to do a "refresh" after starting
2905 to observe in order to get the current board right away. */
2906 if (looking_at(buf, &i, "Adding game * to observation list")) {
2907 started = STARTED_OBSERVE;
2911 /* Handle auto-observe */
2912 if (appData.autoObserve &&
2913 (gameMode == IcsIdle || gameMode == BeginningOfGame) &&
2914 looking_at(buf, &i, "Game notification: * (*) vs. * (*)")) {
2916 /* Choose the player that was highlighted, if any. */
2917 if (star_match[0][0] == '\033' ||
2918 star_match[1][0] != '\033') {
2919 player = star_match[0];
2921 player = star_match[2];
2923 sprintf(str, "%sobserve %s\n",
2924 ics_prefix, StripHighlightAndTitle(player));
2927 /* Save ratings from notify string */
2928 strcpy(player1Name, star_match[0]);
2929 player1Rating = string_to_rating(star_match[1]);
2930 strcpy(player2Name, star_match[2]);
2931 player2Rating = string_to_rating(star_match[3]);
2933 if (appData.debugMode)
2935 "Ratings from 'Game notification:' %s %d, %s %d\n",
2936 player1Name, player1Rating,
2937 player2Name, player2Rating);
2942 /* Deal with automatic examine mode after a game,
2943 and with IcsObserving -> IcsExamining transition */
2944 if (looking_at(buf, &i, "Entering examine mode for game *") ||
2945 looking_at(buf, &i, "has made you an examiner of game *")) {
2947 int gamenum = atoi(star_match[0]);
2948 if ((gameMode == IcsIdle || gameMode == IcsObserving) &&
2949 gamenum == ics_gamenum) {
2950 /* We were already playing or observing this game;
2951 no need to refetch history */
2952 gameMode = IcsExamining;
2954 pauseExamForwardMostMove = forwardMostMove;
2955 } else if (currentMove < forwardMostMove) {
2956 ForwardInner(forwardMostMove);
2959 /* I don't think this case really can happen */
2960 SendToICS(ics_prefix);
2961 SendToICS("refresh\n");
2966 /* Error messages */
2967 // if (ics_user_moved) {
2968 if (1) { // [HGM] old way ignored error after move type in; ics_user_moved is not set then!
2969 if (looking_at(buf, &i, "Illegal move") ||
2970 looking_at(buf, &i, "Not a legal move") ||
2971 looking_at(buf, &i, "Your king is in check") ||
2972 looking_at(buf, &i, "It isn't your turn") ||
2973 looking_at(buf, &i, "It is not your move")) {
2975 if (ics_user_moved && forwardMostMove > backwardMostMove) { // only backup if we already moved
2976 currentMove = --forwardMostMove;
2977 DisplayMove(currentMove - 1); /* before DMError */
2978 DrawPosition(FALSE, boards[currentMove]);
2980 DisplayBothClocks();
2982 DisplayMoveError(_("Illegal move (rejected by ICS)")); // [HGM] but always relay error msg
2988 if (looking_at(buf, &i, "still have time") ||
2989 looking_at(buf, &i, "not out of time") ||
2990 looking_at(buf, &i, "either player is out of time") ||
2991 looking_at(buf, &i, "has timeseal; checking")) {
2992 /* We must have called his flag a little too soon */
2993 whiteFlag = blackFlag = FALSE;
2997 if (looking_at(buf, &i, "added * seconds to") ||
2998 looking_at(buf, &i, "seconds were added to")) {
2999 /* Update the clocks */
3000 SendToICS(ics_prefix);
3001 SendToICS("refresh\n");
3005 if (!ics_clock_paused && looking_at(buf, &i, "clock paused")) {
3006 ics_clock_paused = TRUE;
3011 if (ics_clock_paused && looking_at(buf, &i, "clock resumed")) {
3012 ics_clock_paused = FALSE;
3017 /* Grab player ratings from the Creating: message.
3018 Note we have to check for the special case when
3019 the ICS inserts things like [white] or [black]. */
3020 if (looking_at(buf, &i, "Creating: * (*)* * (*)") ||
3021 looking_at(buf, &i, "Creating: * (*) [*] * (*)")) {
3023 0 player 1 name (not necessarily white)
3025 2 empty, white, or black (IGNORED)
3026 3 player 2 name (not necessarily black)
3029 The names/ratings are sorted out when the game
3030 actually starts (below).
3032 strcpy(player1Name, StripHighlightAndTitle(star_match[0]));
3033 player1Rating = string_to_rating(star_match[1]);
3034 strcpy(player2Name, StripHighlightAndTitle(star_match[3]));
3035 player2Rating = string_to_rating(star_match[4]);
3037 if (appData.debugMode)
3039 "Ratings from 'Creating:' %s %d, %s %d\n",
3040 player1Name, player1Rating,
3041 player2Name, player2Rating);
3046 /* Improved generic start/end-of-game messages */
3047 if ((tkind=0, looking_at(buf, &i, "{Game * (* vs. *) *}*")) ||
3048 (tkind=1, looking_at(buf, &i, "{Game * (*(*) vs. *(*)) *}*"))){
3049 /* If tkind == 0: */
3050 /* star_match[0] is the game number */
3051 /* [1] is the white player's name */
3052 /* [2] is the black player's name */
3053 /* For end-of-game: */
3054 /* [3] is the reason for the game end */
3055 /* [4] is a PGN end game-token, preceded by " " */
3056 /* For start-of-game: */
3057 /* [3] begins with "Creating" or "Continuing" */
3058 /* [4] is " *" or empty (don't care). */
3059 int gamenum = atoi(star_match[0]);
3060 char *whitename, *blackname, *why, *endtoken;
3061 ChessMove endtype = (ChessMove) 0;
3064 whitename = star_match[1];
3065 blackname = star_match[2];
3066 why = star_match[3];
3067 endtoken = star_match[4];
3069 whitename = star_match[1];
3070 blackname = star_match[3];
3071 why = star_match[5];
3072 endtoken = star_match[6];
3075 /* Game start messages */
3076 if (strncmp(why, "Creating ", 9) == 0 ||
3077 strncmp(why, "Continuing ", 11) == 0) {
3078 gs_gamenum = gamenum;
3079 strcpy(gs_kind, strchr(why, ' ') + 1);
3081 if (appData.zippyPlay) {
3082 ZippyGameStart(whitename, blackname);
3088 /* Game end messages */
3089 if (gameMode == IcsIdle || gameMode == BeginningOfGame ||
3090 ics_gamenum != gamenum) {
3093 while (endtoken[0] == ' ') endtoken++;
3094 switch (endtoken[0]) {
3097 endtype = GameUnfinished;
3100 endtype = BlackWins;
3103 if (endtoken[1] == '/')
3104 endtype = GameIsDrawn;
3106 endtype = WhiteWins;
3109 GameEnds(endtype, why, GE_ICS);
3111 if (appData.zippyPlay && first.initDone) {
3112 ZippyGameEnd(endtype, why);
3113 if (first.pr == NULL) {
3114 /* Start the next process early so that we'll
3115 be ready for the next challenge */
3116 StartChessProgram(&first);
3118 /* Send "new" early, in case this command takes
3119 a long time to finish, so that we'll be ready
3120 for the next challenge. */
3121 gameInfo.variant = VariantNormal; // [HGM] variantswitch: suppress sending of 'variant'
3128 if (looking_at(buf, &i, "Removing game * from observation") ||
3129 looking_at(buf, &i, "no longer observing game *") ||
3130 looking_at(buf, &i, "Game * (*) has no examiners")) {
3131 if (gameMode == IcsObserving &&
3132 atoi(star_match[0]) == ics_gamenum)
3134 /* icsEngineAnalyze */
3135 if (appData.icsEngineAnalyze) {
3142 ics_user_moved = FALSE;
3147 if (looking_at(buf, &i, "no longer examining game *")) {
3148 if (gameMode == IcsExamining &&
3149 atoi(star_match[0]) == ics_gamenum)
3153 ics_user_moved = FALSE;
3158 /* Advance leftover_start past any newlines we find,
3159 so only partial lines can get reparsed */
3160 if (looking_at(buf, &i, "\n")) {
3161 prevColor = curColor;
3162 if (curColor != ColorNormal) {
3163 if (oldi > next_out) {
3164 SendToPlayer(&buf[next_out], oldi - next_out);
3167 Colorize(ColorNormal, FALSE);
3168 curColor = ColorNormal;
3170 if (started == STARTED_BOARD) {
3171 started = STARTED_NONE;
3172 parse[parse_pos] = NULLCHAR;
3173 ParseBoard12(parse);
3176 /* Send premove here */
3177 if (appData.premove) {
3179 if (currentMove == 0 &&
3180 gameMode == IcsPlayingWhite &&
3181 appData.premoveWhite) {
3182 sprintf(str, "%s%s\n", ics_prefix,
3183 appData.premoveWhiteText);
3184 if (appData.debugMode)
3185 fprintf(debugFP, "Sending premove:\n");
3187 } else if (currentMove == 1 &&
3188 gameMode == IcsPlayingBlack &&
3189 appData.premoveBlack) {
3190 sprintf(str, "%s%s\n", ics_prefix,
3191 appData.premoveBlackText);
3192 if (appData.debugMode)
3193 fprintf(debugFP, "Sending premove:\n");
3195 } else if (gotPremove) {
3197 ClearPremoveHighlights();
3198 if (appData.debugMode)
3199 fprintf(debugFP, "Sending premove:\n");
3200 UserMoveEvent(premoveFromX, premoveFromY,
3201 premoveToX, premoveToY,
3206 /* Usually suppress following prompt */
3207 if (!(forwardMostMove == 0 && gameMode == IcsExamining)) {
3208 if (looking_at(buf, &i, "*% ")) {
3209 savingComment = FALSE;
3213 } else if (started == STARTED_HOLDINGS) {
3215 char new_piece[MSG_SIZ];
3216 started = STARTED_NONE;
3217 parse[parse_pos] = NULLCHAR;
3218 if (appData.debugMode)
3219 fprintf(debugFP, "Parsing holdings: %s, currentMove = %d\n",
3220 parse, currentMove);
3221 if (sscanf(parse, " game %d", &gamenum) == 1 &&
3222 gamenum == ics_gamenum) {
3223 if (gameInfo.variant == VariantNormal) {
3224 /* [HGM] We seem to switch variant during a game!
3225 * Presumably no holdings were displayed, so we have
3226 * to move the position two files to the right to
3227 * create room for them!
3229 VariantSwitch(boards[currentMove], VariantCrazyhouse); /* temp guess */
3230 /* Get a move list just to see the header, which
3231 will tell us whether this is really bug or zh */
3232 if (ics_getting_history == H_FALSE) {
3233 ics_getting_history = H_REQUESTED;
3234 sprintf(str, "%smoves %d\n", ics_prefix, gamenum);
3238 new_piece[0] = NULLCHAR;
3239 sscanf(parse, "game %d white [%s black [%s <- %s",
3240 &gamenum, white_holding, black_holding,
3242 white_holding[strlen(white_holding)-1] = NULLCHAR;
3243 black_holding[strlen(black_holding)-1] = NULLCHAR;
3244 /* [HGM] copy holdings to board holdings area */
3245 CopyHoldings(boards[currentMove], white_holding, WhitePawn);
3246 CopyHoldings(boards[currentMove], black_holding, BlackPawn);
3248 if (appData.zippyPlay && first.initDone) {
3249 ZippyHoldings(white_holding, black_holding,
3253 if (tinyLayout || smallLayout) {
3254 char wh[16], bh[16];
3255 PackHolding(wh, white_holding);
3256 PackHolding(bh, black_holding);
3257 sprintf(str, "[%s-%s] %s-%s", wh, bh,
3258 gameInfo.white, gameInfo.black);
3260 sprintf(str, "%s [%s] vs. %s [%s]",
3261 gameInfo.white, white_holding,
3262 gameInfo.black, black_holding);
3265 DrawPosition(FALSE, boards[currentMove]);
3268 /* Suppress following prompt */
3269 if (looking_at(buf, &i, "*% ")) {
3270 savingComment = FALSE;
3277 i++; /* skip unparsed character and loop back */
3280 if (started != STARTED_MOVES && started != STARTED_BOARD && !suppressKibitz && // [HGM] kibitz suppress printing in ICS interaction window
3281 started != STARTED_HOLDINGS && i > next_out) {
3282 SendToPlayer(&buf[next_out], i - next_out);
3285 suppressKibitz = FALSE; // [HGM] kibitz: has done its duty in if-statement above
3287 leftover_len = buf_len - leftover_start;
3288 /* if buffer ends with something we couldn't parse,
3289 reparse it after appending the next read */
3291 } else if (count == 0) {
3292 RemoveInputSource(isr);
3293 DisplayFatalError(_("Connection closed by ICS"), 0, 0);
3295 DisplayFatalError(_("Error reading from ICS"), error, 1);
3300 /* Board style 12 looks like this:
3302 <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
3304 * The "<12> " is stripped before it gets to this routine. The two
3305 * trailing 0's (flip state and clock ticking) are later addition, and
3306 * some chess servers may not have them, or may have only the first.
3307 * Additional trailing fields may be added in the future.
3310 #define PATTERN "%c%d%d%d%d%d%d%d%s%s%d%d%d%d%d%d%d%d%s%s%s%d%d"
3312 #define RELATION_OBSERVING_PLAYED 0
3313 #define RELATION_OBSERVING_STATIC -2 /* examined, oldmoves, or smoves */
3314 #define RELATION_PLAYING_MYMOVE 1
3315 #define RELATION_PLAYING_NOTMYMOVE -1
3316 #define RELATION_EXAMINING 2
3317 #define RELATION_ISOLATED_BOARD -3
3318 #define RELATION_STARTING_POSITION -4 /* FICS only */
3321 ParseBoard12(string)
3324 GameMode newGameMode;
3325 int gamenum, newGame, newMove, relation, basetime, increment, ics_flip = 0, i;
3326 int j, k, n, moveNum, white_stren, black_stren, white_time, black_time, takeback;
3327 int double_push, castle_ws, castle_wl, castle_bs, castle_bl, irrev_count;
3328 char to_play, board_chars[200];
3329 char move_str[500], str[500], elapsed_time[500];
3330 char black[32], white[32];
3332 int prevMove = currentMove;
3335 int fromX, fromY, toX, toY;
3337 int ranks=1, files=0; /* [HGM] ICS80: allow variable board size */
3338 char *bookHit = NULL; // [HGM] book
3340 fromX = fromY = toX = toY = -1;
3344 if (appData.debugMode)
3345 fprintf(debugFP, _("Parsing board: %s\n"), string);
3347 move_str[0] = NULLCHAR;
3348 elapsed_time[0] = NULLCHAR;
3349 { /* [HGM] figure out how many ranks and files the board has, for ICS extension used by Capablanca server */
3351 while(i < 199 && (string[i] != ' ' || string[i+2] != ' ')) {
3352 if(string[i] == ' ') { ranks++; files = 0; }
3356 for(j = 0; j <i; j++) board_chars[j] = string[j];
3357 board_chars[i] = '\0';
3360 n = sscanf(string, PATTERN, &to_play, &double_push,
3361 &castle_ws, &castle_wl, &castle_bs, &castle_bl, &irrev_count,
3362 &gamenum, white, black, &relation, &basetime, &increment,
3363 &white_stren, &black_stren, &white_time, &black_time,
3364 &moveNum, str, elapsed_time, move_str, &ics_flip,
3368 snprintf(str, sizeof(str), _("Failed to parse board string:\n\"%s\""), string);
3369 DisplayError(str, 0);
3373 /* Convert the move number to internal form */
3374 moveNum = (moveNum - 1) * 2;
3375 if (to_play == 'B') moveNum++;
3376 if (moveNum >= MAX_MOVES) {
3377 DisplayFatalError(_("Game too long; increase MAX_MOVES and recompile"),
3383 case RELATION_OBSERVING_PLAYED:
3384 case RELATION_OBSERVING_STATIC:
3385 if (gamenum == -1) {
3386 /* Old ICC buglet */
3387 relation = RELATION_OBSERVING_STATIC;
3389 newGameMode = IcsObserving;
3391 case RELATION_PLAYING_MYMOVE:
3392 case RELATION_PLAYING_NOTMYMOVE:
3394 ((relation == RELATION_PLAYING_MYMOVE) == (to_play == 'W')) ?
3395 IcsPlayingWhite : IcsPlayingBlack;
3397 case RELATION_EXAMINING:
3398 newGameMode = IcsExamining;
3400 case RELATION_ISOLATED_BOARD:
3402 /* Just display this board. If user was doing something else,
3403 we will forget about it until the next board comes. */
3404 newGameMode = IcsIdle;
3406 case RELATION_STARTING_POSITION:
3407 newGameMode = gameMode;
3411 /* Modify behavior for initial board display on move listing
3414 switch (ics_getting_history) {
3418 case H_GOT_REQ_HEADER:
3419 case H_GOT_UNREQ_HEADER:
3420 /* This is the initial position of the current game */
3421 gamenum = ics_gamenum;
3422 moveNum = 0; /* old ICS bug workaround */
3423 if (to_play == 'B') {
3424 startedFromSetupPosition = TRUE;
3425 blackPlaysFirst = TRUE;
3427 if (forwardMostMove == 0) forwardMostMove = 1;
3428 if (backwardMostMove == 0) backwardMostMove = 1;
3429 if (currentMove == 0) currentMove = 1;
3431 newGameMode = gameMode;
3432 relation = RELATION_STARTING_POSITION; /* ICC needs this */
3434 case H_GOT_UNWANTED_HEADER:
3435 /* This is an initial board that we don't want */
3437 case H_GETTING_MOVES:
3438 /* Should not happen */
3439 DisplayError(_("Error gathering move list: extra board"), 0);
3440 ics_getting_history = H_FALSE;
3444 /* Take action if this is the first board of a new game, or of a
3445 different game than is currently being displayed. */
3446 if (gamenum != ics_gamenum || newGameMode != gameMode ||
3447 relation == RELATION_ISOLATED_BOARD) {
3449 /* Forget the old game and get the history (if any) of the new one */
3450 if (gameMode != BeginningOfGame) {
3454 if (appData.autoRaiseBoard) BoardToTop();
3456 if (gamenum == -1) {
3457 newGameMode = IcsIdle;
3458 } else if (moveNum > 0 && newGameMode != IcsIdle &&
3459 appData.getMoveList) {
3460 /* Need to get game history */
3461 ics_getting_history = H_REQUESTED;
3462 sprintf(str, "%smoves %d\n", ics_prefix, gamenum);
3466 /* Initially flip the board to have black on the bottom if playing
3467 black or if the ICS flip flag is set, but let the user change
3468 it with the Flip View button. */
3469 flipView = appData.autoFlipView ?
3470 (newGameMode == IcsPlayingBlack) || ics_flip :
3473 /* Done with values from previous mode; copy in new ones */
3474 gameMode = newGameMode;
3476 ics_gamenum = gamenum;
3477 if (gamenum == gs_gamenum) {
3478 int klen = strlen(gs_kind);
3479 if (gs_kind[klen - 1] == '.') gs_kind[klen - 1] = NULLCHAR;
3480 sprintf(str, "ICS %s", gs_kind);
3481 gameInfo.event = StrSave(str);
3483 gameInfo.event = StrSave("ICS game");
3485 gameInfo.site = StrSave(appData.icsHost);
3486 gameInfo.date = PGNDate();
3487 gameInfo.round = StrSave("-");
3488 gameInfo.white = StrSave(white);
3489 gameInfo.black = StrSave(black);
3490 timeControl = basetime * 60 * 1000;
3492 timeIncrement = increment * 1000;
3493 movesPerSession = 0;
3494 gameInfo.timeControl = TimeControlTagValue();
3495 VariantSwitch(board, StringToVariant(gameInfo.event) );
3496 if (appData.debugMode) {
3497 fprintf(debugFP, "ParseBoard says variant = '%s'\n", gameInfo.event);
3498 fprintf(debugFP, "recognized as %s\n", VariantName(gameInfo.variant));
3499 setbuf(debugFP, NULL);
3502 gameInfo.outOfBook = NULL;
3504 /* Do we have the ratings? */
3505 if (strcmp(player1Name, white) == 0 &&
3506 strcmp(player2Name, black) == 0) {
3507 if (appData.debugMode)
3508 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
3509 player1Rating, player2Rating);
3510 gameInfo.whiteRating = player1Rating;
3511 gameInfo.blackRating = player2Rating;
3512 } else if (strcmp(player2Name, white) == 0 &&
3513 strcmp(player1Name, black) == 0) {
3514 if (appData.debugMode)
3515 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
3516 player2Rating, player1Rating);
3517 gameInfo.whiteRating = player2Rating;
3518 gameInfo.blackRating = player1Rating;
3520 player1Name[0] = player2Name[0] = NULLCHAR;
3522 /* Silence shouts if requested */
3523 if (appData.quietPlay &&
3524 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)) {
3525 SendToICS(ics_prefix);
3526 SendToICS("set shout 0\n");
3530 /* Deal with midgame name changes */
3532 if (!gameInfo.white || strcmp(gameInfo.white, white) != 0) {
3533 if (gameInfo.white) free(gameInfo.white);
3534 gameInfo.white = StrSave(white);
3536 if (!gameInfo.black || strcmp(gameInfo.black, black) != 0) {
3537 if (gameInfo.black) free(gameInfo.black);
3538 gameInfo.black = StrSave(black);
3542 /* Throw away game result if anything actually changes in examine mode */
3543 if (gameMode == IcsExamining && !newGame) {
3544 gameInfo.result = GameUnfinished;
3545 if (gameInfo.resultDetails != NULL) {
3546 free(gameInfo.resultDetails);
3547 gameInfo.resultDetails = NULL;
3551 /* In pausing && IcsExamining mode, we ignore boards coming
3552 in if they are in a different variation than we are. */
3553 if (pauseExamInvalid) return;
3554 if (pausing && gameMode == IcsExamining) {
3555 if (moveNum <= pauseExamForwardMostMove) {
3556 pauseExamInvalid = TRUE;
3557 forwardMostMove = pauseExamForwardMostMove;
3562 if (appData.debugMode) {
3563 fprintf(debugFP, "load %dx%d board\n", files, ranks);
3565 /* Parse the board */
3566 for (k = 0; k < ranks; k++) {
3567 for (j = 0; j < files; j++)
3568 board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
3569 if(gameInfo.holdingsWidth > 1) {
3570 board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
3571 board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
3574 CopyBoard(boards[moveNum], board);
3576 startedFromSetupPosition =
3577 !CompareBoards(board, initialPosition);
3578 if(startedFromSetupPosition)
3579 initialRulePlies = irrev_count; /* [HGM] 50-move counter offset */
3582 /* [HGM] Set castling rights. Take the outermost Rooks,
3583 to make it also work for FRC opening positions. Note that board12
3584 is really defective for later FRC positions, as it has no way to
3585 indicate which Rook can castle if they are on the same side of King.
3586 For the initial position we grant rights to the outermost Rooks,
3587 and remember thos rights, and we then copy them on positions
3588 later in an FRC game. This means WB might not recognize castlings with
3589 Rooks that have moved back to their original position as illegal,
3590 but in ICS mode that is not its job anyway.
3592 if(moveNum == 0 || gameInfo.variant != VariantFischeRandom)
3593 { int i, j; ChessSquare wKing = WhiteKing, bKing = BlackKing;
3595 for(i=BOARD_LEFT, j= -1; i<BOARD_RGHT; i++)
3596 if(board[0][i] == WhiteRook) j = i;
3597 initialRights[0] = castlingRights[moveNum][0] = (castle_ws == 0 && gameInfo.variant != VariantFischeRandom ? -1 : j);
3598 for(i=BOARD_RGHT-1, j= -1; i>=BOARD_LEFT; i--)
3599 if(board[0][i] == WhiteRook) j = i;
3600 initialRights[1] = castlingRights[moveNum][1] = (castle_wl == 0 && gameInfo.variant != VariantFischeRandom ? -1 : j);
3601 for(i=BOARD_LEFT, j= -1; i<BOARD_RGHT; i++)
3602 if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
3603 initialRights[3] = castlingRights[moveNum][3] = (castle_bs == 0 && gameInfo.variant != VariantFischeRandom ? -1 : j);
3604 for(i=BOARD_RGHT-1, j= -1; i>=BOARD_LEFT; i--)
3605 if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
3606 initialRights[4] = castlingRights[moveNum][4] = (castle_bl == 0 && gameInfo.variant != VariantFischeRandom ? -1 : j);
3608 if(gameInfo.variant == VariantKnightmate) { wKing = WhiteUnicorn; bKing = BlackUnicorn; }
3609 for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
3610 if(board[0][k] == wKing) initialRights[2] = castlingRights[moveNum][2] = k;
3611 for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
3612 if(board[BOARD_HEIGHT-1][k] == bKing)
3613 initialRights[5] = castlingRights[moveNum][5] = k;
3615 r = castlingRights[moveNum][0] = initialRights[0];
3616 if(board[0][r] != WhiteRook) castlingRights[moveNum][0] = -1;
3617 r = castlingRights[moveNum][1] = initialRights[1];
3618 if(board[0][r] != WhiteRook) castlingRights[moveNum][1] = -1;
3619 r = castlingRights[moveNum][3] = initialRights[3];
3620 if(board[BOARD_HEIGHT-1][r] != BlackRook) castlingRights[moveNum][3] = -1;
3621 r = castlingRights[moveNum][4] = initialRights[4];
3622 if(board[BOARD_HEIGHT-1][r] != BlackRook) castlingRights[moveNum][4] = -1;
3623 /* wildcastle kludge: always assume King has rights */
3624 r = castlingRights[moveNum][2] = initialRights[2];
3625 r = castlingRights[moveNum][5] = initialRights[5];
3627 /* [HGM] e.p. rights. Assume that ICS sends file number here? */
3628 epStatus[moveNum] = double_push == -1 ? EP_NONE : double_push + BOARD_LEFT;
3631 if (ics_getting_history == H_GOT_REQ_HEADER ||
3632 ics_getting_history == H_GOT_UNREQ_HEADER) {
3633 /* This was an initial position from a move list, not
3634 the current position */
3638 /* Update currentMove and known move number limits */
3639 newMove = newGame || moveNum > forwardMostMove;
3641 /* [DM] If we found takebacks during icsEngineAnalyze try send to engine */
3642 if (!newGame && appData.icsEngineAnalyze && moveNum < forwardMostMove) {
3643 takeback = forwardMostMove - moveNum;
3644 for (i = 0; i < takeback; i++) {
3645 if (appData.debugMode) fprintf(debugFP, "take back move\n");
3646 SendToProgram("undo\n", &first);
3651 forwardMostMove = backwardMostMove = currentMove = moveNum;
3652 if (gameMode == IcsExamining && moveNum == 0) {
3653 /* Workaround for ICS limitation: we are not told the wild
3654 type when starting to examine a game. But if we ask for
3655 the move list, the move list header will tell us */
3656 ics_getting_history = H_REQUESTED;
3657 sprintf(str, "%smoves %d\n", ics_prefix, gamenum);
3660 } else if (moveNum == forwardMostMove + 1 || moveNum == forwardMostMove
3661 || (moveNum < forwardMostMove && moveNum >= backwardMostMove)) {
3662 forwardMostMove = moveNum;
3663 if (!pausing || currentMove > forwardMostMove)
3664 currentMove = forwardMostMove;
3666 /* New part of history that is not contiguous with old part */
3667 if (pausing && gameMode == IcsExamining) {
3668 pauseExamInvalid = TRUE;
3669 forwardMostMove = pauseExamForwardMostMove;
3672 forwardMostMove = backwardMostMove = currentMove = moveNum;
3673 if (gameMode == IcsExamining && moveNum > 0 && appData.getMoveList) {
3674 ics_getting_history = H_REQUESTED;
3675 sprintf(str, "%smoves %d\n", ics_prefix, gamenum);
3680 /* Update the clocks */
3681 if (strchr(elapsed_time, '.')) {
3683 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time;
3684 timeRemaining[1][moveNum] = blackTimeRemaining = black_time;
3686 /* Time is in seconds */
3687 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time * 1000;
3688 timeRemaining[1][moveNum] = blackTimeRemaining = black_time * 1000;
3693 if (appData.zippyPlay && newGame &&
3694 gameMode != IcsObserving && gameMode != IcsIdle &&
3695 gameMode != IcsExamining)
3696 ZippyFirstBoard(moveNum, basetime, increment);
3699 /* Put the move on the move list, first converting
3700 to canonical algebraic form. */
3702 if (appData.debugMode) {
3703 if (appData.debugMode) { int f = forwardMostMove;
3704 fprintf(debugFP, "parseboard %d, castling = %d %d %d %d %d %d\n", f,
3705 castlingRights[f][0],castlingRights[f][1],castlingRights[f][2],castlingRights[f][3],castlingRights[f][4],castlingRights[f][5]);
3707 fprintf(debugFP, "accepted move %s from ICS, parse it.\n", move_str);
3708 fprintf(debugFP, "moveNum = %d\n", moveNum);
3709 fprintf(debugFP, "board = %d-%d x %d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT);
3710 setbuf(debugFP, NULL);
3712 if (moveNum <= backwardMostMove) {
3713 /* We don't know what the board looked like before
3715 strcpy(parseList[moveNum - 1], move_str);
3716 strcat(parseList[moveNum - 1], " ");
3717 strcat(parseList[moveNum - 1], elapsed_time);
3718 moveList[moveNum - 1][0] = NULLCHAR;
3719 } else if (strcmp(move_str, "none") == 0) {
3720 // [HGM] long SAN: swapped order; test for 'none' before parsing move
3721 /* Again, we don't know what the board looked like;
3722 this is really the start of the game. */
3723 parseList[moveNum - 1][0] = NULLCHAR;
3724 moveList[moveNum - 1][0] = NULLCHAR;
3725 backwardMostMove = moveNum;
3726 startedFromSetupPosition = TRUE;
3727 fromX = fromY = toX = toY = -1;
3729 // [HGM] long SAN: if legality-testing is off, disambiguation might not work or give wrong move.
3730 // So we parse the long-algebraic move string in stead of the SAN move
3731 int valid; char buf[MSG_SIZ], *prom;
3733 // str looks something like "Q/a1-a2"; kill the slash
3735 sprintf(buf, "%c%s", str[0], str+2);
3736 else strcpy(buf, str); // might be castling
3737 if((prom = strstr(move_str, "=")) && !strstr(buf, "="))
3738 strcat(buf, prom); // long move lacks promo specification!
3739 if(!appData.testLegality && move_str[1] != '@') { // drops never ambiguous (parser chokes on long form!)
3740 if(appData.debugMode)
3741 fprintf(debugFP, "replaced ICS move '%s' by '%s'\n", move_str, buf);
3742 strcpy(move_str, buf);
3744 valid = ParseOneMove(move_str, moveNum - 1, &moveType,
3745 &fromX, &fromY, &toX, &toY, &promoChar)
3746 || ParseOneMove(buf, moveNum - 1, &moveType,
3747 &fromX, &fromY, &toX, &toY, &promoChar);
3748 // end of long SAN patch
3750 (void) CoordsToAlgebraic(boards[moveNum - 1],
3751 PosFlags(moveNum - 1), EP_UNKNOWN,
3752 fromY, fromX, toY, toX, promoChar,
3753 parseList[moveNum-1]);
3754 switch (MateTest(boards[moveNum], PosFlags(moveNum), EP_UNKNOWN,
3755 castlingRights[moveNum]) ) {
3761 if(gameInfo.variant != VariantShogi)
3762 strcat(parseList[moveNum - 1], "+");
3765 case MT_STAINMATE: // [HGM] xq: for notation stalemate that wins counts as checkmate
3766 strcat(parseList[moveNum - 1], "#");
3769 strcat(parseList[moveNum - 1], " ");
3770 strcat(parseList[moveNum - 1], elapsed_time);
3771 /* currentMoveString is set as a side-effect of ParseOneMove */
3772 strcpy(moveList[moveNum - 1], currentMoveString);
3773 strcat(moveList[moveNum - 1], "\n");
3775 /* Move from ICS was illegal!? Punt. */
3776 if (appData.debugMode) {
3777 fprintf(debugFP, "Illegal move from ICS '%s'\n", move_str);
3778 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
3780 strcpy(parseList[moveNum - 1], move_str);
3781 strcat(parseList[moveNum - 1], " ");
3782 strcat(parseList[moveNum - 1], elapsed_time);
3783 moveList[moveNum - 1][0] = NULLCHAR;
3784 fromX = fromY = toX = toY = -1;
3787 if (appData.debugMode) {
3788 fprintf(debugFP, "Move parsed to '%s'\n", parseList[moveNum - 1]);
3789 setbuf(debugFP, NULL);
3793 /* Send move to chess program (BEFORE animating it). */
3794 if (appData.zippyPlay && !newGame && newMove &&
3795 (!appData.getMoveList || backwardMostMove == 0) && first.initDone) {
3797 if ((gameMode == IcsPlayingWhite && WhiteOnMove(moveNum)) ||
3798 (gameMode == IcsPlayingBlack && !WhiteOnMove(moveNum))) {
3799 if (moveList[moveNum - 1][0] == NULLCHAR) {
3800 sprintf(str, _("Couldn't parse move \"%s\" from ICS"),
3802 DisplayError(str, 0);
3804 if (first.sendTime) {
3805 SendTimeRemaining(&first, gameMode == IcsPlayingWhite);
3807 bookHit = SendMoveToBookUser(moveNum - 1, &first, FALSE); // [HGM] book
3808 if (firstMove && !bookHit) {
3810 if (first.useColors) {
3811 SendToProgram(gameMode == IcsPlayingWhite ?
3813 "black\ngo\n", &first);
3815 SendToProgram("go\n", &first);
3817 first.maybeThinking = TRUE;