Print progress during load / selection of game
[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->gameInfo.resultDetails != NULL) {
308                 free(currentListGame->gameInfo.resultDetails);
309             }
310             if(yy_text[0] == '{') { char *p;
311               safeStrCpy(lastComment, yy_text+1, sizeof(lastComment)/sizeof(lastComment[0]));
312               if(p = strchr(lastComment, '}')) *p = 0;
313               currentListGame->gameInfo.resultDetails = StrSave(lastComment);
314             }
315             break;
316           default:
317             break;
318         }
319         if(gameNumber % 1000 == 0) {
320             snprintf(buf, MSG_SIZ,"Reading game file (%d)", gameNumber);
321             DisplayTitle(buf);
322         }
323     }
324     while (cm != (ChessMove) 0);
325
326     if (appData.debugMode) {
327         for (currentListGame = (ListGame *) gameList.head;
328              currentListGame->node.succ;
329              currentListGame = (ListGame *) currentListGame->node.succ) {
330
331             fprintf(debugFP, "Parsed game number %d, offset %ld:\n",
332                     currentListGame->number, currentListGame->offset);
333             PrintPGNTags(debugFP, &currentListGame->gameInfo);
334         }
335     }
336
337     rewind(f);
338     yyskipmoves = FALSE;
339     DisplayTitle("WinBoard");
340     return 0;
341 }
342
343
344 /* Clear an existing GameInfo structure.
345  */
346 void ClearGameInfo(gameInfo)
347     GameInfo *gameInfo;
348 {
349     if (gameInfo->event != NULL) {
350         free(gameInfo->event);
351     }
352     if (gameInfo->site != NULL) {
353         free(gameInfo->site);
354     }
355     if (gameInfo->date != NULL) {
356         free(gameInfo->date);
357     }
358     if (gameInfo->round != NULL) {
359         free(gameInfo->round);
360     }
361     if (gameInfo->white != NULL) {
362         free(gameInfo->white);
363     }
364     if (gameInfo->black != NULL) {
365         free(gameInfo->black);
366     }
367     if (gameInfo->resultDetails != NULL) {
368         free(gameInfo->resultDetails);
369     }
370     if (gameInfo->fen != NULL) {
371         free(gameInfo->fen);
372     }
373     if (gameInfo->timeControl != NULL) {
374         free(gameInfo->timeControl);
375     }
376     if (gameInfo->extraTags != NULL) {
377         free(gameInfo->extraTags);
378     }
379     if (gameInfo->outOfBook != NULL) {
380         free(gameInfo->outOfBook);
381     }
382     GameListInitGameInfo(gameInfo);
383 }
384
385 /* [AS] Replaced by "dynamic" tag selection below */
386 char *
387 GameListLineOld(number, gameInfo)
388      int number;
389      GameInfo *gameInfo;
390 {
391     char *event = (gameInfo->event && strcmp(gameInfo->event, "?") != 0) ?
392                      gameInfo->event : gameInfo->site ? gameInfo->site : "?";
393     char *white = gameInfo->white ? gameInfo->white : "?";
394     char *black = gameInfo->black ? gameInfo->black : "?";
395     char *date = gameInfo->date ? gameInfo->date : "?";
396     int len = 10 + strlen(event) + 2 + strlen(white) + 1 +
397       strlen(black) + 11 + strlen(date) + 1;
398     char *ret = (char *) malloc(len);
399     sprintf(ret, "%d. %s, %s-%s, %s, %s",
400             number, event, white, black, PGNResult(gameInfo->result), date);
401     return ret;
402 }
403
404 #define MAX_FIELD_LEN   80  /* To avoid overflowing the buffer */
405
406 char * GameListLine( int number, GameInfo * gameInfo )
407 {
408     char buffer[2*MSG_SIZ];
409     char * buf = buffer;
410     char * glt = appData.gameListTags;
411
412     buf += sprintf( buffer, "%d.", number );
413
414     while( *glt != '\0' ) {
415         *buf++ = ' ';
416
417         switch( *glt ) {
418         case GLT_EVENT:
419             strncpy( buf, gameInfo->event ? gameInfo->event : "?", MAX_FIELD_LEN );
420             break;
421         case GLT_SITE:
422             strncpy( buf, gameInfo->site ? gameInfo->site : "?", MAX_FIELD_LEN );
423             break;
424         case GLT_DATE:
425             strncpy( buf, gameInfo->date ? gameInfo->date : "?", MAX_FIELD_LEN );
426             break;
427         case GLT_ROUND:
428             strncpy( buf, gameInfo->round ? gameInfo->round : "?", MAX_FIELD_LEN );
429             break;
430         case GLT_PLAYERS:
431             strncpy( buf, gameInfo->white ? gameInfo->white : "?", MAX_FIELD_LEN );
432             buf[ MAX_FIELD_LEN-1 ] = '\0';
433             buf += strlen( buf );
434             *buf++ = '-';
435             strncpy( buf, gameInfo->black ? gameInfo->black : "?", MAX_FIELD_LEN );
436             break;
437         case GLT_RESULT:
438             safeStrCpy( buf, PGNResult(gameInfo->result), 2*MSG_SIZ );
439             break;
440         case GLT_WHITE_ELO:
441             if( gameInfo->whiteRating > 0 )
442               sprintf( buf,  "%d", gameInfo->whiteRating );
443             else
444               safeStrCpy( buf, "?" , 2*MSG_SIZ);
445             break;
446         case GLT_BLACK_ELO:
447             if( gameInfo->blackRating > 0 )
448                 sprintf( buf, "%d", gameInfo->blackRating );
449             else
450               safeStrCpy( buf, "?" , 2*MSG_SIZ);
451             break;
452         case GLT_TIME_CONTROL:
453             strncpy( buf, gameInfo->timeControl ? gameInfo->timeControl : "?", MAX_FIELD_LEN );
454             break;
455         case GLT_VARIANT:
456             break;
457         case GLT_OUT_OF_BOOK:
458             strncpy( buf, gameInfo->outOfBook ? gameInfo->outOfBook : "?", MAX_FIELD_LEN );
459             break;
460         case GLT_RESULT_COMMENT:
461             strncpy( buf, gameInfo->resultDetails ? gameInfo->resultDetails : "res?", MAX_FIELD_LEN );
462             break;
463         default:
464             break;
465         }
466
467         buf[MAX_FIELD_LEN-1] = '\0';
468
469         buf += strlen( buf );
470
471         glt++;
472
473         if( *glt != '\0' ) {
474             *buf++ = ',';
475         }
476     }
477
478     *buf = '\0';
479
480     return strdup( buffer );
481 }
482
483 char * GameListLineFull( int number, GameInfo * gameInfo )
484 {
485     char * event = gameInfo->event ? gameInfo->event : "?";
486     char * site = gameInfo->site ? gameInfo->site : "?";
487     char * white = gameInfo->white ? gameInfo->white : "?";
488     char * black = gameInfo->black ? gameInfo->black : "?";
489     char * round = gameInfo->round ? gameInfo->round : "?";
490     char * date = gameInfo->date ? gameInfo->date : "?";
491     char * oob = gameInfo->outOfBook ? gameInfo->outOfBook : "";
492     char * reason = gameInfo->resultDetails ? gameInfo->resultDetails : "";
493
494     int len = 64 + strlen(event) + strlen(site) + strlen(white) + strlen(black) + strlen(date) + strlen(oob) + strlen(reason);
495
496     char *ret = (char *) malloc(len);
497
498     sprintf(ret, "%d, \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\"",
499         number, event, site, round, white, black, PGNResult(gameInfo->result), reason, date, oob );
500
501     return ret;
502 }
503 // --------------------------------------- Game-List options dialog --------------------------------------
504
505 // back-end
506 typedef struct {
507     char id;
508     char * name;
509 } GLT_Item;
510
511 // back-end: translation table tag id-char <-> full tag name
512 static GLT_Item GLT_ItemInfo[] = {
513     { GLT_EVENT,      "Event" },
514     { GLT_SITE,       "Site" },
515     { GLT_DATE,       "Date" },
516     { GLT_ROUND,      "Round" },
517     { GLT_PLAYERS,    "Players" },
518     { GLT_RESULT,     "Result" },
519     { GLT_WHITE_ELO,  "White Rating" },
520     { GLT_BLACK_ELO,  "Black Rating" },
521     { GLT_TIME_CONTROL,"Time Control" },
522     { GLT_VARIANT,    "Variant" },
523     { GLT_OUT_OF_BOOK,PGN_OUT_OF_BOOK },
524     { GLT_RESULT_COMMENT, "Result Comment" }, // [HGM] rescom
525     { 0, 0 }
526 };
527
528 char lpUserGLT[LPUSERGLT_SIZE];
529
530 // back-end: convert the tag id-char to a full tag name
531 char * GLT_FindItem( char id )
532 {
533     char * result = 0;
534
535     GLT_Item * list = GLT_ItemInfo;
536
537     while( list->id != 0 ) {
538         if( list->id == id ) {
539             result = list->name;
540             break;
541         }
542
543         list++;
544     }
545
546     return result;
547 }
548
549 // back-end: build the list of tag names
550 void
551 GLT_TagsToList( char * tags )
552 {
553     char * pc = tags;
554
555     GLT_ClearList();
556
557     while( *pc ) {
558         GLT_AddToList( GLT_FindItem(*pc) );
559         pc++;
560     }
561
562     GLT_AddToList( "     --- Hidden tags ---     " );
563
564     pc = GLT_ALL_TAGS;
565
566     while( *pc ) {
567         if( strchr( tags, *pc ) == 0 ) {
568             GLT_AddToList( GLT_FindItem(*pc) );
569         }
570         pc++;
571     }
572
573     GLT_DeSelectList();
574 }
575
576 // back-end: retrieve item from dialog and translate to id-char
577 char
578 GLT_ListItemToTag( int index )
579 {
580     char result = '\0';
581     char name[MSG_SIZ];
582
583     GLT_Item * list = GLT_ItemInfo;
584
585     if( GLT_GetFromList(index, name) ) {
586         while( list->id != 0 ) {
587             if( strcmp( list->name, name ) == 0 ) {
588                 result = list->id;
589                 break;
590             }
591
592             list++;
593         }
594     }
595
596     return result;
597 }
598
599 // back-end: add items id-chars one-by-one to temp tags string
600 void
601 GLT_ParseList()
602 {
603     char * pc = lpUserGLT;
604     int idx = 0;
605     char id;
606
607     do {
608         id = GLT_ListItemToTag( idx );
609         *pc++ = id;
610         idx++;
611     } while( id != '\0' );
612 }
613