Quickscan
[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     quickFlag = 1;
228
229     lastStart = (ChessMove) 0;
230     yyskipmoves = FALSE;
231     do {
232         yyboardindex = scratch + (plyNr & 1);
233         offset = yyoffset();
234         cm = (ChessMove) Myylex();
235         switch (cm) {
236           case GNUChessGame:
237             if ((error = GameListNewGame(&currentListGame))) {
238                 rewind(f);
239                 yyskipmoves = FALSE;
240                 return(error);
241             }
242             currentListGame->number = ++gameNumber;
243             currentListGame->offset = offset;
244             if (currentListGame->gameInfo.event != NULL) {
245                 free(currentListGame->gameInfo.event);
246             }
247             currentListGame->gameInfo.event = StrSave(yy_text);
248             lastStart = cm;
249             break;
250           case XBoardGame:
251             lastStart = cm;
252             break;
253           case MoveNumberOne:
254             switch (lastStart) {
255               case GNUChessGame:
256                 break;          /*  ignore  */
257               case PGNTag:
258                 lastStart = cm;
259                 break;          /*  Already started */
260               case (ChessMove) 0:
261               case MoveNumberOne:
262               case XBoardGame:
263                 if ((error = GameListNewGame(&currentListGame))) {
264                     rewind(f);
265                     yyskipmoves = FALSE;
266                     return(error);
267                 }
268                 currentListGame->number = ++gameNumber;
269                 currentListGame->offset = offset;
270                 lastStart = cm;
271                 break;
272               default:
273                 break;          /*  impossible  */
274             }
275             break;
276           case PGNTag:
277             lastStart = cm;
278             if ((error = GameListNewGame(&currentListGame))) {
279                 rewind(f);
280                 yyskipmoves = FALSE;
281                 return(error);
282             }
283             currentListGame->number = ++gameNumber;
284             currentListGame->offset = offset;
285             ParsePGNTag(yy_text, &currentListGame->gameInfo);
286             do {
287                 yyboardindex = 1;
288                 offset = yyoffset();
289                 cm = (ChessMove) Myylex();
290                 if (cm == PGNTag) {
291                     ParsePGNTag(yy_text, &currentListGame->gameInfo);
292                 }
293             } while (cm == PGNTag || cm == Comment);
294             if(1) { CopyBoard(boards[scratch], initialPosition); plyNr = 0; currentListGame->moves = PackGame(boards[scratch]); }
295             if(cm != NormalMove) break;
296           case IllegalMove:
297                 if(appData.testLegality) break;
298           case NormalMove:
299             /* Allow the first game to start with an unnumbered move */
300             yyskipmoves = FALSE;
301             if (lastStart == (ChessMove) 0) {
302               if ((error = GameListNewGame(&currentListGame))) {
303                 rewind(f);
304                 yyskipmoves = FALSE;
305                 return(error);
306               }
307               currentListGame->number = ++gameNumber;
308               currentListGame->offset = offset;
309               lastStart = MoveNumberOne;
310             }
311           case WhiteCapturesEnPassant:
312           case BlackCapturesEnPassant:
313           case WhitePromotion:
314           case BlackPromotion:
315           case WhiteNonPromotion:
316           case BlackNonPromotion:
317           case WhiteKingSideCastle:
318           case WhiteQueenSideCastle:
319           case BlackKingSideCastle:
320           case BlackQueenSideCastle:
321           case WhiteKingSideCastleWild:
322           case WhiteQueenSideCastleWild:
323           case BlackKingSideCastleWild:
324           case BlackQueenSideCastleWild:
325           case WhiteHSideCastleFR:
326           case WhiteASideCastleFR:
327           case BlackHSideCastleFR:
328           case BlackASideCastleFR:
329                 fromX = currentMoveString[0] - AAA;
330                 fromY = currentMoveString[1] - ONE;
331                 toX = currentMoveString[2] - AAA;
332                 toY = currentMoveString[3] - ONE;
333                 CopyBoard(boards[scratch + (plyNr+1&1)], boards[scratch + (plyNr&1)]);
334                 plyNr++;
335                 ApplyMove(fromX, fromY, toX, toY, currentMoveString[4], boards[scratch + (plyNr&1)]);
336                 PackMove(fromX, fromY, toX, toY, currentMoveString[4]);
337             break;
338         case WhiteWins: // [HGM] rescom: save last comment as result details
339         case BlackWins:
340         case GameIsDrawn:
341         case GameUnfinished:
342             if(!currentListGame) break;
343             if (currentListGame->gameInfo.resultDetails != NULL) {
344                 free(currentListGame->gameInfo.resultDetails);
345             }
346             if(yy_text[0] == '{') { char *p;
347               safeStrCpy(lastComment, yy_text+1, sizeof(lastComment)/sizeof(lastComment[0]));
348               if(p = strchr(lastComment, '}')) *p = 0;
349               currentListGame->gameInfo.resultDetails = StrSave(lastComment);
350             }
351             break;
352           default:
353             break;
354         }
355         if(gameNumber % 1000 == 0) {
356             snprintf(buf, MSG_SIZ,"Reading game file (%d)", gameNumber);
357             DisplayTitle(buf);
358         }
359     }
360     while (cm != (ChessMove) 0);
361
362     if (appData.debugMode) {
363         for (currentListGame = (ListGame *) gameList.head;
364              currentListGame->node.succ;
365              currentListGame = (ListGame *) currentListGame->node.succ) {
366
367             fprintf(debugFP, "Parsed game number %d, offset %ld:\n",
368                     currentListGame->number, currentListGame->offset);
369             PrintPGNTags(debugFP, &currentListGame->gameInfo);
370         }
371     }
372 GetTimeMark(&t2);printf("GameListBuild %d msec\n", SubtractTimeMarks(&t2,&t));
373     quickFlag = 0;
374     DisplayTitle("WinBoard");
375     rewind(f);
376     yyskipmoves = FALSE;
377     return 0;
378 }
379
380
381 /* Clear an existing GameInfo structure.
382  */
383 void ClearGameInfo(gameInfo)
384     GameInfo *gameInfo;
385 {
386     if (gameInfo->event != NULL) {
387         free(gameInfo->event);
388     }
389     if (gameInfo->site != NULL) {
390         free(gameInfo->site);
391     }
392     if (gameInfo->date != NULL) {
393         free(gameInfo->date);
394     }
395     if (gameInfo->round != NULL) {
396         free(gameInfo->round);
397     }
398     if (gameInfo->white != NULL) {
399         free(gameInfo->white);
400     }
401     if (gameInfo->black != NULL) {
402         free(gameInfo->black);
403     }
404     if (gameInfo->resultDetails != NULL) {
405         free(gameInfo->resultDetails);
406     }
407     if (gameInfo->fen != NULL) {
408         free(gameInfo->fen);
409     }
410     if (gameInfo->timeControl != NULL) {
411         free(gameInfo->timeControl);
412     }
413     if (gameInfo->extraTags != NULL) {
414         free(gameInfo->extraTags);
415     }
416     if (gameInfo->outOfBook != NULL) {
417         free(gameInfo->outOfBook);
418     }
419     GameListInitGameInfo(gameInfo);
420 }
421
422 /* [AS] Replaced by "dynamic" tag selection below */
423 char *
424 GameListLineOld(number, gameInfo)
425      int number;
426      GameInfo *gameInfo;
427 {
428     char *event = (gameInfo->event && strcmp(gameInfo->event, "?") != 0) ?
429                      gameInfo->event : gameInfo->site ? gameInfo->site : "?";
430     char *white = gameInfo->white ? gameInfo->white : "?";
431     char *black = gameInfo->black ? gameInfo->black : "?";
432     char *date = gameInfo->date ? gameInfo->date : "?";
433     int len = 10 + strlen(event) + 2 + strlen(white) + 1 +
434       strlen(black) + 11 + strlen(date) + 1;
435     char *ret = (char *) malloc(len);
436     sprintf(ret, "%d. %s, %s-%s, %s, %s",
437             number, event, white, black, PGNResult(gameInfo->result), date);
438     return ret;
439 }
440
441 #define MAX_FIELD_LEN   80  /* To avoid overflowing the buffer */
442
443 char * GameListLine( int number, GameInfo * gameInfo )
444 {
445     char buffer[2*MSG_SIZ];
446     char * buf = buffer;
447     char * glt = appData.gameListTags;
448
449     buf += sprintf( buffer, "%d.", number );
450
451     while( *glt != '\0' ) {
452         *buf++ = ' ';
453
454         switch( *glt ) {
455         case GLT_EVENT:
456             strncpy( buf, gameInfo->event ? gameInfo->event : "?", MAX_FIELD_LEN );
457             break;
458         case GLT_SITE:
459             strncpy( buf, gameInfo->site ? gameInfo->site : "?", MAX_FIELD_LEN );
460             break;
461         case GLT_DATE:
462             strncpy( buf, gameInfo->date ? gameInfo->date : "?", MAX_FIELD_LEN );
463             break;
464         case GLT_ROUND:
465             strncpy( buf, gameInfo->round ? gameInfo->round : "?", MAX_FIELD_LEN );
466             break;
467         case GLT_PLAYERS:
468             strncpy( buf, gameInfo->white ? gameInfo->white : "?", MAX_FIELD_LEN );
469             buf[ MAX_FIELD_LEN-1 ] = '\0';
470             buf += strlen( buf );
471             *buf++ = '-';
472             strncpy( buf, gameInfo->black ? gameInfo->black : "?", MAX_FIELD_LEN );
473             break;
474         case GLT_RESULT:
475             safeStrCpy( buf, PGNResult(gameInfo->result), 2*MSG_SIZ );
476             break;
477         case GLT_WHITE_ELO:
478             if( gameInfo->whiteRating > 0 )
479               sprintf( buf,  "%d", gameInfo->whiteRating );
480             else
481               safeStrCpy( buf, "?" , 2*MSG_SIZ);
482             break;
483         case GLT_BLACK_ELO:
484             if( gameInfo->blackRating > 0 )
485                 sprintf( buf, "%d", gameInfo->blackRating );
486             else
487               safeStrCpy( buf, "?" , 2*MSG_SIZ);
488             break;
489         case GLT_TIME_CONTROL:
490             strncpy( buf, gameInfo->timeControl ? gameInfo->timeControl : "?", MAX_FIELD_LEN );
491             break;
492         case GLT_VARIANT:
493             break;
494         case GLT_OUT_OF_BOOK:
495             strncpy( buf, gameInfo->outOfBook ? gameInfo->outOfBook : "?", MAX_FIELD_LEN );
496             break;
497         case GLT_RESULT_COMMENT:
498             strncpy( buf, gameInfo->resultDetails ? gameInfo->resultDetails : "res?", MAX_FIELD_LEN );
499             break;
500         default:
501             break;
502         }
503
504         buf[MAX_FIELD_LEN-1] = '\0';
505
506         buf += strlen( buf );
507
508         glt++;
509
510         if( *glt != '\0' ) {
511             *buf++ = ',';
512         }
513     }
514
515     *buf = '\0';
516
517     return strdup( buffer );
518 }
519
520 char * GameListLineFull( int number, GameInfo * gameInfo )
521 {
522     char * event = gameInfo->event ? gameInfo->event : "?";
523     char * site = gameInfo->site ? gameInfo->site : "?";
524     char * white = gameInfo->white ? gameInfo->white : "?";
525     char * black = gameInfo->black ? gameInfo->black : "?";
526     char * round = gameInfo->round ? gameInfo->round : "?";
527     char * date = gameInfo->date ? gameInfo->date : "?";
528     char * oob = gameInfo->outOfBook ? gameInfo->outOfBook : "";
529     char * reason = gameInfo->resultDetails ? gameInfo->resultDetails : "";
530
531     int len = 64 + strlen(event) + strlen(site) + strlen(white) + strlen(black) + strlen(date) + strlen(oob) + strlen(reason);
532
533     char *ret = (char *) malloc(len);
534
535     sprintf(ret, "%d, \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\"",
536         number, event, site, round, white, black, PGNResult(gameInfo->result), reason, date, oob );
537
538     return ret;
539 }
540 // --------------------------------------- Game-List options dialog --------------------------------------
541
542 // back-end
543 typedef struct {
544     char id;
545     char * name;
546 } GLT_Item;
547
548 // back-end: translation table tag id-char <-> full tag name
549 static GLT_Item GLT_ItemInfo[] = {
550     { GLT_EVENT,      "Event" },
551     { GLT_SITE,       "Site" },
552     { GLT_DATE,       "Date" },
553     { GLT_ROUND,      "Round" },
554     { GLT_PLAYERS,    "Players" },
555     { GLT_RESULT,     "Result" },
556     { GLT_WHITE_ELO,  "White Rating" },
557     { GLT_BLACK_ELO,  "Black Rating" },
558     { GLT_TIME_CONTROL,"Time Control" },
559     { GLT_VARIANT,    "Variant" },
560     { GLT_OUT_OF_BOOK,PGN_OUT_OF_BOOK },
561     { GLT_RESULT_COMMENT, "Result Comment" }, // [HGM] rescom
562     { 0, 0 }
563 };
564
565 char lpUserGLT[LPUSERGLT_SIZE];
566
567 // back-end: convert the tag id-char to a full tag name
568 char * GLT_FindItem( char id )
569 {
570     char * result = 0;
571
572     GLT_Item * list = GLT_ItemInfo;
573
574     while( list->id != 0 ) {
575         if( list->id == id ) {
576             result = list->name;
577             break;
578         }
579
580         list++;
581     }
582
583     return result;
584 }
585
586 // back-end: build the list of tag names
587 void
588 GLT_TagsToList( char * tags )
589 {
590     char * pc = tags;
591
592     GLT_ClearList();
593
594     while( *pc ) {
595         GLT_AddToList( GLT_FindItem(*pc) );
596         pc++;
597     }
598
599     GLT_AddToList( "     --- Hidden tags ---     " );
600
601     pc = GLT_ALL_TAGS;
602
603     while( *pc ) {
604         if( strchr( tags, *pc ) == 0 ) {
605             GLT_AddToList( GLT_FindItem(*pc) );
606         }
607         pc++;
608     }
609
610     GLT_DeSelectList();
611 }
612
613 // back-end: retrieve item from dialog and translate to id-char
614 char
615 GLT_ListItemToTag( int index )
616 {
617     char result = '\0';
618     char name[MSG_SIZ];
619
620     GLT_Item * list = GLT_ItemInfo;
621
622     if( GLT_GetFromList(index, name) ) {
623         while( list->id != 0 ) {
624             if( strcmp( list->name, name ) == 0 ) {
625                 result = list->id;
626                 break;
627             }
628
629             list++;
630         }
631     }
632
633     return result;
634 }
635
636 // back-end: add items id-chars one-by-one to temp tags string
637 void
638 GLT_ParseList()
639 {
640     char * pc = lpUserGLT;
641     int idx = 0;
642     char id;
643
644     do {
645         id = GLT_ListItemToTag( idx );
646         *pc++ = id;
647         idx++;
648     } while( id != '\0' );
649 }
650