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