Debug position search cache
[xboard.git] / gamelist.c
1 /*
2  * gamelist.c -- Functions to manage a gamelist
3  *
4  * Copyright 1995, 2009, 2010, 2011 Free Software Foundation, Inc.
5  *
6  * Enhancements Copyright 2005 Alessandro Scotti
7  *
8  * ------------------------------------------------------------------------
9  *
10  * GNU XBoard is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation, either version 3 of the License, or (at
13  * your option) any later version.
14  *
15  * GNU XBoard is distributed in the hope that it will be useful, but
16  * WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18  * General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program. If not, see http://www.gnu.org/licenses/.
22  *
23  *------------------------------------------------------------------------
24  ** See the file ChangeLog for a revision history.  */
25
26 #include "config.h"
27
28 #include <stdio.h>
29 #include <errno.h>
30 #if STDC_HEADERS
31 # include <stdlib.h>
32 # include <string.h>
33 #else /* not STDC_HEADERS */
34 # if HAVE_STRING_H
35 #  include <string.h>
36 # else /* not HAVE_STRING_H */
37 #  include <strings.h>
38 # endif /* not HAVE_STRING_H */
39 #endif /* not STDC_HEADERS */
40
41 #include "common.h"
42 #include "frontend.h"
43 #include "backend.h"
44 #include "parser.h"
45
46
47 /* Variables
48  */
49 List gameList;
50 extern Board initialPosition;
51 extern int quickFlag;
52 extern int movePtr;
53
54 /* Local function prototypes
55  */
56 static void GameListDeleteGame P((ListGame *));
57 static ListGame *GameListCreate P((void));
58 static void GameListFree P((List *));
59 static int GameListNewGame P((ListGame **));
60
61 /* [AS] Wildcard pattern matching */
62 Boolean
63 HasPattern( const char * text, const char * pattern )
64 {
65     while( *pattern != '\0' ) {
66         if( *pattern == '*' ) {
67             while( *pattern == '*' ) {
68                 pattern++;
69             }
70
71             if( *pattern == '\0' ) {
72                 return TRUE;
73             }
74
75             while( *text != '\0' ) {
76                 if( HasPattern( text, pattern ) ) {
77                     return TRUE;
78                 }
79                 text++;
80             }
81         }
82         else if( (*pattern == *text) || ((*pattern == '?') && (*text != '\0')) ) {
83             pattern++;
84             text++;
85             continue;
86         }
87
88         return FALSE;
89     }
90
91     return TRUE;
92 }
93
94 Boolean
95 SearchPattern( const char * text, const char * pattern )
96 {
97     Boolean result = TRUE;
98
99     if( pattern != NULL && *pattern != '\0' ) {
100         if( *pattern == '*' ) {
101             result = HasPattern( text, pattern );
102         }
103         else {
104             result = FALSE;
105
106             while( *text != '\0' ) {
107                 if( HasPattern( text, pattern ) ) {
108                     result = TRUE;
109                     break;
110                 }
111                 text++;
112             }
113         }
114     }
115
116     return result;
117 }
118
119 /* Delete a ListGame; implies removint it from a list.
120  */
121 static void GameListDeleteGame(listGame)
122     ListGame *listGame;
123 {
124     if (listGame) {
125         if (listGame->gameInfo.event) free(listGame->gameInfo.event);
126         if (listGame->gameInfo.site) free(listGame->gameInfo.site);
127         if (listGame->gameInfo.date) free(listGame->gameInfo.date);
128         if (listGame->gameInfo.round) free(listGame->gameInfo.round);
129         if (listGame->gameInfo.white) free(listGame->gameInfo.white);
130         if (listGame->gameInfo.black) free(listGame->gameInfo.black);
131         if (listGame->gameInfo.fen) free(listGame->gameInfo.fen);
132         if (listGame->gameInfo.resultDetails) free(listGame->gameInfo.resultDetails);
133         if (listGame->gameInfo.timeControl) free(listGame->gameInfo.timeControl);
134         if (listGame->gameInfo.extraTags) free(listGame->gameInfo.extraTags);
135         if (listGame->gameInfo.outOfBook) free(listGame->gameInfo.outOfBook);
136         ListNodeFree((ListNode *) listGame);
137     }
138 }
139
140
141 /* Free the previous list of games.
142  */
143 static void GameListFree(gameList)
144     List *gameList;
145 {
146     while (!ListEmpty(gameList))
147     {
148         GameListDeleteGame((ListGame *) gameList->head);
149     }
150 }
151
152
153
154 /* Initialize a new GameInfo structure.
155  */
156 void GameListInitGameInfo(gameInfo)
157     GameInfo *gameInfo;
158 {
159     gameInfo->event = NULL;
160     gameInfo->site = NULL;
161     gameInfo->date = NULL;
162     gameInfo->round = NULL;
163     gameInfo->white = NULL;
164     gameInfo->black = NULL;
165     gameInfo->result = GameUnfinished;
166     gameInfo->fen = NULL;
167     gameInfo->resultDetails = NULL;
168     gameInfo->timeControl = NULL;
169     gameInfo->extraTags = NULL;
170     gameInfo->whiteRating = -1; /* unknown */
171     gameInfo->blackRating = -1; /* unknown */
172     gameInfo->variant = VariantNormal;
173     gameInfo->outOfBook = NULL;
174     gameInfo->resultDetails = NULL;
175 }
176
177
178 /* Create empty ListGame; returns ListGame or NULL, if out of memory.
179  *
180  * Note, that the ListGame is *not* added to any list
181  */
182 static ListGame *GameListCreate()
183
184 {
185     ListGame *listGame;
186
187     if ((listGame = (ListGame *) ListNodeCreate(sizeof(*listGame)))) {
188         GameListInitGameInfo(&listGame->gameInfo);
189     }
190     return(listGame);
191 }
192
193
194 /* Creates a new game for the gamelist.
195  */
196 static int GameListNewGame(listGamePtr)
197      ListGame **listGamePtr;
198 {
199     if (!(*listGamePtr = (ListGame *) GameListCreate())) {
200         GameListFree(&gameList);
201         return(ENOMEM);
202     }
203     ListAddTail(&gameList, (ListNode *) *listGamePtr);
204     return(0);
205 }
206
207
208 /* Build the list of games in the open file f.
209  * Returns 0 for success or error number.
210  */
211 int GameListBuild(f)
212     FILE *f;
213 {
214     ChessMove cm, lastStart;
215     int gameNumber;
216     ListGame *currentListGame = NULL;
217     int error, scratch=100, plyNr=0, fromX, fromY, toX, toY;
218     int offset;
219     char lastComment[MSG_SIZ], buf[MSG_SIZ];
220 struct {
221     long sec;  /* Assuming this is >= 32 bits */
222     int ms;    /* Assuming this is >= 16 bits */
223 } t,t2; GetTimeMark(&t);
224     GameListFree(&gameList);
225     yynewfile(f);
226     gameNumber = 0;
227     movePtr = 0;
228
229     lastStart = (ChessMove) 0;
230     yyskipmoves = FALSE;
231     do {
232         yyboardindex = scratch;
233         offset = yyoffset();
234         quickFlag = plyNr + 1;
235         cm = (ChessMove) Myylex();
236         switch (cm) {
237           case GNUChessGame:
238             if ((error = GameListNewGame(&currentListGame))) {
239                 rewind(f);
240                 yyskipmoves = FALSE;
241                 return(error);
242             }
243             currentListGame->number = ++gameNumber;
244             currentListGame->offset = offset;
245             if(1) { CopyBoard(boards[scratch], initialPosition); plyNr = 0; currentListGame->moves = PackGame(boards[scratch]); }
246             if (currentListGame->gameInfo.event != NULL) {
247                 free(currentListGame->gameInfo.event);
248             }
249             currentListGame->gameInfo.event = StrSave(yy_text);
250             lastStart = cm;
251             break;
252           case XBoardGame:
253             lastStart = cm;
254             break;
255           case MoveNumberOne:
256             switch (lastStart) {
257               case GNUChessGame:
258                 break;          /*  ignore  */
259               case PGNTag:
260                 lastStart = cm;
261                 break;          /*  Already started */
262               case (ChessMove) 0:
263               case MoveNumberOne:
264               case XBoardGame:
265                 if ((error = GameListNewGame(&currentListGame))) {
266                     rewind(f);
267                     yyskipmoves = FALSE;
268                     return(error);
269                 }
270                 currentListGame->number = ++gameNumber;
271                 currentListGame->offset = offset;
272                 if(1) { CopyBoard(boards[scratch], initialPosition); plyNr = 0; currentListGame->moves = PackGame(boards[scratch]); }
273                 lastStart = cm;
274                 break;
275               default:
276                 break;          /*  impossible  */
277             }
278             break;
279           case PGNTag:
280             lastStart = cm;
281             if ((error = GameListNewGame(&currentListGame))) {
282                 rewind(f);
283                 yyskipmoves = FALSE;
284                 return(error);
285             }
286             currentListGame->number = ++gameNumber;
287             currentListGame->offset = offset;
288             ParsePGNTag(yy_text, &currentListGame->gameInfo);
289             do {
290                 yyboardindex = 1;
291                 offset = yyoffset();
292                 cm = (ChessMove) Myylex();
293                 if (cm == PGNTag) {
294                     ParsePGNTag(yy_text, &currentListGame->gameInfo);
295                 }
296             } while (cm == PGNTag || cm == Comment);
297             if(1) {
298                 int btm=0;
299                 if(currentListGame->gameInfo.fen) ParseFEN(boards[scratch], &btm, currentListGame->gameInfo.fen);
300                 else CopyBoard(boards[scratch], initialPosition);
301                 plyNr = (btm != 0);
302                 currentListGame->moves = PackGame(boards[scratch]);
303             }
304             if(cm != NormalMove) break;
305           case IllegalMove:
306                 if(appData.testLegality) break;
307           case NormalMove:
308             /* Allow the first game to start with an unnumbered move */
309             yyskipmoves = FALSE;
310             if (lastStart == (ChessMove) 0) {
311               if ((error = GameListNewGame(&currentListGame))) {
312                 rewind(f);
313                 yyskipmoves = FALSE;
314                 return(error);
315               }
316               currentListGame->number = ++gameNumber;
317               currentListGame->offset = offset;
318               if(1) { CopyBoard(boards[scratch], initialPosition); plyNr = 0; currentListGame->moves = PackGame(boards[scratch]); }
319               lastStart = MoveNumberOne;
320             }
321           case WhiteCapturesEnPassant:
322           case BlackCapturesEnPassant:
323           case WhitePromotion:
324           case BlackPromotion:
325           case WhiteNonPromotion:
326           case BlackNonPromotion:
327           case WhiteKingSideCastle:
328           case WhiteQueenSideCastle:
329           case BlackKingSideCastle:
330           case BlackQueenSideCastle:
331           case WhiteKingSideCastleWild:
332           case WhiteQueenSideCastleWild:
333           case BlackKingSideCastleWild:
334           case BlackQueenSideCastleWild:
335           case WhiteHSideCastleFR:
336           case WhiteASideCastleFR:
337           case BlackHSideCastleFR:
338           case BlackASideCastleFR:
339                 fromX = currentMoveString[0] - AAA;
340                 fromY = currentMoveString[1] - ONE;
341                 toX = currentMoveString[2] - AAA;
342                 toY = currentMoveString[3] - ONE;
343                 plyNr++;
344                 ApplyMove(fromX, fromY, toX, toY, currentMoveString[4], boards[scratch]);
345                 if(currentListGame->moves) PackMove(fromX, fromY, toX, toY, boards[scratch][toY][toX]);
346             break;
347         case WhiteWins: // [HGM] rescom: save last comment as result details
348         case BlackWins:
349         case GameIsDrawn:
350         case GameUnfinished:
351             if(!currentListGame) break;
352             if (currentListGame->gameInfo.resultDetails != NULL) {
353                 free(currentListGame->gameInfo.resultDetails);
354             }
355             if(yy_text[0] == '{') { char *p;
356               safeStrCpy(lastComment, yy_text+1, sizeof(lastComment)/sizeof(lastComment[0]));
357               if(p = strchr(lastComment, '}')) *p = 0;
358               currentListGame->gameInfo.resultDetails = StrSave(lastComment);
359             }
360             break;
361           default:
362             break;
363         }
364         if(gameNumber % 1000 == 0) {
365             snprintf(buf, MSG_SIZ,"Reading game file (%d)", gameNumber);
366             DisplayTitle(buf);
367         }
368     }
369     while (cm != (ChessMove) 0);
370
371     if(!currentListGame->moves) DisplayError("Game cache overflowed\nPosition-searching might not work properly", 0);
372
373     if (appData.debugMode) {
374         for (currentListGame = (ListGame *) gameList.head;
375              currentListGame->node.succ;
376              currentListGame = (ListGame *) currentListGame->node.succ) {
377
378             fprintf(debugFP, "Parsed game number %d, offset %ld:\n",
379                     currentListGame->number, currentListGame->offset);
380             PrintPGNTags(debugFP, &currentListGame->gameInfo);
381         }
382     }
383 GetTimeMark(&t2);printf("GameListBuild %d msec\n", SubtractTimeMarks(&t2,&t));
384     quickFlag = 0;
385     PackGame(boards[scratch]); // for appending end-of-game marker.
386     DisplayTitle("WinBoard");
387     rewind(f);
388     yyskipmoves = FALSE;
389     return 0;
390 }
391
392
393 /* Clear an existing GameInfo structure.
394  */
395 void ClearGameInfo(gameInfo)
396     GameInfo *gameInfo;
397 {
398     if (gameInfo->event != NULL) {
399         free(gameInfo->event);
400     }
401     if (gameInfo->site != NULL) {
402         free(gameInfo->site);
403     }
404     if (gameInfo->date != NULL) {
405         free(gameInfo->date);
406     }
407     if (gameInfo->round != NULL) {
408         free(gameInfo->round);
409     }
410     if (gameInfo->white != NULL) {
411         free(gameInfo->white);
412     }
413     if (gameInfo->black != NULL) {
414         free(gameInfo->black);
415     }
416     if (gameInfo->resultDetails != NULL) {
417         free(gameInfo->resultDetails);
418     }
419     if (gameInfo->fen != NULL) {
420         free(gameInfo->fen);
421     }
422     if (gameInfo->timeControl != NULL) {
423         free(gameInfo->timeControl);
424     }
425     if (gameInfo->extraTags != NULL) {
426         free(gameInfo->extraTags);
427     }
428     if (gameInfo->outOfBook != NULL) {
429         free(gameInfo->outOfBook);
430     }
431     GameListInitGameInfo(gameInfo);
432 }
433
434 /* [AS] Replaced by "dynamic" tag selection below */
435 char *
436 GameListLineOld(number, gameInfo)
437      int number;
438      GameInfo *gameInfo;
439 {
440     char *event = (gameInfo->event && strcmp(gameInfo->event, "?") != 0) ?
441                      gameInfo->event : gameInfo->site ? gameInfo->site : "?";
442     char *white = gameInfo->white ? gameInfo->white : "?";
443     char *black = gameInfo->black ? gameInfo->black : "?";
444     char *date = gameInfo->date ? gameInfo->date : "?";
445     int len = 10 + strlen(event) + 2 + strlen(white) + 1 +
446       strlen(black) + 11 + strlen(date) + 1;
447     char *ret = (char *) malloc(len);
448     sprintf(ret, "%d. %s, %s-%s, %s, %s",
449             number, event, white, black, PGNResult(gameInfo->result), date);
450     return ret;
451 }
452
453 #define MAX_FIELD_LEN   80  /* To avoid overflowing the buffer */
454
455 char * GameListLine( int number, GameInfo * gameInfo )
456 {
457     char buffer[2*MSG_SIZ];
458     char * buf = buffer;
459     char * glt = appData.gameListTags;
460
461     buf += sprintf( buffer, "%d.", number );
462
463     while( *glt != '\0' ) {
464         *buf++ = ' ';
465
466         switch( *glt ) {
467         case GLT_EVENT:
468             strncpy( buf, gameInfo->event ? gameInfo->event : "?", MAX_FIELD_LEN );
469             break;
470         case GLT_SITE:
471             strncpy( buf, gameInfo->site ? gameInfo->site : "?", MAX_FIELD_LEN );
472             break;
473         case GLT_DATE:
474             strncpy( buf, gameInfo->date ? gameInfo->date : "?", MAX_FIELD_LEN );
475             break;
476         case GLT_ROUND:
477             strncpy( buf, gameInfo->round ? gameInfo->round : "?", MAX_FIELD_LEN );
478             break;
479         case GLT_PLAYERS:
480             strncpy( buf, gameInfo->white ? gameInfo->white : "?", MAX_FIELD_LEN );
481             buf[ MAX_FIELD_LEN-1 ] = '\0';
482             buf += strlen( buf );
483             *buf++ = '-';
484             strncpy( buf, gameInfo->black ? gameInfo->black : "?", MAX_FIELD_LEN );
485             break;
486         case GLT_RESULT:
487             safeStrCpy( buf, PGNResult(gameInfo->result), 2*MSG_SIZ );
488             break;
489         case GLT_WHITE_ELO:
490             if( gameInfo->whiteRating > 0 )
491               sprintf( buf,  "%d", gameInfo->whiteRating );
492             else
493               safeStrCpy( buf, "?" , 2*MSG_SIZ);
494             break;
495         case GLT_BLACK_ELO:
496             if( gameInfo->blackRating > 0 )
497                 sprintf( buf, "%d", gameInfo->blackRating );
498             else
499               safeStrCpy( buf, "?" , 2*MSG_SIZ);
500             break;
501         case GLT_TIME_CONTROL:
502             strncpy( buf, gameInfo->timeControl ? gameInfo->timeControl : "?", MAX_FIELD_LEN );
503             break;
504         case GLT_VARIANT:
505             break;
506         case GLT_OUT_OF_BOOK:
507             strncpy( buf, gameInfo->outOfBook ? gameInfo->outOfBook : "?", MAX_FIELD_LEN );
508             break;
509         case GLT_RESULT_COMMENT:
510             strncpy( buf, gameInfo->resultDetails ? gameInfo->resultDetails : "res?", MAX_FIELD_LEN );
511             break;
512         default:
513             break;
514         }
515
516         buf[MAX_FIELD_LEN-1] = '\0';
517
518         buf += strlen( buf );
519
520         glt++;
521
522         if( *glt != '\0' ) {
523             *buf++ = ',';
524         }
525     }
526
527     *buf = '\0';
528
529     return strdup( buffer );
530 }
531
532 char * GameListLineFull( int number, GameInfo * gameInfo )
533 {
534     char * event = gameInfo->event ? gameInfo->event : "?";
535     char * site = gameInfo->site ? gameInfo->site : "?";
536     char * white = gameInfo->white ? gameInfo->white : "?";
537     char * black = gameInfo->black ? gameInfo->black : "?";
538     char * round = gameInfo->round ? gameInfo->round : "?";
539     char * date = gameInfo->date ? gameInfo->date : "?";
540     char * oob = gameInfo->outOfBook ? gameInfo->outOfBook : "";
541     char * reason = gameInfo->resultDetails ? gameInfo->resultDetails : "";
542
543     int len = 64 + strlen(event) + strlen(site) + strlen(white) + strlen(black) + strlen(date) + strlen(oob) + strlen(reason);
544
545     char *ret = (char *) malloc(len);
546
547     sprintf(ret, "%d, \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\"",
548         number, event, site, round, white, black, PGNResult(gameInfo->result), reason, date, oob );
549
550     return ret;
551 }
552 // --------------------------------------- Game-List options dialog --------------------------------------
553
554 // back-end
555 typedef struct {
556     char id;
557     char * name;
558 } GLT_Item;
559
560 // back-end: translation table tag id-char <-> full tag name
561 static GLT_Item GLT_ItemInfo[] = {
562     { GLT_EVENT,      "Event" },
563     { GLT_SITE,       "Site" },
564     { GLT_DATE,       "Date" },
565     { GLT_ROUND,      "Round" },
566     { GLT_PLAYERS,    "Players" },
567     { GLT_RESULT,     "Result" },
568     { GLT_WHITE_ELO,  "White Rating" },
569     { GLT_BLACK_ELO,  "Black Rating" },
570     { GLT_TIME_CONTROL,"Time Control" },
571     { GLT_VARIANT,    "Variant" },
572     { GLT_OUT_OF_BOOK,PGN_OUT_OF_BOOK },
573     { GLT_RESULT_COMMENT, "Result Comment" }, // [HGM] rescom
574     { 0, 0 }
575 };
576
577 char lpUserGLT[LPUSERGLT_SIZE];
578
579 // back-end: convert the tag id-char to a full tag name
580 char * GLT_FindItem( char id )
581 {
582     char * result = 0;
583
584     GLT_Item * list = GLT_ItemInfo;
585
586     while( list->id != 0 ) {
587         if( list->id == id ) {
588             result = list->name;
589             break;
590         }
591
592         list++;
593     }
594
595     return result;
596 }
597
598 // back-end: build the list of tag names
599 void
600 GLT_TagsToList( char * tags )
601 {
602     char * pc = tags;
603
604     GLT_ClearList();
605
606     while( *pc ) {
607         GLT_AddToList( GLT_FindItem(*pc) );
608         pc++;
609     }
610
611     GLT_AddToList( "     --- Hidden tags ---     " );
612
613     pc = GLT_ALL_TAGS;
614
615     while( *pc ) {
616         if( strchr( tags, *pc ) == 0 ) {
617             GLT_AddToList( GLT_FindItem(*pc) );
618         }
619         pc++;
620     }
621
622     GLT_DeSelectList();
623 }
624
625 // back-end: retrieve item from dialog and translate to id-char
626 char
627 GLT_ListItemToTag( int index )
628 {
629     char result = '\0';
630     char name[MSG_SIZ];
631
632     GLT_Item * list = GLT_ItemInfo;
633
634     if( GLT_GetFromList(index, name) ) {
635         while( list->id != 0 ) {
636             if( strcmp( list->name, name ) == 0 ) {
637                 result = list->id;
638                 break;
639             }
640
641             list++;
642         }
643     }
644
645     return result;
646 }
647
648 // back-end: add items id-chars one-by-one to temp tags string
649 void
650 GLT_ParseList()
651 {
652     char * pc = lpUserGLT;
653     int idx = 0;
654     char id;
655
656     do {
657         id = GLT_ListItemToTag( idx );
658         *pc++ = id;
659         idx++;
660     } while( id != '\0' );
661 }
662