Describe -overrideLineGap option in texi file
[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 #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 GameListDeleteGame(listGame)
132     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 GameListFree(gameList)
154     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 GameListInitGameInfo(gameInfo)
167     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 *GameListCreate()
193
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 GameListNewGame(listGamePtr)
207      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 GameListBuild(f)
222     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);
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 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 ClearGameInfo(gameInfo)
408     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(number, gameInfo)
449      int number;
450      GameInfo *gameInfo;
451 {
452     char *event = (gameInfo->event && strcmp(gameInfo->event, "?") != 0) ?
453                      gameInfo->event : gameInfo->site ? gameInfo->site : "?";
454     char *white = gameInfo->white ? gameInfo->white : "?";
455     char *black = gameInfo->black ? gameInfo->black : "?";
456     char *date = gameInfo->date ? gameInfo->date : "?";
457     int len = 10 + strlen(event) + 2 + strlen(white) + 1 +
458       strlen(black) + 11 + strlen(date) + 1;
459     char *ret = (char *) malloc(len);
460     sprintf(ret, "%d. %s, %s-%s, %s, %s",
461             number, event, white, black, PGNResult(gameInfo->result), date);
462     return ret;
463 }
464
465 #define MAX_FIELD_LEN   80  /* To avoid overflowing the buffer */
466
467 char * GameListLine( int number, GameInfo * gameInfo )
468 {
469     char buffer[2*MSG_SIZ];
470     char * buf = buffer;
471     char * glt = appData.gameListTags;
472
473     buf += sprintf( buffer, "%d.", number );
474
475     while( *glt != '\0' ) {
476         *buf++ = ' ';
477
478         switch( *glt ) {
479         case GLT_EVENT:
480             strncpy( buf, gameInfo->event ? gameInfo->event : "?", MAX_FIELD_LEN );
481             break;
482         case GLT_SITE:
483             strncpy( buf, gameInfo->site ? gameInfo->site : "?", MAX_FIELD_LEN );
484             break;
485         case GLT_DATE:
486             strncpy( buf, gameInfo->date ? gameInfo->date : "?", MAX_FIELD_LEN );
487             break;
488         case GLT_ROUND:
489             strncpy( buf, gameInfo->round ? gameInfo->round : "?", MAX_FIELD_LEN );
490             break;
491         case GLT_PLAYERS:
492             strncpy( buf, gameInfo->white ? gameInfo->white : "?", MAX_FIELD_LEN );
493             buf[ MAX_FIELD_LEN-1 ] = '\0';
494             buf += strlen( buf );
495             *buf++ = '-';
496             strncpy( buf, gameInfo->black ? gameInfo->black : "?", MAX_FIELD_LEN );
497             break;
498         case GLT_RESULT:
499             safeStrCpy( buf, PGNResult(gameInfo->result), 2*MSG_SIZ );
500             break;
501         case GLT_WHITE_ELO:
502             if( gameInfo->whiteRating > 0 )
503               sprintf( buf,  "%d", gameInfo->whiteRating );
504             else
505               safeStrCpy( buf, "?" , 2*MSG_SIZ);
506             break;
507         case GLT_BLACK_ELO:
508             if( gameInfo->blackRating > 0 )
509                 sprintf( buf, "%d", gameInfo->blackRating );
510             else
511               safeStrCpy( buf, "?" , 2*MSG_SIZ);
512             break;
513         case GLT_TIME_CONTROL:
514             strncpy( buf, gameInfo->timeControl ? gameInfo->timeControl : "?", MAX_FIELD_LEN );
515             break;
516         case GLT_VARIANT:
517             break;
518         case GLT_OUT_OF_BOOK:
519             strncpy( buf, gameInfo->outOfBook ? gameInfo->outOfBook : "?", MAX_FIELD_LEN );
520             break;
521         case GLT_RESULT_COMMENT:
522             strncpy( buf, gameInfo->resultDetails ? gameInfo->resultDetails : "res?", MAX_FIELD_LEN );
523             break;
524         default:
525             break;
526         }
527
528         buf[MAX_FIELD_LEN-1] = '\0';
529
530         buf += strlen( buf );
531
532         glt++;
533
534         if( *glt != '\0' ) {
535             *buf++ = ',';
536         }
537     }
538
539     *buf = '\0';
540
541     return strdup( buffer );
542 }
543
544 char * 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 * GLT_FindItem( char id )
593 {
594     char * result = 0;
595
596     GLT_Item * list = GLT_ItemInfo;
597
598     while( list->id != 0 ) {
599         if( list->id == id ) {
600             result = list->name;
601             break;
602         }
603
604         list++;
605     }
606
607     return result;
608 }
609
610 // back-end: build the list of tag names
611 void
612 GLT_TagsToList( char * tags )
613 {
614     char * pc = tags;
615
616     GLT_ClearList();
617
618     while( *pc ) {
619         GLT_AddToList( GLT_FindItem(*pc) );
620         pc++;
621     }
622
623     GLT_AddToList( "     --- Hidden tags ---     " );
624
625     pc = GLT_ALL_TAGS;
626
627     while( *pc ) {
628         if( strchr( tags, *pc ) == 0 ) {
629             GLT_AddToList( GLT_FindItem(*pc) );
630         }
631         pc++;
632     }
633
634     GLT_DeSelectList();
635 }
636
637 // back-end: retrieve item from dialog and translate to id-char
638 char
639 GLT_ListItemToTag( int index )
640 {
641     char result = '\0';
642     char name[MSG_SIZ];
643
644     GLT_Item * list = GLT_ItemInfo;
645
646     if( GLT_GetFromList(index, name) ) {
647         while( list->id != 0 ) {
648             if( strcmp( list->name, name ) == 0 ) {
649                 result = list->id;
650                 break;
651             }
652
653             list++;
654         }
655     }
656
657     return result;
658 }
659
660 // back-end: add items id-chars one-by-one to temp tags string
661 void
662 GLT_ParseList()
663 {
664     char * pc = lpUserGLT;
665     int idx = 0;
666     char id;
667
668     do {
669         id = GLT_ListItemToTag( idx );
670         *pc++ = id;
671         idx++;
672     } while( id != '\0' );
673 }
674