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