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