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