Fix crash on loading garbage game file
[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
51
52 /* Local function prototypes
53  */
54 static void GameListDeleteGame P((ListGame *));
55 static ListGame *GameListCreate P((void));
56 static void GameListFree P((List *));
57 static int GameListNewGame P((ListGame **));
58
59 /* [AS] Wildcard pattern matching */
60 Boolean
61 HasPattern( const char * text, const char * pattern )
62 {
63     while( *pattern != '\0' ) {
64         if( *pattern == '*' ) {
65             while( *pattern == '*' ) {
66                 pattern++;
67             }
68
69             if( *pattern == '\0' ) {
70                 return TRUE;
71             }
72
73             while( *text != '\0' ) {
74                 if( HasPattern( text, pattern ) ) {
75                     return TRUE;
76                 }
77                 text++;
78             }
79         }
80         else if( (*pattern == *text) || ((*pattern == '?') && (*text != '\0')) ) {
81             pattern++;
82             text++;
83             continue;
84         }
85
86         return FALSE;
87     }
88
89     return TRUE;
90 }
91
92 Boolean
93 SearchPattern( const char * text, const char * pattern )
94 {
95     Boolean result = TRUE;
96
97     if( pattern != NULL && *pattern != '\0' ) {
98         if( *pattern == '*' ) {
99             result = HasPattern( text, pattern );
100         }
101         else {
102             result = FALSE;
103
104             while( *text != '\0' ) {
105                 if( HasPattern( text, pattern ) ) {
106                     result = TRUE;
107                     break;
108                 }
109                 text++;
110             }
111         }
112     }
113
114     return result;
115 }
116
117 /* Delete a ListGame; implies removint it from a list.
118  */
119 static void GameListDeleteGame(listGame)
120     ListGame *listGame;
121 {
122     if (listGame) {
123         if (listGame->gameInfo.event) free(listGame->gameInfo.event);
124         if (listGame->gameInfo.site) free(listGame->gameInfo.site);
125         if (listGame->gameInfo.date) free(listGame->gameInfo.date);
126         if (listGame->gameInfo.round) free(listGame->gameInfo.round);
127         if (listGame->gameInfo.white) free(listGame->gameInfo.white);
128         if (listGame->gameInfo.black) free(listGame->gameInfo.black);
129         if (listGame->gameInfo.fen) free(listGame->gameInfo.fen);
130         if (listGame->gameInfo.resultDetails) free(listGame->gameInfo.resultDetails);
131         if (listGame->gameInfo.timeControl) free(listGame->gameInfo.timeControl);
132         if (listGame->gameInfo.extraTags) free(listGame->gameInfo.extraTags);
133         if (listGame->gameInfo.outOfBook) free(listGame->gameInfo.outOfBook);
134         ListNodeFree((ListNode *) listGame);
135     }
136 }
137
138
139 /* Free the previous list of games.
140  */
141 static void GameListFree(gameList)
142     List *gameList;
143 {
144     while (!ListEmpty(gameList))
145     {
146         GameListDeleteGame((ListGame *) gameList->head);
147     }
148 }
149
150
151
152 /* Initialize a new GameInfo structure.
153  */
154 void GameListInitGameInfo(gameInfo)
155     GameInfo *gameInfo;
156 {
157     gameInfo->event = NULL;
158     gameInfo->site = NULL;
159     gameInfo->date = NULL;
160     gameInfo->round = NULL;
161     gameInfo->white = NULL;
162     gameInfo->black = NULL;
163     gameInfo->result = GameUnfinished;
164     gameInfo->fen = NULL;
165     gameInfo->resultDetails = NULL;
166     gameInfo->timeControl = NULL;
167     gameInfo->extraTags = NULL;
168     gameInfo->whiteRating = -1; /* unknown */
169     gameInfo->blackRating = -1; /* unknown */
170     gameInfo->variant = VariantNormal;
171     gameInfo->outOfBook = NULL;
172     gameInfo->resultDetails = NULL;
173 }
174
175
176 /* Create empty ListGame; returns ListGame or NULL, if out of memory.
177  *
178  * Note, that the ListGame is *not* added to any list
179  */
180 static ListGame *GameListCreate()
181
182 {
183     ListGame *listGame;
184
185     if ((listGame = (ListGame *) ListNodeCreate(sizeof(*listGame)))) {
186         GameListInitGameInfo(&listGame->gameInfo);
187     }
188     return(listGame);
189 }
190
191
192 /* Creates a new game for the gamelist.
193  */
194 static int GameListNewGame(listGamePtr)
195      ListGame **listGamePtr;
196 {
197     if (!(*listGamePtr = (ListGame *) GameListCreate())) {
198         GameListFree(&gameList);
199         return(ENOMEM);
200     }
201     ListAddTail(&gameList, (ListNode *) *listGamePtr);
202     return(0);
203 }
204
205
206 /* Build the list of games in the open file f.
207  * Returns 0 for success or error number.
208  */
209 int GameListBuild(f)
210     FILE *f;
211 {
212     ChessMove cm, lastStart;
213     int gameNumber;
214     ListGame *currentListGame = NULL;
215     int error;
216     int offset;
217     char lastComment[MSG_SIZ], buf[MSG_SIZ];
218
219     GameListFree(&gameList);
220     yynewfile(f);
221     gameNumber = 0;
222
223     lastStart = (ChessMove) 0;
224     yyskipmoves = FALSE;
225     do {
226         yyboardindex = 0;
227         offset = yyoffset();
228         cm = (ChessMove) Myylex();
229         switch (cm) {
230           case GNUChessGame:
231             if ((error = GameListNewGame(&currentListGame))) {
232                 rewind(f);
233                 yyskipmoves = FALSE;
234                 return(error);
235             }
236             currentListGame->number = ++gameNumber;
237             currentListGame->offset = offset;
238             if (currentListGame->gameInfo.event != NULL) {
239                 free(currentListGame->gameInfo.event);
240             }
241             currentListGame->gameInfo.event = StrSave(yy_text);
242             lastStart = cm;
243             break;
244           case XBoardGame:
245             lastStart = cm;
246             break;
247           case MoveNumberOne:
248             switch (lastStart) {
249               case GNUChessGame:
250                 break;          /*  ignore  */
251               case PGNTag:
252                 lastStart = cm;
253                 break;          /*  Already started */
254               case (ChessMove) 0:
255               case MoveNumberOne:
256               case XBoardGame:
257                 if ((error = GameListNewGame(&currentListGame))) {
258                     rewind(f);
259                     yyskipmoves = FALSE;
260                     return(error);
261                 }
262                 currentListGame->number = ++gameNumber;
263                 currentListGame->offset = offset;
264                 lastStart = cm;
265                 break;
266               default:
267                 break;          /*  impossible  */
268             }
269             break;
270           case PGNTag:
271             lastStart = cm;
272             if ((error = GameListNewGame(&currentListGame))) {
273                 rewind(f);
274                 yyskipmoves = FALSE;
275                 return(error);
276             }
277             currentListGame->number = ++gameNumber;
278             currentListGame->offset = offset;
279             ParsePGNTag(yy_text, &currentListGame->gameInfo);
280             do {
281                 yyboardindex = 1;
282                 offset = yyoffset();
283                 cm = (ChessMove) Myylex();
284                 if (cm == PGNTag) {
285                     ParsePGNTag(yy_text, &currentListGame->gameInfo);
286                 }
287             } while (cm == PGNTag || cm == Comment);
288             break;
289           case NormalMove:
290             /* Allow the first game to start with an unnumbered move */
291             yyskipmoves = TRUE;
292             if (lastStart == (ChessMove) 0) {
293               if ((error = GameListNewGame(&currentListGame))) {
294                 rewind(f);
295                 yyskipmoves = FALSE;
296                 return(error);
297               }
298               currentListGame->number = ++gameNumber;
299               currentListGame->offset = offset;
300               lastStart = MoveNumberOne;
301             }
302             break;
303         case WhiteWins: // [HGM] rescom: save last comment as result details
304         case BlackWins:
305         case GameIsDrawn:
306         case GameUnfinished:
307             if(!currentListGame) break;
308             if (currentListGame->gameInfo.resultDetails != NULL) {
309                 free(currentListGame->gameInfo.resultDetails);
310             }
311             if(yy_text[0] == '{') { char *p;
312               safeStrCpy(lastComment, yy_text+1, sizeof(lastComment)/sizeof(lastComment[0]));
313               if(p = strchr(lastComment, '}')) *p = 0;
314               currentListGame->gameInfo.resultDetails = StrSave(lastComment);
315             }
316             break;
317           default:
318             break;
319         }
320         if(gameNumber % 1000 == 0) {
321             snprintf(buf, MSG_SIZ,"Reading game file (%d)", gameNumber);
322             DisplayTitle(buf);
323         }
324     }
325     while (cm != (ChessMove) 0);
326
327     if (appData.debugMode) {
328         for (currentListGame = (ListGame *) gameList.head;
329              currentListGame->node.succ;
330              currentListGame = (ListGame *) currentListGame->node.succ) {
331
332             fprintf(debugFP, "Parsed game number %d, offset %ld:\n",
333                     currentListGame->number, currentListGame->offset);
334             PrintPGNTags(debugFP, &currentListGame->gameInfo);
335         }
336     }
337
338     DisplayTitle("WinBoard");
339     rewind(f);
340     yyskipmoves = FALSE;
341     return 0;
342 }
343
344
345 /* Clear an existing GameInfo structure.
346  */
347 void ClearGameInfo(gameInfo)
348     GameInfo *gameInfo;
349 {
350     if (gameInfo->event != NULL) {
351         free(gameInfo->event);
352     }
353     if (gameInfo->site != NULL) {
354         free(gameInfo->site);
355     }
356     if (gameInfo->date != NULL) {
357         free(gameInfo->date);
358     }
359     if (gameInfo->round != NULL) {
360         free(gameInfo->round);
361     }
362     if (gameInfo->white != NULL) {
363         free(gameInfo->white);
364     }
365     if (gameInfo->black != NULL) {
366         free(gameInfo->black);
367     }
368     if (gameInfo->resultDetails != NULL) {
369         free(gameInfo->resultDetails);
370     }
371     if (gameInfo->fen != NULL) {
372         free(gameInfo->fen);
373     }
374     if (gameInfo->timeControl != NULL) {
375         free(gameInfo->timeControl);
376     }
377     if (gameInfo->extraTags != NULL) {
378         free(gameInfo->extraTags);
379     }
380     if (gameInfo->outOfBook != NULL) {
381         free(gameInfo->outOfBook);
382     }
383     GameListInitGameInfo(gameInfo);
384 }
385
386 /* [AS] Replaced by "dynamic" tag selection below */
387 char *
388 GameListLineOld(number, gameInfo)
389      int number;
390      GameInfo *gameInfo;
391 {
392     char *event = (gameInfo->event && strcmp(gameInfo->event, "?") != 0) ?
393                      gameInfo->event : gameInfo->site ? gameInfo->site : "?";
394     char *white = gameInfo->white ? gameInfo->white : "?";
395     char *black = gameInfo->black ? gameInfo->black : "?";
396     char *date = gameInfo->date ? gameInfo->date : "?";
397     int len = 10 + strlen(event) + 2 + strlen(white) + 1 +
398       strlen(black) + 11 + strlen(date) + 1;
399     char *ret = (char *) malloc(len);
400     sprintf(ret, "%d. %s, %s-%s, %s, %s",
401             number, event, white, black, PGNResult(gameInfo->result), date);
402     return ret;
403 }
404
405 #define MAX_FIELD_LEN   80  /* To avoid overflowing the buffer */
406
407 char * GameListLine( int number, GameInfo * gameInfo )
408 {
409     char buffer[2*MSG_SIZ];
410     char * buf = buffer;
411     char * glt = appData.gameListTags;
412
413     buf += sprintf( buffer, "%d.", number );
414
415     while( *glt != '\0' ) {
416         *buf++ = ' ';
417
418         switch( *glt ) {
419         case GLT_EVENT:
420             strncpy( buf, gameInfo->event ? gameInfo->event : "?", MAX_FIELD_LEN );
421             break;
422         case GLT_SITE:
423             strncpy( buf, gameInfo->site ? gameInfo->site : "?", MAX_FIELD_LEN );
424             break;
425         case GLT_DATE:
426             strncpy( buf, gameInfo->date ? gameInfo->date : "?", MAX_FIELD_LEN );
427             break;
428         case GLT_ROUND:
429             strncpy( buf, gameInfo->round ? gameInfo->round : "?", MAX_FIELD_LEN );
430             break;
431         case GLT_PLAYERS:
432             strncpy( buf, gameInfo->white ? gameInfo->white : "?", MAX_FIELD_LEN );
433             buf[ MAX_FIELD_LEN-1 ] = '\0';
434             buf += strlen( buf );
435             *buf++ = '-';
436             strncpy( buf, gameInfo->black ? gameInfo->black : "?", MAX_FIELD_LEN );
437             break;
438         case GLT_RESULT:
439             safeStrCpy( buf, PGNResult(gameInfo->result), 2*MSG_SIZ );
440             break;
441         case GLT_WHITE_ELO:
442             if( gameInfo->whiteRating > 0 )
443               sprintf( buf,  "%d", gameInfo->whiteRating );
444             else
445               safeStrCpy( buf, "?" , 2*MSG_SIZ);
446             break;
447         case GLT_BLACK_ELO:
448             if( gameInfo->blackRating > 0 )
449                 sprintf( buf, "%d", gameInfo->blackRating );
450             else
451               safeStrCpy( buf, "?" , 2*MSG_SIZ);
452             break;
453         case GLT_TIME_CONTROL:
454             strncpy( buf, gameInfo->timeControl ? gameInfo->timeControl : "?", MAX_FIELD_LEN );
455             break;
456         case GLT_VARIANT:
457             break;
458         case GLT_OUT_OF_BOOK:
459             strncpy( buf, gameInfo->outOfBook ? gameInfo->outOfBook : "?", MAX_FIELD_LEN );
460             break;
461         case GLT_RESULT_COMMENT:
462             strncpy( buf, gameInfo->resultDetails ? gameInfo->resultDetails : "res?", MAX_FIELD_LEN );
463             break;
464         default:
465             break;
466         }
467
468         buf[MAX_FIELD_LEN-1] = '\0';
469
470         buf += strlen( buf );
471
472         glt++;
473
474         if( *glt != '\0' ) {
475             *buf++ = ',';
476         }
477     }
478
479     *buf = '\0';
480
481     return strdup( buffer );
482 }
483
484 char * GameListLineFull( int number, GameInfo * gameInfo )
485 {
486     char * event = gameInfo->event ? gameInfo->event : "?";
487     char * site = gameInfo->site ? gameInfo->site : "?";
488     char * white = gameInfo->white ? gameInfo->white : "?";
489     char * black = gameInfo->black ? gameInfo->black : "?";
490     char * round = gameInfo->round ? gameInfo->round : "?";
491     char * date = gameInfo->date ? gameInfo->date : "?";
492     char * oob = gameInfo->outOfBook ? gameInfo->outOfBook : "";
493     char * reason = gameInfo->resultDetails ? gameInfo->resultDetails : "";
494
495     int len = 64 + strlen(event) + strlen(site) + strlen(white) + strlen(black) + strlen(date) + strlen(oob) + strlen(reason);
496
497     char *ret = (char *) malloc(len);
498
499     sprintf(ret, "%d, \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\"",
500         number, event, site, round, white, black, PGNResult(gameInfo->result), reason, date, oob );
501
502     return ret;
503 }
504 // --------------------------------------- Game-List options dialog --------------------------------------
505
506 // back-end
507 typedef struct {
508     char id;
509     char * name;
510 } GLT_Item;
511
512 // back-end: translation table tag id-char <-> full tag name
513 static GLT_Item GLT_ItemInfo[] = {
514     { GLT_EVENT,      "Event" },
515     { GLT_SITE,       "Site" },
516     { GLT_DATE,       "Date" },
517     { GLT_ROUND,      "Round" },
518     { GLT_PLAYERS,    "Players" },
519     { GLT_RESULT,     "Result" },
520     { GLT_WHITE_ELO,  "White Rating" },
521     { GLT_BLACK_ELO,  "Black Rating" },
522     { GLT_TIME_CONTROL,"Time Control" },
523     { GLT_VARIANT,    "Variant" },
524     { GLT_OUT_OF_BOOK,PGN_OUT_OF_BOOK },
525     { GLT_RESULT_COMMENT, "Result Comment" }, // [HGM] rescom
526     { 0, 0 }
527 };
528
529 char lpUserGLT[LPUSERGLT_SIZE];
530
531 // back-end: convert the tag id-char to a full tag name
532 char * GLT_FindItem( char id )
533 {
534     char * result = 0;
535
536     GLT_Item * list = GLT_ItemInfo;
537
538     while( list->id != 0 ) {
539         if( list->id == id ) {
540             result = list->name;
541             break;
542         }
543
544         list++;
545     }
546
547     return result;
548 }
549
550 // back-end: build the list of tag names
551 void
552 GLT_TagsToList( char * tags )
553 {
554     char * pc = tags;
555
556     GLT_ClearList();
557
558     while( *pc ) {
559         GLT_AddToList( GLT_FindItem(*pc) );
560         pc++;
561     }
562
563     GLT_AddToList( "     --- Hidden tags ---     " );
564
565     pc = GLT_ALL_TAGS;
566
567     while( *pc ) {
568         if( strchr( tags, *pc ) == 0 ) {
569             GLT_AddToList( GLT_FindItem(*pc) );
570         }
571         pc++;
572     }
573
574     GLT_DeSelectList();
575 }
576
577 // back-end: retrieve item from dialog and translate to id-char
578 char
579 GLT_ListItemToTag( int index )
580 {
581     char result = '\0';
582     char name[MSG_SIZ];
583
584     GLT_Item * list = GLT_ItemInfo;
585
586     if( GLT_GetFromList(index, name) ) {
587         while( list->id != 0 ) {
588             if( strcmp( list->name, name ) == 0 ) {
589                 result = list->id;
590                 break;
591             }
592
593             list++;
594         }
595     }
596
597     return result;
598 }
599
600 // back-end: add items id-chars one-by-one to temp tags string
601 void
602 GLT_ParseList()
603 {
604     char * pc = lpUserGLT;
605     int idx = 0;
606     char id;
607
608     do {
609         id = GLT_ListItemToTag( idx );
610         *pc++ = id;
611         idx++;
612     } while( id != '\0' );
613 }
614