marked more strings for translation
[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 struct {
221     long sec;  /* Assuming this is >= 32 bits */
222     int ms;    /* Assuming this is >= 16 bits */
223 } t,t2; 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] == '{') { char *p;
356               safeStrCpy(lastComment, yy_text+1, sizeof(lastComment)/sizeof(lastComment[0]));
357               if(p = strchr(lastComment, '}')) *p = 0;
358               currentListGame->gameInfo.resultDetails = StrSave(lastComment);
359             }
360             break;
361           default:
362             break;
363         }
364         if(gameNumber % 1000 == 0) {
365             snprintf(buf, MSG_SIZ,"Reading game file (%d)", gameNumber);
366             DisplayTitle(buf);
367         }
368     }
369     while (cm != (ChessMove) 0);
370
371  if(currentListGame) {
372     if(!currentListGame->moves) DisplayError("Game cache overflowed\nPosition-searching might not work properly", 0);
373
374     if (appData.debugMode) {
375         for (currentListGame = (ListGame *) gameList.head;
376              currentListGame->node.succ;
377              currentListGame = (ListGame *) currentListGame->node.succ) {
378
379             fprintf(debugFP, "Parsed game number %d, offset %ld:\n",
380                     currentListGame->number, currentListGame->offset);
381             PrintPGNTags(debugFP, &currentListGame->gameInfo);
382         }
383     }
384   }
385 GetTimeMark(&t2);printf("GameListBuild %d msec\n", SubtractTimeMarks(&t2,&t));
386     quickFlag = 0;
387     PackGame(boards[scratch]); // for appending end-of-game marker.
388     DisplayTitle("WinBoard");
389     rewind(f);
390     yyskipmoves = FALSE;
391     return 0;
392 }
393
394
395 /* Clear an existing GameInfo structure.
396  */
397 void ClearGameInfo(gameInfo)
398     GameInfo *gameInfo;
399 {
400     if (gameInfo->event != NULL) {
401         free(gameInfo->event);
402     }
403     if (gameInfo->site != NULL) {
404         free(gameInfo->site);
405     }
406     if (gameInfo->date != NULL) {
407         free(gameInfo->date);
408     }
409     if (gameInfo->round != NULL) {
410         free(gameInfo->round);
411     }
412     if (gameInfo->white != NULL) {
413         free(gameInfo->white);
414     }
415     if (gameInfo->black != NULL) {
416         free(gameInfo->black);
417     }
418     if (gameInfo->resultDetails != NULL) {
419         free(gameInfo->resultDetails);
420     }
421     if (gameInfo->fen != NULL) {
422         free(gameInfo->fen);
423     }
424     if (gameInfo->timeControl != NULL) {
425         free(gameInfo->timeControl);
426     }
427     if (gameInfo->extraTags != NULL) {
428         free(gameInfo->extraTags);
429     }
430     if (gameInfo->outOfBook != NULL) {
431         free(gameInfo->outOfBook);
432     }
433     GameListInitGameInfo(gameInfo);
434 }
435
436 /* [AS] Replaced by "dynamic" tag selection below */
437 char *
438 GameListLineOld(number, gameInfo)
439      int number;
440      GameInfo *gameInfo;
441 {
442     char *event = (gameInfo->event && strcmp(gameInfo->event, "?") != 0) ?
443                      gameInfo->event : gameInfo->site ? gameInfo->site : "?";
444     char *white = gameInfo->white ? gameInfo->white : "?";
445     char *black = gameInfo->black ? gameInfo->black : "?";
446     char *date = gameInfo->date ? gameInfo->date : "?";
447     int len = 10 + strlen(event) + 2 + strlen(white) + 1 +
448       strlen(black) + 11 + strlen(date) + 1;
449     char *ret = (char *) malloc(len);
450     sprintf(ret, "%d. %s, %s-%s, %s, %s",
451             number, event, white, black, PGNResult(gameInfo->result), date);
452     return ret;
453 }
454
455 #define MAX_FIELD_LEN   80  /* To avoid overflowing the buffer */
456
457 char * GameListLine( int number, GameInfo * gameInfo )
458 {
459     char buffer[2*MSG_SIZ];
460     char * buf = buffer;
461     char * glt = appData.gameListTags;
462
463     buf += sprintf( buffer, "%d.", number );
464
465     while( *glt != '\0' ) {
466         *buf++ = ' ';
467
468         switch( *glt ) {
469         case GLT_EVENT:
470             strncpy( buf, gameInfo->event ? gameInfo->event : "?", MAX_FIELD_LEN );
471             break;
472         case GLT_SITE:
473             strncpy( buf, gameInfo->site ? gameInfo->site : "?", MAX_FIELD_LEN );
474             break;
475         case GLT_DATE:
476             strncpy( buf, gameInfo->date ? gameInfo->date : "?", MAX_FIELD_LEN );
477             break;
478         case GLT_ROUND:
479             strncpy( buf, gameInfo->round ? gameInfo->round : "?", MAX_FIELD_LEN );
480             break;
481         case GLT_PLAYERS:
482             strncpy( buf, gameInfo->white ? gameInfo->white : "?", MAX_FIELD_LEN );
483             buf[ MAX_FIELD_LEN-1 ] = '\0';
484             buf += strlen( buf );
485             *buf++ = '-';
486             strncpy( buf, gameInfo->black ? gameInfo->black : "?", MAX_FIELD_LEN );
487             break;
488         case GLT_RESULT:
489             safeStrCpy( buf, PGNResult(gameInfo->result), 2*MSG_SIZ );
490             break;
491         case GLT_WHITE_ELO:
492             if( gameInfo->whiteRating > 0 )
493               sprintf( buf,  "%d", gameInfo->whiteRating );
494             else
495               safeStrCpy( buf, "?" , 2*MSG_SIZ);
496             break;
497         case GLT_BLACK_ELO:
498             if( gameInfo->blackRating > 0 )
499                 sprintf( buf, "%d", gameInfo->blackRating );
500             else
501               safeStrCpy( buf, "?" , 2*MSG_SIZ);
502             break;
503         case GLT_TIME_CONTROL:
504             strncpy( buf, gameInfo->timeControl ? gameInfo->timeControl : "?", MAX_FIELD_LEN );
505             break;
506         case GLT_VARIANT:
507             break;
508         case GLT_OUT_OF_BOOK:
509             strncpy( buf, gameInfo->outOfBook ? gameInfo->outOfBook : "?", MAX_FIELD_LEN );
510             break;
511         case GLT_RESULT_COMMENT:
512             strncpy( buf, gameInfo->resultDetails ? gameInfo->resultDetails : "res?", MAX_FIELD_LEN );
513             break;
514         default:
515             break;
516         }
517
518         buf[MAX_FIELD_LEN-1] = '\0';
519
520         buf += strlen( buf );
521
522         glt++;
523
524         if( *glt != '\0' ) {
525             *buf++ = ',';
526         }
527     }
528
529     *buf = '\0';
530
531     return strdup( buffer );
532 }
533
534 char * GameListLineFull( int number, GameInfo * gameInfo )
535 {
536     char * event = gameInfo->event ? gameInfo->event : "?";
537     char * site = gameInfo->site ? gameInfo->site : "?";
538     char * white = gameInfo->white ? gameInfo->white : "?";
539     char * black = gameInfo->black ? gameInfo->black : "?";
540     char * round = gameInfo->round ? gameInfo->round : "?";
541     char * date = gameInfo->date ? gameInfo->date : "?";
542     char * oob = gameInfo->outOfBook ? gameInfo->outOfBook : "";
543     char * reason = gameInfo->resultDetails ? gameInfo->resultDetails : "";
544
545     int len = 64 + strlen(event) + strlen(site) + strlen(white) + strlen(black) + strlen(date) + strlen(oob) + strlen(reason);
546
547     char *ret = (char *) malloc(len);
548
549     sprintf(ret, "%d, \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\"",
550         number, event, site, round, white, black, PGNResult(gameInfo->result), reason, date, oob );
551
552     return ret;
553 }
554 // --------------------------------------- Game-List options dialog --------------------------------------
555
556 // back-end
557 typedef struct {
558     char id;
559     char * name;
560 } GLT_Item;
561
562 // back-end: translation table tag id-char <-> full tag name
563 static GLT_Item GLT_ItemInfo[] = {
564     { GLT_EVENT,      "Event" },
565     { GLT_SITE,       "Site" },
566     { GLT_DATE,       "Date" },
567     { GLT_ROUND,      "Round" },
568     { GLT_PLAYERS,    "Players" },
569     { GLT_RESULT,     "Result" },
570     { GLT_WHITE_ELO,  "White Rating" },
571     { GLT_BLACK_ELO,  "Black Rating" },
572     { GLT_TIME_CONTROL,"Time Control" },
573     { GLT_VARIANT,    "Variant" },
574     { GLT_OUT_OF_BOOK,PGN_OUT_OF_BOOK },
575     { GLT_RESULT_COMMENT, "Result Comment" }, // [HGM] rescom
576     { 0, 0 }
577 };
578
579 char lpUserGLT[LPUSERGLT_SIZE];
580
581 // back-end: convert the tag id-char to a full tag name
582 char * GLT_FindItem( char id )
583 {
584     char * result = 0;
585
586     GLT_Item * list = GLT_ItemInfo;
587
588     while( list->id != 0 ) {
589         if( list->id == id ) {
590             result = list->name;
591             break;
592         }
593
594         list++;
595     }
596
597     return result;
598 }
599
600 // back-end: build the list of tag names
601 void
602 GLT_TagsToList( char * tags )
603 {
604     char * pc = tags;
605
606     GLT_ClearList();
607
608     while( *pc ) {
609         GLT_AddToList( GLT_FindItem(*pc) );
610         pc++;
611     }
612
613     GLT_AddToList( "     --- Hidden tags ---     " );
614
615     pc = GLT_ALL_TAGS;
616
617     while( *pc ) {
618         if( strchr( tags, *pc ) == 0 ) {
619             GLT_AddToList( GLT_FindItem(*pc) );
620         }
621         pc++;
622     }
623
624     GLT_DeSelectList();
625 }
626
627 // back-end: retrieve item from dialog and translate to id-char
628 char
629 GLT_ListItemToTag( int index )
630 {
631     char result = '\0';
632     char name[MSG_SIZ];
633
634     GLT_Item * list = GLT_ItemInfo;
635
636     if( GLT_GetFromList(index, name) ) {
637         while( list->id != 0 ) {
638             if( strcmp( list->name, name ) == 0 ) {
639                 result = list->id;
640                 break;
641             }
642
643             list++;
644         }
645     }
646
647     return result;
648 }
649
650 // back-end: add items id-chars one-by-one to temp tags string
651 void
652 GLT_ParseList()
653 {
654     char * pc = lpUserGLT;
655     int idx = 0;
656     char id;
657
658     do {
659         id = GLT_ListItemToTag( idx );
660         *pc++ = id;
661         idx++;
662     } while( id != '\0' );
663 }
664