Beef up variant detection
[xboard.git] / backend.h
1 /*
2  * backend.h -- Interface exported by XBoard back end
3  *
4  * Copyright 1991 by Digital Equipment Corporation, Maynard,
5  * Massachusetts.
6  *
7  * Enhancements Copyright 1992-2001, 2002, 2003, 2004, 2005, 2006,
8  * 2007, 2008, 2009, 2010, 2011, 2012, 2013 Free Software Foundation, Inc.
9  *
10  * Enhancements Copyright 2005 Alessandro Scotti
11  *
12  * The following terms apply to Digital Equipment Corporation's copyright
13  * interest in XBoard:
14  * ------------------------------------------------------------------------
15  * All Rights Reserved
16  *
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.
24  *
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
31  * SOFTWARE.
32  * ------------------------------------------------------------------------
33  *
34  * The following terms apply to the enhanced version of XBoard
35  * distributed by the Free Software Foundation:
36  * ------------------------------------------------------------------------
37  *
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.
42  *
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.
47  *
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/.  *
50  *
51  *------------------------------------------------------------------------
52  ** See the file ChangeLog for a revision history.  */
53
54 #ifndef XB_BACKEND
55 #define XB_BACKEND
56
57 /* unsigned int 64 for engine nodes work and display */
58 #ifdef WIN32
59        /* I don't know the name for this type of other compiler
60         * If it not work, just modify here
61         * This is for MS Visual Studio
62         */
63        #ifdef _MSC_VER
64                #define u64 unsigned __int64
65                #define s64 signed __int64
66                #define u64Display "%I64u"
67                #define s64Display "%I64d"
68                #define u64Const(c) (c ## UI64)
69                #define s64Const(c) (c ## I64)
70        #else
71                /* place holder
72                 * or dummy types for other compiler
73                 * [HGM] seems that -mno-cygwin comple needs %I64?
74                 */
75                #define u64 unsigned long long
76                #define s64 signed long long
77                #ifdef USE_I64
78                   #define u64Display "%I64u"
79                   #define s64Display "%I64d"
80                #else
81                   #define u64Display "%llu"
82                   #define s64Display "%lld"
83                #endif
84                #define u64Const(c) (c ## ULL)
85                #define s64Const(c) (c ## LL)
86        #endif
87 #else
88        /* GNU gcc */
89        #define u64 unsigned long long
90        #define s64 signed long long
91        #define u64Display "%llu"
92        #define s64Display "%lld"
93        #define u64Const(c) (c ## ull)
94        #define s64Const(c) (c ## ll)
95 #endif
96
97 #include "lists.h"
98
99 typedef int (*FileProc) P((FILE *f, int n, char *title));
100
101 extern char *wbOptions;
102 extern int gotPremove;
103 extern GameMode gameMode;
104 extern int matchMode;
105 extern int matchGame;
106 extern int pausing, cmailMsgLoaded, flipView, mute;
107 extern char white_holding[], black_holding[];
108 extern int currentMove, backwardMostMove, forwardMostMove;
109 extern int blackPlaysFirst;
110 extern FILE *debugFP;
111 extern char* programVersion;
112 extern Board boards[];
113 extern char marker[BOARD_RANKS][BOARD_FILES];
114 extern char lastMsg[MSG_SIZ];
115 extern Boolean bookUp;
116 extern int tinyLayout, smallLayout;
117 extern Boolean mcMode;
118 extern int dragging;
119 extern char variantError[];
120
121 void MarkMenuItem P((char *menuRef, int state));
122 char *CmailMsg P((void));
123 /* Tord: Added the useFEN960 parameter in PositionToFEN() below */
124 char *PositionToFEN P((int move, char* useFEN960, int moveCounts));
125 void AlphaRank P((char *s, int n)); /* [HGM] Shogi move preprocessor */
126 void EditPositionPasteFEN P((char *fen));
127 void TimeDelay P((long ms));
128 void SendMultiLineToICS P(( char *text ));
129 void AnalysisPeriodicEvent P((int force));
130 void SetWhiteToPlayEvent P((void));
131 void SetBlackToPlayEvent P((void));
132 void UploadGameEvent P((void));
133 void InitBackEnd1 P((void));
134 void InitBackEnd2 P((void));
135 int HasPromotionChoice P((int fromX, int fromY, int toX, int toY, char *choice, int sweep));
136 int InPalace P((int row, int column));
137 int PieceForSquare P((int x, int y));
138 int OKToStartUserMove P((int x, int y));
139 void Reset P((int redraw, int init));
140 void ResetGameEvent P((void));
141 Boolean HasPattern P(( const char * text, const char * pattern ));
142 Boolean SearchPattern P(( const char * text, const char * pattern ));
143 int LoadGame P((FILE *f, int n, char *title, int useList));
144 int LoadGameFromFile P((char *filename, int n, char *title, int useList));
145 int CmailLoadGame P((FILE *f, int n, char *title, int useList));
146 int ReloadGame P((int offset));
147 int SaveGame P((FILE *f, int dummy, char *dummy2));
148 int SaveGameToFile P((char *filename, int append));
149 int LoadPosition P((FILE *f, int n, char *title));
150 int ReloadPosition P((int offset));
151 int SavePosition P((FILE *f, int dummy, char *dummy2));
152 int DrawSeekGraph P(());
153 int SeekGraphClick P((ClickType click, int x, int y, int moving));
154 void EditPositionEvent P((void));
155 void FlipViewEvent P((void));
156 void MachineWhiteEvent P((void));
157 void MachineBlackEvent P((void));
158 void TwoMachinesEvent P((void));
159 void EditGameEvent P((void));
160 void TrainingEvent P((void));
161 void IcsClientEvent P((void));
162 void ForwardEvent P((void));
163 void BackwardEvent P((void));
164 void ToEndEvent P((void));
165 void ToStartEvent P((void));
166 void ToNrEvent P((int to));
167 void RevertEvent P((Boolean annotate));
168 void RetractMoveEvent P((void));
169 void MoveNowEvent P((void));
170 void TruncateGameEvent P((void));
171 void PauseEvent P((void));
172 void CallFlagEvent P((void));
173 void ClockClick P((int which));
174 void AcceptEvent P((void));
175 void DeclineEvent P((void));
176 void RematchEvent P((void));
177 void DrawEvent P((void));
178 void AbortEvent P((void));
179 void AdjournEvent P((void));
180 void ResignEvent P((void));
181 void UserAdjudicationEvent P((int result));
182 void StopObservingEvent P((void));
183 void StopExaminingEvent P((void));
184 void PonderNextMoveEvent P((int newState));
185 void ShowThinkingEvent P(());
186 void PeriodicUpdatesEvent P((int newState));
187 void HintEvent P((void));
188 void BookEvent P((void));
189 void AboutGameEvent P((void));
190 void ExitEvent P((int status));
191 char *DefaultFileName P((char *));
192 ChessMove UserMoveTest P((int fromX, int fromY, int toX, int toY, int promoChar, Boolean captureOwn));
193 void UserMoveEvent P((int fromX, int fromY, int toX, int toY, int promoChar));
194 void DecrementClocks P((void));
195 char *TimeString P((long millisec));
196 void AutoPlayGameLoop P((void));
197 void AdjustClock P((Boolean which, int dir));
198 void DisplayBothClocks P((void));
199 void EditPositionMenuEvent P((ChessSquare selection, int x, int y));
200 void DropMenuEvent P((ChessSquare selection, int x, int y));
201 int ParseTimeControl P((char *tc, float ti, int mps));
202 void EscapeExpand(char *p, char *q);
203 void ProcessICSInitScript P((FILE * f));
204 void EditCommentEvent P((void));
205 void ReplaceComment P((int index, char *text));
206 int ReplaceTags P((char *tags, GameInfo *gi));/* returns nonzero on error */
207 void AppendComment P((int index, char *text, Boolean addBraces));
208 void LoadVariation P((int index, char *text));
209 void ReloadCmailMsgEvent P((int unregister));
210 void MailMoveEvent P((void));
211 void EditTagsEvent P((void));
212 void GetMoveListEvent P((void));
213 void ExitAnalyzeMode P((void));
214 int  AnalyzeModeEvent P((void));
215 void AnalyzeFileEvent P((void));
216 void MatchEvent P((int mode));
217 void RecentEngineEvent P((int nr));
218 void TypeInEvent P((char first));
219 void TypeInDoneEvent P((char *move));
220 void InitPosition P((int redraw));
221 void NewSettingEvent P((int option, int *feature, char *command, int value));
222 void SettingsMenuIfReady P((void));
223 void DoEcho P((void));
224 void DontEcho P((void));
225 void TidyProgramName P((char *prog, char *host, char *buf));
226 void SetGameInfo P((void));
227 void AskQuestionEvent P((char *title, char *question,
228                          char *replyPrefix, char *which));
229 Boolean ParseOneMove P((char *move, int moveNum,
230                         ChessMove *moveType, int *fromX, int *fromY,
231                         int *toX, int *toY, char *promoChar));
232 char *VariantName P((VariantClass v));
233 VariantClass StringToVariant P((char *e));
234 double u64ToDouble P((u64 value));
235 void OutputChatMessage P((int partner, char *mess));
236 void EditPositionDone P((Boolean fakeRights));
237 Boolean GetArgValue P((char *name));
238 Boolean LoadPV P((int x, int y));
239 Boolean LoadMultiPV P((int x, int y, char *buf, int index, int *start, int *end, int pane));
240 void UnLoadPV P(());
241 void MovePV P((int x, int y, int h));
242 int PromoScroll P((int x, int y));
243 void EditBookEvent P((void));
244 Boolean DisplayBook P((int moveNr));
245 void SaveToBook P((char *text));
246 void HoverEvent P((int hiX, int hiY, int x, int y));
247 int PackGame P((Board board));
248 Boolean ParseFEN P((Board board, int *blackPlaysFirst, char *fen, Boolean autoSize));
249 void ApplyMove P((int fromX, int fromY, int toX, int toY, int promoChar, Board board));
250 void PackMove P((int fromX, int fromY, int toX, int toY, ChessSquare promoPiece));
251 void ics_printf P((char *format, ...));
252 int GetEngineLine P((char *nick, int engine));
253 void AddGameToBook P((int always));
254 void FlushBook P((void));
255
256 char *StrStr P((char *string, char *match));
257 char *StrCaseStr P((char *string, char *match));
258 char *StrSave P((char *s));
259 char *StrSavePtr P((char *s, char **savePtr));
260 char *SavePart P((char *));
261 char* safeStrCpy P(( char *dst, const char *src, size_t count ));
262
263 #ifndef _amigados
264 int StrCaseCmp P((char *s1, char *s2));
265 int ToLower P((int c));
266 int ToUpper P((int c));
267 #else
268 #define StrCaseCmp Stricmp  /*  Use utility.library functions   */
269 #include <proto/utility.h>
270 #endif
271
272 extern GameInfo gameInfo;
273
274 /* ICS vars used with backend.c and zippy.c */
275 enum ICS_TYPE { ICS_GENERIC, ICS_ICC, ICS_FICS, ICS_CHESSNET /* not really supported */ };
276 enum ICS_TYPE ics_type;
277
278 /* pgntags.c prototypes
279  */
280 char *PGNTags P((GameInfo *));
281 void PrintPGNTags P((FILE *f, GameInfo *));
282 int ParsePGNTag P((char *, GameInfo *));
283 char *PGNResult P((ChessMove result));
284
285
286 /* gamelist.c prototypes
287  */
288 /* A game node in the double linked list of games.
289  */
290 typedef struct XB_ListGame {
291     ListNode node;
292     int number;
293     int position;
294     int moves;
295     unsigned long offset;   /*  Byte offset of game within file.     */
296     GameInfo gameInfo;      /*  Note that some entries may be NULL. */
297 } ListGame;
298
299 extern int doubleClick;
300 extern int storedGames;
301 extern int opponentKibitzes;
302 extern ChessSquare gatingPiece;
303 extern List gameList;
304 extern int lastLoadGameNumber;
305 void ClearGameInfo P((GameInfo *));
306 int GameListBuild P((FILE *));
307 void GameListInitGameInfo P((GameInfo *));
308 char *GameListLine P((int, GameInfo *));
309 char * GameListLineFull P(( int, GameInfo *));
310 void InitSearch P((void));
311 int GameContainsPosition P((FILE *f, ListGame *lg));
312 void GLT_TagsToList P(( char * tags ));
313 void GLT_ParseList P((void));
314 int NamesToList P((char *name, char **engines, char **mnemonics, char *group));
315 int CreateTourney P((char *name));
316 char *MakeName P((char *templ));
317 void SwapEngines P((int n));
318 void Substitute P((char *participants, int expunge));
319
320 extern char* StripHighlight P((char *));  /* returns static data */
321 extern char* StripHighlightAndTitle P((char *));  /* returns static data */
322 extern void ics_update_width P((int new_width));
323 extern Boolean set_cont_sequence P((char *new_seq));
324 extern int wrap P((char *dest, char *src, int count, int width, int *lp));
325 int Explode P((Board board, int fromX, int fromY, int toX, int toY));
326
327 typedef enum { CheckBox, ComboBox, TextBox, Button, Spin, ResetButton, SaveButton, ListBox, Graph, PopUp,
328                  FileName, PathName, Slider, Message, Fractional, Label, Icon,
329                  BoxBegin, BoxEnd, BarBegin, BarEnd, DropDown, Break, EndMark } Control;
330
331 typedef struct XB_OPT {   // [HGM] options: descriptor of UCI-style option
332     int value;          // current setting, starts as default
333     int min;            // Also used for flags
334     int max;
335     void *handle;       // for use by front end
336     void *target;       // for use by front end
337     char *textValue;    // points to beginning of text value in name field
338     char **choice;      // points to array of combo choices in cps->combo
339     Control type;
340     char *name;         // holds both option name and text value (in allocated memory)
341 } Option;
342
343 typedef struct XB_CPS {
344     char *which;
345     int maybeThinking;
346     ProcRef pr;
347     InputSourceRef isr;
348     char *twoMachinesColor; /* "white\n" or "black\n" */
349     char *program;
350     char *host;
351     char *dir;
352     struct XB_CPS *other;
353     char *initString;
354     char *computerString;
355     int sendTime; /* 0=don't, 1=do, 2=test */
356     int sendDrawOffers;
357     int useSigint;
358     int useSigterm;
359     int offeredDraw; /* countdown */
360     int reuse;
361     int useSetboard; /* 0=use "edit"; 1=use "setboard" */
362     int extendedEdit;/* 1=also set holdings with "edit" */
363     int useSAN;      /* 0=use coordinate notation; 1=use SAN */
364     int usePing;     /* 0=not OK to use ping; 1=OK */
365     int lastPing;
366     int lastPong;
367     int usePlayother;/* 0=not OK to use playother; 1=OK */
368     int useColors;   /* 0=avoid obsolete white/black commands; 1=use them */
369     int useUsermove; /* 0=just send move; 1=send "usermove move" */
370     int sendICS;     /* 0=don't use "ics" command; 1=do */
371     int sendName;    /* 0=don't use "name" command; 1=do */
372     int sdKludge;    /* 0=use "sd DEPTH" command; 1=use "depth\nDEPTH" */
373     int stKludge;    /* 0=use "st TIME" command; 1=use "level 1 TIME" */
374     int excludeMoves;/* 0=don't use "exclude" command; 1=do */
375     char *tidy;
376     int matchWins;
377     char *variants;
378     int analysisSupport;
379     int analyzing;
380     int protocolVersion;
381     int initDone;
382
383     /* Added by Tord: */
384     int useFEN960;   /* 0=use "KQkq" style FENs, 1=use "HAha" style FENs */
385     int useOOCastle; /* 0="O-O" notation for castling, 1="king capture rook" notation */
386     /* End of additions by Tord */
387
388     int scoreIsAbsolute; /* [AS] 0=don't know (standard), 1=score is always from white side */
389     int isUCI;           /* [AS] 0=no (Winboard), 1=UCI (requires Polyglot) */
390     int hasOwnBookUCI;   /* [AS] 0=use GUI or Polyglot book, 1=has own book */
391
392     /* [HGM] time odds */
393     float timeOdds; /* factor through which we divide time for this engine  */
394     int debug;      /* [HGM] ignore engine debug lines starting with '#'    */
395     int maxNrOfSessions; /* [HGM] secondary TC: max args in 'level' command */
396     int accumulateTC; /* [HGM] secondary TC: how to handle extra sessions   */
397     int nps;          /* [HGM] nps: factor for node count to replace time   */
398     int supportsNPS;
399     int alphaRank;    /* [HGM] shogi: engine uses shogi-type coordinates    */
400     int maxCores;     /* [HGM] SMP: engine understands cores command        */
401     int memSize;      /* [HGM] memsize: engine understands memory command   */
402     char *egtFormats; /* [HGM] EGT: supported tablebase formats             */
403     int bookSuspend;  /* [HGM] book: go was deferred because of book hit    */
404     int pause;        /* [HGM] pause: 1=supports it, 2=actually paused      */
405     int highlight;    /* [HGM] engine wants to get lift and put commands    */
406     int nrOptions;    /* [HGM] options: remembered option="..." features    */
407 #define MAX_OPTIONS 200
408     Option option[MAX_OPTIONS];
409     int comboCnt;
410     char *comboList[20*MAX_OPTIONS];
411     char *optionSettings;
412     void *programLogo; /* [HGM] logo: bitmap of the logo                    */
413     char *fenOverride; /* [HGM} FRC: force FEN casling & ep fields by hand  */
414     char userError;    /* [HGM] crash: flag to suppress fatal-error messages*/
415     char reload;       /* [HGM] options: flag to resend options with xreuse */
416 } ChessProgramState;
417
418 extern ChessProgramState first, second;
419
420 /* Search stats from chessprogram */
421 typedef struct {
422   char movelist[2*MSG_SIZ]; /* Last PV we were sent */
423   int depth;              /* Current search depth */
424   int nr_moves;           /* Total nr of root moves */
425   int moves_left;         /* Moves remaining to be searched */
426   char move_name[MOVE_LEN];  /* Current move being searched, if provided */
427   u64 nodes;    /* # of nodes searched */
428   int time;               /* Search time (centiseconds) */
429   int score;              /* Score (centipawns) */
430   int got_only_move;      /* If last msg was "(only move)" */
431   int got_fail;           /* 0 - nothing, 1 - got "--", 2 - got "++" */
432   int ok_to_send;         /* handshaking between send & recv */
433   int line_is_book;       /* 1 if movelist is book moves */
434   int seen_stat;          /* 1 if we've seen the stat01: line */
435 } ChessProgramStats;
436
437 extern ChessProgramStats_Move pvInfoList[MAX_MOVES];
438 extern Boolean shuffleOpenings;
439 extern ChessProgramStats programStats;
440 extern int opponentKibitzes; // used by wengineo.c
441 extern int errorExitStatus;
442 extern char *recentEngines;
443 extern char *comboLine;
444 extern Boolean partnerUp, twoBoards;
445 extern char engineVariant[];
446 char *EngineDefinedVariant P((ChessProgramState *cps, int n));
447 void SettingsPopUp P((ChessProgramState *cps)); // [HGM] really in front-end, but CPS not known in frontend.h
448 int WaitForEngine P((ChessProgramState *cps, DelayedEventCallback x));
449 void Load P((ChessProgramState *cps, int n));
450 int MultiPV P((ChessProgramState *cps));
451 void MoveHistorySet P(( char movelist[][2*MOVE_LEN], int first, int last, int current, ChessProgramStats_Move * pvInfo ));
452 void MakeEngineOutputTitle P((void));
453 void LoadTheme P((void));
454 void CreateBookEvent P((void));
455 char *SupportedVariant P((char *list, VariantClass v, int w, int h, int s, int proto, char *engine));
456
457 /* A point in time */
458 typedef struct {
459     long sec;  /* Assuming this is >= 32 bits */
460     int ms;    /* Assuming this is >= 16 bits */
461 } TimeMark;
462
463 void GetTimeMark P((TimeMark *));
464 long SubtractTimeMarks P((TimeMark *, TimeMark *));
465
466 #endif /* XB_BACKEND */