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>
81 #else /* not STDC_HEADERS */
84 # else /* not HAVE_STRING_H */
86 # endif /* not HAVE_STRING_H */
87 #endif /* not STDC_HEADERS */
90 # include <sys/fcntl.h>
91 #else /* not HAVE_SYS_FCNTL_H */
94 # endif /* HAVE_FCNTL_H */
95 #endif /* not HAVE_SYS_FCNTL_H */
97 #if TIME_WITH_SYS_TIME
98 # include <sys/time.h>
102 # include <sys/time.h>
108 #if defined(_amigados) && !defined(__GNUC__)
113 extern int gettimeofday(struct timeval *, struct timezone *);
121 #include "frontend.h"
128 #include "backendz.h"
132 # define _(s) gettext (s)
133 # define N_(s) gettext_noop (s)
140 /* A point in time */
142 long sec; /* Assuming this is >= 32 bits */
143 int ms; /* Assuming this is >= 16 bits */
146 int establish P((void));
147 void read_from_player P((InputSourceRef isr, VOIDSTAR closure,
148 char *buf, int count, int error));
149 void read_from_ics P((InputSourceRef isr, VOIDSTAR closure,
150 char *buf, int count, int error));
151 void ics_printf P((char *format, ...));
152 void SendToICS P((char *s));
153 void SendToICSDelayed P((char *s, long msdelay));
154 void SendMoveToICS P((ChessMove moveType, int fromX, int fromY,
156 void HandleMachineMove P((char *message, ChessProgramState *cps));
157 int AutoPlayOneMove P((void));
158 int LoadGameOneMove P((ChessMove readAhead));
159 int LoadGameFromFile P((char *filename, int n, char *title, int useList));
160 int LoadPositionFromFile P((char *filename, int n, char *title));
161 int SavePositionToFile P((char *filename));
162 void ApplyMove P((int fromX, int fromY, int toX, int toY, int promoChar,
163 Board board, char *castle, char *ep));
164 void MakeMove P((int fromX, int fromY, int toX, int toY, int promoChar));
165 void ShowMove P((int fromX, int fromY, int toX, int toY));
166 int FinishMove P((ChessMove moveType, int fromX, int fromY, int toX, int toY,
167 /*char*/int promoChar));
168 void BackwardInner P((int target));
169 void ForwardInner P((int target));
170 void GameEnds P((ChessMove result, char *resultDetails, int whosays));
171 void EditPositionDone P((void));
172 void PrintOpponents P((FILE *fp));
173 void PrintPosition P((FILE *fp, int move));
174 void StartChessProgram P((ChessProgramState *cps));
175 void SendToProgram P((char *message, ChessProgramState *cps));
176 void SendMoveToProgram P((int moveNum, ChessProgramState *cps));
177 void ReceiveFromProgram P((InputSourceRef isr, VOIDSTAR closure,
178 char *buf, int count, int error));
179 void SendTimeControl P((ChessProgramState *cps,
180 int mps, long tc, int inc, int sd, int st));
181 char *TimeControlTagValue P((void));
182 void Attention P((ChessProgramState *cps));
183 void FeedMovesToProgram P((ChessProgramState *cps, int upto));
184 void ResurrectChessProgram P((void));
185 void DisplayComment P((int moveNumber, char *text));
186 void DisplayMove P((int moveNumber));
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];
1429 va_start(args, format);
1430 vsnprintf(buffer, sizeof(buffer), format, args);
1431 buffer[sizeof(buffer)-1] = '\0';
1440 int count, outCount, outError;
1442 if (icsPR == NULL) return;
1445 outCount = OutputMaybeTelnet(icsPR, s, count, &outError);
1446 if (outCount < count) {
1447 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1451 /* This is used for sending logon scripts to the ICS. Sending
1452 without a delay causes problems when using timestamp on ICC
1453 (at least on my machine). */
1455 SendToICSDelayed(s,msdelay)
1459 int count, outCount, outError;
1461 if (icsPR == NULL) return;
1464 if (appData.debugMode) {
1465 fprintf(debugFP, ">ICS: ");
1466 show_bytes(debugFP, s, count);
1467 fprintf(debugFP, "\n");
1469 outCount = OutputToProcessDelayed(icsPR, s, count, &outError,
1471 if (outCount < count) {
1472 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1477 /* Remove all highlighting escape sequences in s
1478 Also deletes any suffix starting with '('
1481 StripHighlightAndTitle(s)
1484 static char retbuf[MSG_SIZ];
1487 while (*s != NULLCHAR) {
1488 while (*s == '\033') {
1489 while (*s != NULLCHAR && !isalpha(*s)) s++;
1490 if (*s != NULLCHAR) s++;
1492 while (*s != NULLCHAR && *s != '\033') {
1493 if (*s == '(' || *s == '[') {
1504 /* Remove all highlighting escape sequences in s */
1509 static char retbuf[MSG_SIZ];
1512 while (*s != NULLCHAR) {
1513 while (*s == '\033') {
1514 while (*s != NULLCHAR && !isalpha(*s)) s++;
1515 if (*s != NULLCHAR) s++;
1517 while (*s != NULLCHAR && *s != '\033') {
1525 char *variantNames[] = VARIANT_NAMES;
1530 return variantNames[v];
1534 /* Identify a variant from the strings the chess servers use or the
1535 PGN Variant tag names we use. */
1542 VariantClass v = VariantNormal;
1543 int i, found = FALSE;
1548 /* [HGM] skip over optional board-size prefixes */
1549 if( sscanf(e, "%dx%d_", &i, &i) == 2 ||
1550 sscanf(e, "%dx%d+%d_", &i, &i, &i) == 3 ) {
1551 while( *e++ != '_');
1554 if(StrCaseStr(e, "misc/")) { // [HGM] on FICS, misc/shogi is not shogi
1558 for (i=0; i<sizeof(variantNames)/sizeof(char*); i++) {
1559 if (StrCaseStr(e, variantNames[i])) {
1560 v = (VariantClass) i;
1567 if ((StrCaseStr(e, "fischer") && StrCaseStr(e, "random"))
1568 || StrCaseStr(e, "wild/fr")
1569 || StrCaseStr(e, "frc") || StrCaseStr(e, "960")) {
1570 v = VariantFischeRandom;
1571 } else if ((i = 4, p = StrCaseStr(e, "wild")) ||
1572 (i = 1, p = StrCaseStr(e, "w"))) {
1574 while (*p && (isspace(*p) || *p == '(' || *p == '/')) p++;
1581 case 0: /* FICS only, actually */
1583 /* Castling legal even if K starts on d-file */
1584 v = VariantWildCastle;
1589 /* Castling illegal even if K & R happen to start in
1590 normal positions. */
1591 v = VariantNoCastle;
1604 /* Castling legal iff K & R start in normal positions */
1610 /* Special wilds for position setup; unclear what to do here */
1611 v = VariantLoadable;
1614 /* Bizarre ICC game */
1615 v = VariantTwoKings;
1618 v = VariantKriegspiel;
1624 v = VariantFischeRandom;
1627 v = VariantCrazyhouse;
1630 v = VariantBughouse;
1636 /* Not quite the same as FICS suicide! */
1637 v = VariantGiveaway;
1643 v = VariantShatranj;
1646 /* Temporary names for future ICC types. The name *will* change in
1647 the next xboard/WinBoard release after ICC defines it. */
1685 v = VariantCapablanca;
1688 v = VariantKnightmate;
1694 v = VariantCylinder;
1700 v = VariantCapaRandom;
1703 v = VariantBerolina;
1715 /* Found "wild" or "w" in the string but no number;
1716 must assume it's normal chess. */
1720 sprintf(buf, _("Unknown wild type %d"), wnum);
1721 DisplayError(buf, 0);
1727 if (appData.debugMode) {
1728 fprintf(debugFP, _("recognized '%s' (%d) as variant %s\n"),
1729 e, wnum, VariantName(v));
1734 static int leftover_start = 0, leftover_len = 0;
1735 char star_match[STAR_MATCH_N][MSG_SIZ];
1737 /* Test whether pattern is present at &buf[*index]; if so, return TRUE,
1738 advance *index beyond it, and set leftover_start to the new value of
1739 *index; else return FALSE. If pattern contains the character '*', it
1740 matches any sequence of characters not containing '\r', '\n', or the
1741 character following the '*' (if any), and the matched sequence(s) are
1742 copied into star_match.
1745 looking_at(buf, index, pattern)
1750 char *bufp = &buf[*index], *patternp = pattern;
1752 char *matchp = star_match[0];
1755 if (*patternp == NULLCHAR) {
1756 *index = leftover_start = bufp - buf;
1760 if (*bufp == NULLCHAR) return FALSE;
1761 if (*patternp == '*') {
1762 if (*bufp == *(patternp + 1)) {
1764 matchp = star_match[++star_count];
1768 } else if (*bufp == '\n' || *bufp == '\r') {
1770 if (*patternp == NULLCHAR)
1775 *matchp++ = *bufp++;
1779 if (*patternp != *bufp) return FALSE;
1786 SendToPlayer(data, length)
1790 int error, outCount;
1791 outCount = OutputToProcess(NoProc, data, length, &error);
1792 if (outCount < length) {
1793 DisplayFatalError(_("Error writing to display"), error, 1);
1798 PackHolding(packed, holding)
1810 switch (runlength) {
1821 sprintf(q, "%d", runlength);
1833 /* Telnet protocol requests from the front end */
1835 TelnetRequest(ddww, option)
1836 unsigned char ddww, option;
1838 unsigned char msg[3];
1839 int outCount, outError;
1841 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet) return;
1843 if (appData.debugMode) {
1844 char buf1[8], buf2[8], *ddwwStr, *optionStr;
1860 sprintf(buf1, "%d", ddww);
1869 sprintf(buf2, "%d", option);
1872 fprintf(debugFP, ">%s %s ", ddwwStr, optionStr);
1877 outCount = OutputToProcess(icsPR, (char *)msg, 3, &outError);
1879 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1886 if (!appData.icsActive) return;
1887 TelnetRequest(TN_DO, TN_ECHO);
1893 if (!appData.icsActive) return;
1894 TelnetRequest(TN_DONT, TN_ECHO);
1898 CopyHoldings(Board board, char *holdings, ChessSquare lowestPiece)
1900 /* put the holdings sent to us by the server on the board holdings area */
1901 int i, j, holdingsColumn, holdingsStartRow, direction, countsColumn;
1905 if(gameInfo.holdingsWidth < 2) return;
1907 if( (int)lowestPiece >= BlackPawn ) {
1910 holdingsStartRow = BOARD_HEIGHT-1;
1913 holdingsColumn = BOARD_WIDTH-1;
1914 countsColumn = BOARD_WIDTH-2;
1915 holdingsStartRow = 0;
1919 for(i=0; i<BOARD_HEIGHT; i++) { /* clear holdings */
1920 board[i][holdingsColumn] = EmptySquare;
1921 board[i][countsColumn] = (ChessSquare) 0;
1923 while( (p=*holdings++) != NULLCHAR ) {
1924 piece = CharToPiece( ToUpper(p) );
1925 if(piece == EmptySquare) continue;
1926 /*j = (int) piece - (int) WhitePawn;*/
1927 j = PieceToNumber(piece);
1928 if(j >= gameInfo.holdingsSize) continue; /* ignore pieces that do not fit */
1929 if(j < 0) continue; /* should not happen */
1930 piece = (ChessSquare) ( (int)piece + (int)lowestPiece );
1931 board[holdingsStartRow+j*direction][holdingsColumn] = piece;
1932 board[holdingsStartRow+j*direction][countsColumn]++;
1939 VariantSwitch(Board board, VariantClass newVariant)
1941 int newHoldingsWidth, newWidth = 8, newHeight = 8, i, j;
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 */
1969 newWidth = 9; newHeight = 9;
1970 gameInfo.holdingsSize = 7;
1971 case VariantBughouse:
1972 case VariantCrazyhouse:
1973 newHoldingsWidth = 2; break;
1977 newHoldingsWidth = 2;
1978 gameInfo.holdingsSize = 8;
1981 case VariantCapablanca:
1982 case VariantCapaRandom:
1985 newHoldingsWidth = gameInfo.holdingsSize = 0;
1988 if(newWidth != gameInfo.boardWidth ||
1989 newHeight != gameInfo.boardHeight ||
1990 newHoldingsWidth != gameInfo.holdingsWidth ) {
1992 /* shift position to new playing area, if needed */
1993 if(newHoldingsWidth > gameInfo.holdingsWidth) {
1994 for(i=0; i<BOARD_HEIGHT; i++)
1995 for(j=BOARD_RGHT-1; j>=BOARD_LEFT; j--)
1996 board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
1998 for(i=0; i<newHeight; i++) {
1999 board[i][0] = board[i][newWidth+2*newHoldingsWidth-1] = EmptySquare;
2000 board[i][1] = board[i][newWidth+2*newHoldingsWidth-2] = (ChessSquare) 0;
2002 } else if(newHoldingsWidth < gameInfo.holdingsWidth) {
2003 for(i=0; i<BOARD_HEIGHT; i++)
2004 for(j=BOARD_LEFT; j<BOARD_RGHT; j++)
2005 board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
2008 gameInfo.boardWidth = newWidth;
2009 gameInfo.boardHeight = newHeight;
2010 gameInfo.holdingsWidth = newHoldingsWidth;
2011 gameInfo.variant = newVariant;
2012 InitDrawingSizes(-2, 0);
2013 InitPosition(FALSE); /* this sets up board[0], but also other stuff */
2014 } else { gameInfo.variant = newVariant; InitPosition(FALSE); }
2016 DrawPosition(TRUE, boards[currentMove]);
2019 static int loggedOn = FALSE;
2021 /*-- Game start info cache: --*/
2023 char gs_kind[MSG_SIZ];
2024 static char player1Name[128] = "";
2025 static char player2Name[128] = "";
\r
2026 static char cont_seq[] = "\n\\ ";
2027 static int player1Rating = -1;
2028 static int player2Rating = -1;
2029 /*----------------------------*/
2031 ColorClass curColor = ColorNormal;
2032 int suppressKibitz = 0;
2035 read_from_ics(isr, closure, data, count, error)
2042 #define BUF_SIZE 8192
2043 #define STARTED_NONE 0
2044 #define STARTED_MOVES 1
2045 #define STARTED_BOARD 2
2046 #define STARTED_OBSERVE 3
2047 #define STARTED_HOLDINGS 4
2048 #define STARTED_CHATTER 5
2049 #define STARTED_COMMENT 6
2050 #define STARTED_MOVES_NOHIDE 7
2052 static int started = STARTED_NONE;
2053 static char parse[20000];
2054 static int parse_pos = 0;
2055 static char buf[BUF_SIZE + 1];
2056 static int firstTime = TRUE, intfSet = FALSE;
2057 static ColorClass prevColor = ColorNormal;
2058 static int savingComment = FALSE;
\r
2059 static int cmatch = 0; // continuation sequence match
\r
2066 int backup; /* [DM] For zippy color lines */
2068 char talker[MSG_SIZ]; // [HGM] chat
2071 if (appData.debugMode) {
2073 fprintf(debugFP, "<ICS: ");
2074 show_bytes(debugFP, data, count);
2075 fprintf(debugFP, "\n");
2079 if (appData.debugMode) { int f = forwardMostMove;
2080 fprintf(debugFP, "ics input %d, castling = %d %d %d %d %d %d\n", f,
2081 castlingRights[f][0],castlingRights[f][1],castlingRights[f][2],castlingRights[f][3],castlingRights[f][4],castlingRights[f][5]);
2084 /* If last read ended with a partial line that we couldn't parse,
2085 prepend it to the new read and try again. */
2086 if (leftover_len > 0) {
2087 for (i=0; i<leftover_len; i++)
2088 buf[i] = buf[leftover_start + i];
2091 /* copy new characters into the buffer */
\r
2092 bp = buf + leftover_len;
\r
2093 buf_len=leftover_len;
\r
2094 for (i=0; i<count; i++)
\r
2097 if (data[i] == '\r')
\r
2100 // join lines split by ICS?
\r
2101 if (!appData.noJoin)
\r
2104 Joining just consists of finding matches against the
\r
2105 continuation sequence, and discarding that sequence
\r
2106 if found instead of copying it. So, until a match
\r
2107 fails, there's nothing to do since it might be the
\r
2108 complete sequence, and thus, something we don't want
\r
2111 if (data[i] == cont_seq[cmatch])
\r
2114 if (cmatch == strlen(cont_seq))
\r
2115 cmatch = 0; // complete match. just reset the counter
\r
2121 match failed, so we have to copy what matched before
\r
2122 falling through and copying this character. In reality,
\r
2123 this will only ever be just the newline character, but
\r
2124 it doesn't hurt to be precise.
\r
2126 strncpy(bp, cont_seq, cmatch);
\r
2128 buf_len += cmatch;
\r
2138 buf[buf_len] = NULLCHAR;
2139 next_out = leftover_len;
2143 while (i < buf_len) {
2144 /* Deal with part of the TELNET option negotiation
2145 protocol. We refuse to do anything beyond the
2146 defaults, except that we allow the WILL ECHO option,
2147 which ICS uses to turn off password echoing when we are
2148 directly connected to it. We reject this option
2149 if localLineEditing mode is on (always on in xboard)
2150 and we are talking to port 23, which might be a real
2151 telnet server that will try to keep WILL ECHO on permanently.
2153 if (buf_len - i >= 3 && (unsigned char) buf[i] == TN_IAC) {
2154 static int remoteEchoOption = FALSE; /* telnet ECHO option */
2155 unsigned char option;
2157 switch ((unsigned char) buf[++i]) {
2159 if (appData.debugMode)
2160 fprintf(debugFP, "\n<WILL ");
2161 switch (option = (unsigned char) buf[++i]) {
2163 if (appData.debugMode)
2164 fprintf(debugFP, "ECHO ");
2165 /* Reply only if this is a change, according
2166 to the protocol rules. */
2167 if (remoteEchoOption) break;
2168 if (appData.localLineEditing &&
2169 atoi(appData.icsPort) == TN_PORT) {
2170 TelnetRequest(TN_DONT, TN_ECHO);
2173 TelnetRequest(TN_DO, TN_ECHO);
2174 remoteEchoOption = TRUE;
2178 if (appData.debugMode)
2179 fprintf(debugFP, "%d ", option);
2180 /* Whatever this is, we don't want it. */
2181 TelnetRequest(TN_DONT, option);
2186 if (appData.debugMode)
2187 fprintf(debugFP, "\n<WONT ");
2188 switch (option = (unsigned char) buf[++i]) {
2190 if (appData.debugMode)
2191 fprintf(debugFP, "ECHO ");
2192 /* Reply only if this is a change, according
2193 to the protocol rules. */
2194 if (!remoteEchoOption) break;
2196 TelnetRequest(TN_DONT, TN_ECHO);
2197 remoteEchoOption = FALSE;
2200 if (appData.debugMode)
2201 fprintf(debugFP, "%d ", (unsigned char) option);
2202 /* Whatever this is, it must already be turned
2203 off, because we never agree to turn on
2204 anything non-default, so according to the
2205 protocol rules, we don't reply. */
2210 if (appData.debugMode)
2211 fprintf(debugFP, "\n<DO ");
2212 switch (option = (unsigned char) buf[++i]) {
2214 /* Whatever this is, we refuse to do it. */
2215 if (appData.debugMode)
2216 fprintf(debugFP, "%d ", option);
2217 TelnetRequest(TN_WONT, option);
2222 if (appData.debugMode)
2223 fprintf(debugFP, "\n<DONT ");
2224 switch (option = (unsigned char) buf[++i]) {
2226 if (appData.debugMode)
2227 fprintf(debugFP, "%d ", option);
2228 /* Whatever this is, we are already not doing
2229 it, because we never agree to do anything
2230 non-default, so according to the protocol
2231 rules, we don't reply. */
2236 if (appData.debugMode)
2237 fprintf(debugFP, "\n<IAC ");
2238 /* Doubled IAC; pass it through */
2242 if (appData.debugMode)
2243 fprintf(debugFP, "\n<%d ", (unsigned char) buf[i]);
2244 /* Drop all other telnet commands on the floor */
2247 if (oldi > next_out)
2248 SendToPlayer(&buf[next_out], oldi - next_out);
2254 /* OK, this at least will *usually* work */
2255 if (!loggedOn && looking_at(buf, &i, "ics%")) {
2259 if (loggedOn && !intfSet) {
2260 if (ics_type == ICS_ICC) {
2262 "/set-quietly interface %s\n/set-quietly style 12\n",
2264 } else if (ics_type == ICS_CHESSNET) {
2265 sprintf(str, "/style 12\n");
2267 strcpy(str, "alias $ @\n$set interface ");
2268 strcat(str, programVersion);
2269 strcat(str, "\n$iset startpos 1\n$iset ms 1\n");
2271 strcat(str, "$iset nohighlight 1\n");
2273 strcat(str, "$iset lock 1\n$style 12\n");
2276 NotifyFrontendLogin();
2280 if (started == STARTED_COMMENT) {
2281 /* Accumulate characters in comment */
2282 parse[parse_pos++] = buf[i];
2283 if (buf[i] == '\n') {
2284 parse[parse_pos] = NULLCHAR;
2285 if(chattingPartner>=0) {
2287 sprintf(mess, "%s%s", talker, parse);
2288 OutputChatMessage(chattingPartner, mess);
2289 chattingPartner = -1;
2291 if(!suppressKibitz) // [HGM] kibitz
2292 AppendComment(forwardMostMove, StripHighlight(parse));
2293 else { // [HGM kibitz: divert memorized engine kibitz to engine-output window
2294 int nrDigit = 0, nrAlph = 0, i;
2295 if(parse_pos > MSG_SIZ - 30) // defuse unreasonably long input
2296 { parse_pos = MSG_SIZ-30; parse[parse_pos - 1] = '\n'; }
2297 parse[parse_pos] = NULLCHAR;
2298 // try to be smart: if it does not look like search info, it should go to
2299 // ICS interaction window after all, not to engine-output window.
2300 for(i=0; i<parse_pos; i++) { // count letters and digits
2301 nrDigit += (parse[i] >= '0' && parse[i] <= '9');
2302 nrAlph += (parse[i] >= 'a' && parse[i] <= 'z');
2303 nrAlph += (parse[i] >= 'A' && parse[i] <= 'Z');
2305 if(nrAlph < 9*nrDigit) { // if more than 10% digit we assume search info
2306 int depth=0; float score;
2307 if(sscanf(parse, "!!! %f/%d", &score, &depth) == 2 && depth>0) {
2308 // [HGM] kibitz: save kibitzed opponent info for PGN and eval graph
2309 pvInfoList[forwardMostMove-1].depth = depth;
2310 pvInfoList[forwardMostMove-1].score = 100*score;
2312 OutputKibitz(suppressKibitz, parse);
2315 sprintf(tmp, _("your opponent kibitzes: %s"), parse);
2316 SendToPlayer(tmp, strlen(tmp));
2319 started = STARTED_NONE;
2321 /* Don't match patterns against characters in chatter */
2326 if (started == STARTED_CHATTER) {
2327 if (buf[i] != '\n') {
2328 /* Don't match patterns against characters in chatter */
2332 started = STARTED_NONE;
2335 /* Kludge to deal with rcmd protocol */
2336 if (firstTime && looking_at(buf, &i, "\001*")) {
2337 DisplayFatalError(&buf[1], 0, 1);
2343 if (!loggedOn && looking_at(buf, &i, "chessclub.com")) {
2346 if (appData.debugMode)
2347 fprintf(debugFP, "ics_type %d\n", ics_type);
2350 if (!loggedOn && looking_at(buf, &i, "freechess.org")) {
2351 ics_type = ICS_FICS;
2353 if (appData.debugMode)
2354 fprintf(debugFP, "ics_type %d\n", ics_type);
2357 if (!loggedOn && looking_at(buf, &i, "chess.net")) {
2358 ics_type = ICS_CHESSNET;
2360 if (appData.debugMode)
2361 fprintf(debugFP, "ics_type %d\n", ics_type);
2366 (looking_at(buf, &i, "\"*\" is *a registered name") ||
2367 looking_at(buf, &i, "Logging you in as \"*\"") ||
2368 looking_at(buf, &i, "will be \"*\""))) {
2369 strcpy(ics_handle, star_match[0]);
2373 if (loggedOn && !have_set_title && ics_handle[0] != NULLCHAR) {
2375 snprintf(buf, sizeof(buf), "%s@%s", ics_handle, appData.icsHost);
2376 DisplayIcsInteractionTitle(buf);
2377 have_set_title = TRUE;
2380 /* skip finger notes */
2381 if (started == STARTED_NONE &&
2382 ((buf[i] == ' ' && isdigit(buf[i+1])) ||
2383 (buf[i] == '1' && buf[i+1] == '0')) &&
2384 buf[i+2] == ':' && buf[i+3] == ' ') {
2385 started = STARTED_CHATTER;
2390 /* skip formula vars */
2391 if (started == STARTED_NONE &&
2392 buf[i] == 'f' && isdigit(buf[i+1]) && buf[i+2] == ':') {
2393 started = STARTED_CHATTER;
2399 // [HGM] kibitz: try to recognize opponent engine-score kibitzes, to divert them to engine-output window
2400 if (appData.autoKibitz && started == STARTED_NONE &&
2401 !appData.icsEngineAnalyze && // [HGM] [DM] ICS analyze
2402 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack || gameMode == IcsObserving)) {
2403 if(looking_at(buf, &i, "* kibitzes: ") &&
2404 (StrStr(star_match[0], gameInfo.white) == star_match[0] ||
2405 StrStr(star_match[0], gameInfo.black) == star_match[0] )) { // kibitz of self or opponent
2406 suppressKibitz = TRUE;
2407 if((StrStr(star_match[0], gameInfo.white) == star_match[0]
2408 && (gameMode == IcsPlayingWhite)) ||
2409 (StrStr(star_match[0], gameInfo.black) == star_match[0]
2410 && (gameMode == IcsPlayingBlack)) ) // opponent kibitz
2411 started = STARTED_CHATTER; // own kibitz we simply discard
2413 started = STARTED_COMMENT; // make sure it will be collected in parse[]
2414 parse_pos = 0; parse[0] = NULLCHAR;
2415 savingComment = TRUE;
2416 suppressKibitz = gameMode != IcsObserving ? 2 :
2417 (StrStr(star_match[0], gameInfo.white) == NULL) + 1;
2421 if(looking_at(buf, &i, "kibitzed to")) { // suppress the acknowledgements of our own autoKibitz
2422 started = STARTED_CHATTER;
2423 suppressKibitz = TRUE;
2425 } // [HGM] kibitz: end of patch
2427 //if(appData.debugMode) fprintf(debugFP, "hunt for tell, buf = %s\n", buf+i);
2429 // [HGM] chat: intercept tells by users for which we have an open chat window
2431 if(started == STARTED_NONE && (looking_at(buf, &i, "* tells you:") || looking_at(buf, &i, "* says:") ||
2432 looking_at(buf, &i, "* whispers:") ||
2433 looking_at(buf, &i, "*(*):") && (sscanf(star_match[1], "%d", &channel),1) ||
2434 looking_at(buf, &i, "*(*)(*):") && sscanf(star_match[2], "%d", &channel) == 1 )) {
2436 sscanf(star_match[0], "%[^(]", talker+1); // strip (C) or (U) off ICS handle
2437 chattingPartner = -1;
2439 if(channel >= 0) // channel broadcast; look if there is a chatbox for this channel
2440 for(p=0; p<MAX_CHAT; p++) {
2441 if(channel == atoi(chatPartner[p])) {
2442 talker[0] = '['; strcat(talker, "]");
2443 chattingPartner = p; break;
2446 if(buf[i-3] == 'r') // whisper; look if there is a WHISPER chatbox
2447 for(p=0; p<MAX_CHAT; p++) {
2448 if(!strcmp("WHISPER", chatPartner[p])) {
2449 talker[0] = '['; strcat(talker, "]");
2450 chattingPartner = p; break;
2453 if(chattingPartner<0) // if not, look if there is a chatbox for this indivdual
2454 for(p=0; p<MAX_CHAT; p++) if(!StrCaseCmp(talker+1, chatPartner[p])) {
2456 chattingPartner = p; break;
2458 if(chattingPartner<0) i = oldi; else {
2459 started = STARTED_COMMENT;
2460 parse_pos = 0; parse[0] = NULLCHAR;
2461 savingComment = TRUE;
2462 suppressKibitz = TRUE;
2464 } // [HGM] chat: end of patch
2466 if (appData.zippyTalk || appData.zippyPlay) {
2467 /* [DM] Backup address for color zippy lines */
2471 if (loggedOn == TRUE)
2472 if (ZippyControl(buf, &backup) || ZippyConverse(buf, &backup) ||
2473 (appData.zippyPlay && ZippyMatch(buf, &backup)));
2475 if (ZippyControl(buf, &i) ||
2476 ZippyConverse(buf, &i) ||
2477 (appData.zippyPlay && ZippyMatch(buf, &i))) {
2479 if (!appData.colorize) continue;
2483 } // [DM] 'else { ' deleted
2485 /* Regular tells and says */
2486 (tkind = 1, looking_at(buf, &i, "* tells you: ")) ||
2487 looking_at(buf, &i, "* (your partner) tells you: ") ||
2488 looking_at(buf, &i, "* says: ") ||
2489 /* Don't color "message" or "messages" output */
2490 (tkind = 5, looking_at(buf, &i, "*. * (*:*): ")) ||
2491 looking_at(buf, &i, "*. * at *:*: ") ||
2492 looking_at(buf, &i, "--* (*:*): ") ||
2493 /* Message notifications (same color as tells) */
2494 looking_at(buf, &i, "* has left a message ") ||
2495 looking_at(buf, &i, "* just sent you a message:\n") ||
2496 /* Whispers and kibitzes */
2497 (tkind = 2, looking_at(buf, &i, "* whispers: ")) ||
2498 looking_at(buf, &i, "* kibitzes: ") ||
2500 (tkind = 3, looking_at(buf, &i, "*(*: "))) {
2502 if (tkind == 1 && strchr(star_match[0], ':')) {
2503 /* Avoid "tells you:" spoofs in channels */
2506 if (star_match[0][0] == NULLCHAR ||
2507 strchr(star_match[0], ' ') ||
2508 (tkind == 3 && strchr(star_match[1], ' '))) {
2509 /* Reject bogus matches */
2512 if (appData.colorize) {
2513 if (oldi > next_out) {
2514 SendToPlayer(&buf[next_out], oldi - next_out);
2519 Colorize(ColorTell, FALSE);
2520 curColor = ColorTell;
2523 Colorize(ColorKibitz, FALSE);
2524 curColor = ColorKibitz;
2527 p = strrchr(star_match[1], '(');
2534 Colorize(ColorChannel1, FALSE);
2535 curColor = ColorChannel1;
2537 Colorize(ColorChannel, FALSE);
2538 curColor = ColorChannel;
2542 curColor = ColorNormal;
2546 if (started == STARTED_NONE && appData.autoComment &&
2547 (gameMode == IcsObserving ||
2548 gameMode == IcsPlayingWhite ||
2549 gameMode == IcsPlayingBlack)) {
2550 parse_pos = i - oldi;
2551 memcpy(parse, &buf[oldi], parse_pos);
2552 parse[parse_pos] = NULLCHAR;
2553 started = STARTED_COMMENT;
2554 savingComment = TRUE;
2556 started = STARTED_CHATTER;
2557 savingComment = FALSE;
2564 if (looking_at(buf, &i, "* s-shouts: ") ||
2565 looking_at(buf, &i, "* c-shouts: ")) {
2566 if (appData.colorize) {
2567 if (oldi > next_out) {
2568 SendToPlayer(&buf[next_out], oldi - next_out);
2571 Colorize(ColorSShout, FALSE);
2572 curColor = ColorSShout;
2575 started = STARTED_CHATTER;
2579 if (looking_at(buf, &i, "--->")) {
2584 if (looking_at(buf, &i, "* shouts: ") ||
2585 looking_at(buf, &i, "--> ")) {
2586 if (appData.colorize) {
2587 if (oldi > next_out) {
2588 SendToPlayer(&buf[next_out], oldi - next_out);
2591 Colorize(ColorShout, FALSE);
2592 curColor = ColorShout;
2595 started = STARTED_CHATTER;
2599 if (looking_at( buf, &i, "Challenge:")) {
2600 if (appData.colorize) {
2601 if (oldi > next_out) {
2602 SendToPlayer(&buf[next_out], oldi - next_out);
2605 Colorize(ColorChallenge, FALSE);
2606 curColor = ColorChallenge;
2612 if (looking_at(buf, &i, "* offers you") ||
2613 looking_at(buf, &i, "* offers to be") ||
2614 looking_at(buf, &i, "* would like to") ||
2615 looking_at(buf, &i, "* requests to") ||
2616 looking_at(buf, &i, "Your opponent offers") ||
2617 looking_at(buf, &i, "Your opponent requests")) {
2619 if (appData.colorize) {
2620 if (oldi > next_out) {
2621 SendToPlayer(&buf[next_out], oldi - next_out);
2624 Colorize(ColorRequest, FALSE);
2625 curColor = ColorRequest;
2630 if (looking_at(buf, &i, "* (*) seeking")) {
2631 if (appData.colorize) {
2632 if (oldi > next_out) {
2633 SendToPlayer(&buf[next_out], oldi - next_out);
2636 Colorize(ColorSeek, FALSE);
2637 curColor = ColorSeek;
2642 if (looking_at(buf, &i, "\\ ")) {
2643 if (prevColor != ColorNormal) {
2644 if (oldi > next_out) {
2645 SendToPlayer(&buf[next_out], oldi - next_out);
2648 Colorize(prevColor, TRUE);
2649 curColor = prevColor;
2651 if (savingComment) {
2652 parse_pos = i - oldi;
2653 memcpy(parse, &buf[oldi], parse_pos);
2654 parse[parse_pos] = NULLCHAR;
2655 started = STARTED_COMMENT;
2657 started = STARTED_CHATTER;
2662 if (looking_at(buf, &i, "Black Strength :") ||
2663 looking_at(buf, &i, "<<< style 10 board >>>") ||
2664 looking_at(buf, &i, "<10>") ||
2665 looking_at(buf, &i, "#@#")) {
2666 /* Wrong board style */
2668 SendToICS(ics_prefix);
2669 SendToICS("set style 12\n");
2670 SendToICS(ics_prefix);
2671 SendToICS("refresh\n");
2675 if (!have_sent_ICS_logon && looking_at(buf, &i, "login:")) {
2677 have_sent_ICS_logon = 1;
2681 if (ics_getting_history != H_GETTING_MOVES /*smpos kludge*/ &&
2682 (looking_at(buf, &i, "\n<12> ") ||
2683 looking_at(buf, &i, "<12> "))) {
2685 if (oldi > next_out) {
2686 SendToPlayer(&buf[next_out], oldi - next_out);
2689 started = STARTED_BOARD;
2694 if ((started == STARTED_NONE && looking_at(buf, &i, "\n<b1> ")) ||
2695 looking_at(buf, &i, "<b1> ")) {
2696 if (oldi > next_out) {
2697 SendToPlayer(&buf[next_out], oldi - next_out);
2700 started = STARTED_HOLDINGS;
2705 if (looking_at(buf, &i, "* *vs. * *--- *")) {
2707 /* Header for a move list -- first line */
2709 switch (ics_getting_history) {
2713 case BeginningOfGame:
2714 /* User typed "moves" or "oldmoves" while we
2715 were idle. Pretend we asked for these
2716 moves and soak them up so user can step
2717 through them and/or save them.
2720 gameMode = IcsObserving;
2723 ics_getting_history = H_GOT_UNREQ_HEADER;
2725 case EditGame: /*?*/
2726 case EditPosition: /*?*/
2727 /* Should above feature work in these modes too? */
2728 /* For now it doesn't */
2729 ics_getting_history = H_GOT_UNWANTED_HEADER;
2732 ics_getting_history = H_GOT_UNWANTED_HEADER;
2737 /* Is this the right one? */
2738 if (gameInfo.white && gameInfo.black &&
2739 strcmp(gameInfo.white, star_match[0]) == 0 &&
2740 strcmp(gameInfo.black, star_match[2]) == 0) {
2742 ics_getting_history = H_GOT_REQ_HEADER;
2745 case H_GOT_REQ_HEADER:
2746 case H_GOT_UNREQ_HEADER:
2747 case H_GOT_UNWANTED_HEADER:
2748 case H_GETTING_MOVES:
2749 /* Should not happen */
2750 DisplayError(_("Error gathering move list: two headers"), 0);
2751 ics_getting_history = H_FALSE;
2755 /* Save player ratings into gameInfo if needed */
2756 if ((ics_getting_history == H_GOT_REQ_HEADER ||
2757 ics_getting_history == H_GOT_UNREQ_HEADER) &&
2758 (gameInfo.whiteRating == -1 ||
2759 gameInfo.blackRating == -1)) {
2761 gameInfo.whiteRating = string_to_rating(star_match[1]);
2762 gameInfo.blackRating = string_to_rating(star_match[3]);
2763 if (appData.debugMode)
2764 fprintf(debugFP, _("Ratings from header: W %d, B %d\n"),
2765 gameInfo.whiteRating, gameInfo.blackRating);
2770 if (looking_at(buf, &i,
2771 "* * match, initial time: * minute*, increment: * second")) {
2772 /* Header for a move list -- second line */
2773 /* Initial board will follow if this is a wild game */
2774 if (gameInfo.event != NULL) free(gameInfo.event);
2775 sprintf(str, "ICS %s %s match", star_match[0], star_match[1]);
2776 gameInfo.event = StrSave(str);
2777 /* [HGM] we switched variant. Translate boards if needed. */
2778 VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event));
2782 if (looking_at(buf, &i, "Move ")) {
2783 /* Beginning of a move list */
2784 switch (ics_getting_history) {
2786 /* Normally should not happen */
2787 /* Maybe user hit reset while we were parsing */
2790 /* Happens if we are ignoring a move list that is not
2791 * the one we just requested. Common if the user
2792 * tries to observe two games without turning off
2795 case H_GETTING_MOVES:
2796 /* Should not happen */
2797 DisplayError(_("Error gathering move list: nested"), 0);
2798 ics_getting_history = H_FALSE;
2800 case H_GOT_REQ_HEADER:
2801 ics_getting_history = H_GETTING_MOVES;
2802 started = STARTED_MOVES;
2804 if (oldi > next_out) {
2805 SendToPlayer(&buf[next_out], oldi - next_out);
2808 case H_GOT_UNREQ_HEADER:
2809 ics_getting_history = H_GETTING_MOVES;
2810 started = STARTED_MOVES_NOHIDE;
2813 case H_GOT_UNWANTED_HEADER:
2814 ics_getting_history = H_FALSE;
2820 if (looking_at(buf, &i, "% ") ||
2821 ((started == STARTED_MOVES || started == STARTED_MOVES_NOHIDE)
2822 && looking_at(buf, &i, "}*"))) { char *bookHit = NULL; // [HGM] book
2823 savingComment = FALSE;
2826 case STARTED_MOVES_NOHIDE:
2827 memcpy(&parse[parse_pos], &buf[oldi], i - oldi);
2828 parse[parse_pos + i - oldi] = NULLCHAR;
2829 ParseGameHistory(parse);
2831 if (appData.zippyPlay && first.initDone) {
2832 FeedMovesToProgram(&first, forwardMostMove);
2833 if (gameMode == IcsPlayingWhite) {
2834 if (WhiteOnMove(forwardMostMove)) {
2835 if (first.sendTime) {
2836 if (first.useColors) {
2837 SendToProgram("black\n", &first);
2839 SendTimeRemaining(&first, TRUE);
2841 if (first.useColors) {
2842 SendToProgram("white\n", &first); // [HGM] book: made sending of "go\n" book dependent
2844 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: probe book for initial pos
2845 first.maybeThinking = TRUE;
2847 if (first.usePlayother) {
2848 if (first.sendTime) {
2849 SendTimeRemaining(&first, TRUE);
2851 SendToProgram("playother\n", &first);
2857 } else if (gameMode == IcsPlayingBlack) {
2858 if (!WhiteOnMove(forwardMostMove)) {
2859 if (first.sendTime) {
2860 if (first.useColors) {
2861 SendToProgram("white\n", &first);
2863 SendTimeRemaining(&first, FALSE);
2865 if (first.useColors) {
2866 SendToProgram("black\n", &first);
2868 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE);
2869 first.maybeThinking = TRUE;
2871 if (first.usePlayother) {
2872 if (first.sendTime) {
2873 SendTimeRemaining(&first, FALSE);
2875 SendToProgram("playother\n", &first);
2884 if (gameMode == IcsObserving && ics_gamenum == -1) {
2885 /* Moves came from oldmoves or moves command
2886 while we weren't doing anything else.
2888 currentMove = forwardMostMove;
2889 ClearHighlights();/*!!could figure this out*/
2890 flipView = appData.flipView;
2891 DrawPosition(FALSE, boards[currentMove]);
2892 DisplayBothClocks();
2893 sprintf(str, "%s vs. %s",
2894 gameInfo.white, gameInfo.black);
2898 /* Moves were history of an active game */
2899 if (gameInfo.resultDetails != NULL) {
2900 free(gameInfo.resultDetails);
2901 gameInfo.resultDetails = NULL;
2904 HistorySet(parseList, backwardMostMove,
2905 forwardMostMove, currentMove-1);
2906 DisplayMove(currentMove - 1);
2907 if (started == STARTED_MOVES) next_out = i;
2908 started = STARTED_NONE;
2909 ics_getting_history = H_FALSE;
2912 case STARTED_OBSERVE:
2913 started = STARTED_NONE;
2914 SendToICS(ics_prefix);
2915 SendToICS("refresh\n");
2921 if(bookHit) { // [HGM] book: simulate book reply
2922 static char bookMove[MSG_SIZ]; // a bit generous?
2924 programStats.nodes = programStats.depth = programStats.time =
2925 programStats.score = programStats.got_only_move = 0;
2926 sprintf(programStats.movelist, "%s (xbook)", bookHit);
2928 strcpy(bookMove, "move ");
2929 strcat(bookMove, bookHit);
2930 HandleMachineMove(bookMove, &first);
2935 if ((started == STARTED_MOVES || started == STARTED_BOARD ||
2936 started == STARTED_HOLDINGS ||
2937 started == STARTED_MOVES_NOHIDE) && i >= leftover_len) {
2938 /* Accumulate characters in move list or board */
2939 parse[parse_pos++] = buf[i];
2942 /* Start of game messages. Mostly we detect start of game
2943 when the first board image arrives. On some versions
2944 of the ICS, though, we need to do a "refresh" after starting
2945 to observe in order to get the current board right away. */
2946 if (looking_at(buf, &i, "Adding game * to observation list")) {
2947 started = STARTED_OBSERVE;
2951 /* Handle auto-observe */
2952 if (appData.autoObserve &&
2953 (gameMode == IcsIdle || gameMode == BeginningOfGame) &&
2954 looking_at(buf, &i, "Game notification: * (*) vs. * (*)")) {
2956 /* Choose the player that was highlighted, if any. */
2957 if (star_match[0][0] == '\033' ||
2958 star_match[1][0] != '\033') {
2959 player = star_match[0];
2961 player = star_match[2];
2963 sprintf(str, "%sobserve %s\n",
2964 ics_prefix, StripHighlightAndTitle(player));
2967 /* Save ratings from notify string */
2968 strcpy(player1Name, star_match[0]);
2969 player1Rating = string_to_rating(star_match[1]);
2970 strcpy(player2Name, star_match[2]);
2971 player2Rating = string_to_rating(star_match[3]);
2973 if (appData.debugMode)
2975 "Ratings from 'Game notification:' %s %d, %s %d\n",
2976 player1Name, player1Rating,
2977 player2Name, player2Rating);
2982 /* Deal with automatic examine mode after a game,
2983 and with IcsObserving -> IcsExamining transition */
2984 if (looking_at(buf, &i, "Entering examine mode for game *") ||
2985 looking_at(buf, &i, "has made you an examiner of game *")) {
2987 int gamenum = atoi(star_match[0]);
2988 if ((gameMode == IcsIdle || gameMode == IcsObserving) &&
2989 gamenum == ics_gamenum) {
2990 /* We were already playing or observing this game;
2991 no need to refetch history */
2992 gameMode = IcsExamining;
2994 pauseExamForwardMostMove = forwardMostMove;
2995 } else if (currentMove < forwardMostMove) {
2996 ForwardInner(forwardMostMove);
2999 /* I don't think this case really can happen */
3000 SendToICS(ics_prefix);
3001 SendToICS("refresh\n");
3006 /* Error messages */
3007 // if (ics_user_moved) {
3008 if (1) { // [HGM] old way ignored error after move type in; ics_user_moved is not set then!
3009 if (looking_at(buf, &i, "Illegal move") ||
3010 looking_at(buf, &i, "Not a legal move") ||
3011 looking_at(buf, &i, "Your king is in check") ||
3012 looking_at(buf, &i, "It isn't your turn") ||
3013 looking_at(buf, &i, "It is not your move")) {
3015 if (ics_user_moved && forwardMostMove > backwardMostMove) { // only backup if we already moved
3016 currentMove = --forwardMostMove;
3017 DisplayMove(currentMove - 1); /* before DMError */
3018 DrawPosition(FALSE, boards[currentMove]);
3020 DisplayBothClocks();
3022 DisplayMoveError(_("Illegal move (rejected by ICS)")); // [HGM] but always relay error msg
3028 if (looking_at(buf, &i, "still have time") ||
3029 looking_at(buf, &i, "not out of time") ||
3030 looking_at(buf, &i, "either player is out of time") ||
3031 looking_at(buf, &i, "has timeseal; checking")) {
3032 /* We must have called his flag a little too soon */
3033 whiteFlag = blackFlag = FALSE;
3037 if (looking_at(buf, &i, "added * seconds to") ||
3038 looking_at(buf, &i, "seconds were added to")) {
3039 /* Update the clocks */
3040 SendToICS(ics_prefix);
3041 SendToICS("refresh\n");
3045 if (!ics_clock_paused && looking_at(buf, &i, "clock paused")) {
3046 ics_clock_paused = TRUE;
3051 if (ics_clock_paused && looking_at(buf, &i, "clock resumed")) {
3052 ics_clock_paused = FALSE;
3057 /* Grab player ratings from the Creating: message.
3058 Note we have to check for the special case when
3059 the ICS inserts things like [white] or [black]. */
3060 if (looking_at(buf, &i, "Creating: * (*)* * (*)") ||
3061 looking_at(buf, &i, "Creating: * (*) [*] * (*)")) {
3063 0 player 1 name (not necessarily white)
3065 2 empty, white, or black (IGNORED)
3066 3 player 2 name (not necessarily black)
3069 The names/ratings are sorted out when the game
3070 actually starts (below).
3072 strcpy(player1Name, StripHighlightAndTitle(star_match[0]));
3073 player1Rating = string_to_rating(star_match[1]);
3074 strcpy(player2Name, StripHighlightAndTitle(star_match[3]));
3075 player2Rating = string_to_rating(star_match[4]);
3077 if (appData.debugMode)
3079 "Ratings from 'Creating:' %s %d, %s %d\n",
3080 player1Name, player1Rating,
3081 player2Name, player2Rating);
3086 /* Improved generic start/end-of-game messages */
3087 if ((tkind=0, looking_at(buf, &i, "{Game * (* vs. *) *}*")) ||
3088 (tkind=1, looking_at(buf, &i, "{Game * (*(*) vs. *(*)) *}*"))){
3089 /* If tkind == 0: */
3090 /* star_match[0] is the game number */
3091 /* [1] is the white player's name */
3092 /* [2] is the black player's name */
3093 /* For end-of-game: */
3094 /* [3] is the reason for the game end */
3095 /* [4] is a PGN end game-token, preceded by " " */
3096 /* For start-of-game: */
3097 /* [3] begins with "Creating" or "Continuing" */
3098 /* [4] is " *" or empty (don't care). */
3099 int gamenum = atoi(star_match[0]);
3100 char *whitename, *blackname, *why, *endtoken;
3101 ChessMove endtype = (ChessMove) 0;
3104 whitename = star_match[1];
3105 blackname = star_match[2];
3106 why = star_match[3];
3107 endtoken = star_match[4];
3109 whitename = star_match[1];
3110 blackname = star_match[3];
3111 why = star_match[5];
3112 endtoken = star_match[6];
3115 /* Game start messages */
3116 if (strncmp(why, "Creating ", 9) == 0 ||
3117 strncmp(why, "Continuing ", 11) == 0) {
3118 gs_gamenum = gamenum;
3119 strcpy(gs_kind, strchr(why, ' ') + 1);
3121 if (appData.zippyPlay) {
3122 ZippyGameStart(whitename, blackname);
3128 /* Game end messages */
3129 if (gameMode == IcsIdle || gameMode == BeginningOfGame ||
3130 ics_gamenum != gamenum) {
3133 while (endtoken[0] == ' ') endtoken++;
3134 switch (endtoken[0]) {
3137 endtype = GameUnfinished;
3140 endtype = BlackWins;
3143 if (endtoken[1] == '/')
3144 endtype = GameIsDrawn;
3146 endtype = WhiteWins;
3149 GameEnds(endtype, why, GE_ICS);
3151 if (appData.zippyPlay && first.initDone) {
3152 ZippyGameEnd(endtype, why);
3153 if (first.pr == NULL) {
3154 /* Start the next process early so that we'll
3155 be ready for the next challenge */
3156 StartChessProgram(&first);
3158 /* Send "new" early, in case this command takes
3159 a long time to finish, so that we'll be ready
3160 for the next challenge. */
3161 gameInfo.variant = VariantNormal; // [HGM] variantswitch: suppress sending of 'variant'
3168 if (looking_at(buf, &i, "Removing game * from observation") ||
3169 looking_at(buf, &i, "no longer observing game *") ||
3170 looking_at(buf, &i, "Game * (*) has no examiners")) {
3171 if (gameMode == IcsObserving &&
3172 atoi(star_match[0]) == ics_gamenum)
3174 /* icsEngineAnalyze */
3175 if (appData.icsEngineAnalyze) {
3182 ics_user_moved = FALSE;
3187 if (looking_at(buf, &i, "no longer examining game *")) {
3188 if (gameMode == IcsExamining &&
3189 atoi(star_match[0]) == ics_gamenum)
3193 ics_user_moved = FALSE;
3198 /* Advance leftover_start past any newlines we find,
3199 so only partial lines can get reparsed */
3200 if (looking_at(buf, &i, "\n")) {
3201 prevColor = curColor;
3202 if (curColor != ColorNormal) {
3203 if (oldi > next_out) {
3204 SendToPlayer(&buf[next_out], oldi - next_out);
3207 Colorize(ColorNormal, FALSE);
3208 curColor = ColorNormal;
3210 if (started == STARTED_BOARD) {
3211 started = STARTED_NONE;
3212 parse[parse_pos] = NULLCHAR;
3213 ParseBoard12(parse);
3216 /* Send premove here */
3217 if (appData.premove) {
3219 if (currentMove == 0 &&
3220 gameMode == IcsPlayingWhite &&
3221 appData.premoveWhite) {
3222 sprintf(str, "%s%s\n", ics_prefix,
3223 appData.premoveWhiteText);
3224 if (appData.debugMode)
3225 fprintf(debugFP, "Sending premove:\n");
3227 } else if (currentMove == 1 &&
3228 gameMode == IcsPlayingBlack &&
3229 appData.premoveBlack) {
3230 sprintf(str, "%s%s\n", ics_prefix,
3231 appData.premoveBlackText);
3232 if (appData.debugMode)
3233 fprintf(debugFP, "Sending premove:\n");
3235 } else if (gotPremove) {
3237 ClearPremoveHighlights();
3238 if (appData.debugMode)
3239 fprintf(debugFP, "Sending premove:\n");
3240 UserMoveEvent(premoveFromX, premoveFromY,
3241 premoveToX, premoveToY,
3246 /* Usually suppress following prompt */
3247 if (!(forwardMostMove == 0 && gameMode == IcsExamining)) {
3248 if (looking_at(buf, &i, "*% ")) {
3249 savingComment = FALSE;
3253 } else if (started == STARTED_HOLDINGS) {
3255 char new_piece[MSG_SIZ];
3256 started = STARTED_NONE;
3257 parse[parse_pos] = NULLCHAR;
3258 if (appData.debugMode)
3259 fprintf(debugFP, "Parsing holdings: %s, currentMove = %d\n",
3260 parse, currentMove);
3261 if (sscanf(parse, " game %d", &gamenum) == 1 &&
3262 gamenum == ics_gamenum) {
3263 if (gameInfo.variant == VariantNormal) {
3264 /* [HGM] We seem to switch variant during a game!
3265 * Presumably no holdings were displayed, so we have
3266 * to move the position two files to the right to
3267 * create room for them!
3269 VariantSwitch(boards[currentMove], VariantCrazyhouse); /* temp guess */
3270 /* Get a move list just to see the header, which
3271 will tell us whether this is really bug or zh */
3272 if (ics_getting_history == H_FALSE) {
3273 ics_getting_history = H_REQUESTED;
3274 sprintf(str, "%smoves %d\n", ics_prefix, gamenum);
3278 new_piece[0] = NULLCHAR;
3279 sscanf(parse, "game %d white [%s black [%s <- %s",
3280 &gamenum, white_holding, black_holding,
3282 white_holding[strlen(white_holding)-1] = NULLCHAR;
3283 black_holding[strlen(black_holding)-1] = NULLCHAR;
3284 /* [HGM] copy holdings to board holdings area */
3285 CopyHoldings(boards[currentMove], white_holding, WhitePawn);
3286 CopyHoldings(boards[currentMove], black_holding, BlackPawn);
3288 if (appData.zippyPlay && first.initDone) {
3289 ZippyHoldings(white_holding, black_holding,
3293 if (tinyLayout || smallLayout) {
3294 char wh[16], bh[16];
3295 PackHolding(wh, white_holding);
3296 PackHolding(bh, black_holding);
3297 sprintf(str, "[%s-%s] %s-%s", wh, bh,
3298 gameInfo.white, gameInfo.black);
3300 sprintf(str, "%s [%s] vs. %s [%s]",
3301 gameInfo.white, white_holding,
3302 gameInfo.black, black_holding);
3305 DrawPosition(FALSE, boards[currentMove]);
3308 /* Suppress following prompt */