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