Keep list of excluded moves in Engine Output header
[xboard.git] / engineoutput.c
1 /*
2  * engineoutput.c - split-off backe-end from Engine output (PV) by HGM
3  *
4  * Author: Alessandro Scotti (Dec 2005)
5  *
6  * Copyright 2005 Alessandro Scotti
7  *
8  * Enhancements Copyright 1995, 2009, 2010, 2011, 2012 Free Software Foundation, Inc.
9  *
10  * ------------------------------------------------------------------------
11  *
12  * GNU XBoard is free software: you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation, either version 3 of the License, or (at
15  * your option) any later version.
16  *
17  * GNU XBoard is distributed in the hope that it will be useful, but
18  * WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20  * General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program. If not, see http://www.gnu.org/licenses/.  *
24  *
25  *------------------------------------------------------------------------
26  ** See the file ChangeLog for a revision history.  */
27
28 #define SHOW_PONDERING
29
30 #include "config.h"
31
32 #include <stdio.h>
33
34 #if STDC_HEADERS
35 # include <stdlib.h>
36 # include <string.h>
37 #else /* not STDC_HEADERS */
38 # if HAVE_STRING_H
39 #  include <string.h>
40 # else /* not HAVE_STRING_H */
41 #  include <strings.h>
42 # endif /* not HAVE_STRING_H */
43 #endif /* not STDC_HEADERS */
44
45 #include "common.h"
46 #include "frontend.h"
47 #include "backend.h"
48 #include "moves.h"
49 #include "engineoutput.h"
50 #include "gettext.h"
51
52 #ifdef ENABLE_NLS
53 # define  _(s) gettext (s)
54 # define N_(s) gettext_noop (s)
55 #else
56 # ifdef WIN32
57 #  define  _(s) T_(s)
58 #  undef  ngettext
59 #  define  ngettext(s,p,n) T_(p)
60 # else
61 #  define  _(s) (s)
62 # endif
63 # define N_(s)  s
64 #endif
65
66 typedef struct {
67     char * name;
68     int which;
69     int depth;
70     u64 nodes;
71     int score;
72     int time;
73     char * pv;
74     char * hint;
75     int an_move_index;
76     int an_move_count;
77 } EngineOutputData;
78
79 // called by other front-end
80 void EngineOutputUpdate( FrontEndProgramStats * stats );
81 void OutputKibitz(int window, char *text);
82
83 // module back-end routines
84 static void VerifyDisplayMode();
85 static void UpdateControls( EngineOutputData * ed );
86
87 static int  lastDepth[2] = { -1, -1 };
88 static int  lastForwardMostMove[2] = { -1, -1 };
89 static int  engineState[2] = { -1, -1 };
90 static char lastLine[2][MSG_SIZ];
91 static char header[MSG_SIZ];
92
93 #define MAX_VAR 400
94 static int scores[MAX_VAR], textEnd[MAX_VAR], curDepth[2], nrVariations[2];
95
96 extern int initialRulePlies;
97
98 void
99 MakeEngineOutputTitle ()
100 {
101         static char buf[MSG_SIZ];
102         static char oldTitle[MSG_SIZ];
103         char title[MSG_SIZ];
104         int count, rule = 2*appData.ruleMoves;
105
106         snprintf(title, MSG_SIZ, _("Engine Output") );
107
108         if(!EngineOutputIsUp()) return;
109         // figure out value of 50-move counter
110         count = currentMove;
111         while( (signed char)boards[count][EP_STATUS] <= EP_NONE && count > backwardMostMove ) count--;
112         if( count == backwardMostMove ) count -= initialRulePlies;
113         count = currentMove - count;
114         if(!rule) rule = 100;
115         if(count >= rule - 40 && (!appData.icsActive || gameMode == IcsObserving)) {
116                 snprintf(buf, MSG_SIZ, ngettext("%s (%d reversible ply)", "%s (%d reversible plies)", count), title, count);
117                 safeStrCpy(title, buf, MSG_SIZ);
118         }
119         if(!strcmp(oldTitle, title)) return;
120         safeStrCpy(oldTitle, title, MSG_SIZ);
121         SetEngineOutputTitle(title);
122 }
123
124 // back end, due to front-end wrapper for SetWindowText, and new SetIcon arguments
125 void
126 SetEngineState (int which, int state, char * state_data)
127 {
128     int x_which = 1 - which;
129
130     if( engineState[ which ] != state ) {
131         engineState[ which ] = state;
132
133         switch( state ) {
134         case STATE_THINKING:
135             SetIcon( which, nStateIcon, nThinking );
136             if( engineState[ x_which ] == STATE_THINKING ) {
137                 SetEngineState( x_which, STATE_IDLE, "" );
138             }
139             break;
140         case STATE_PONDERING:
141             SetIcon( which, nStateIcon, nPondering );
142             break;
143         case STATE_ANALYZING:
144             SetIcon( which, nStateIcon, nAnalyzing );
145             break;
146         default:
147             SetIcon( which, nStateIcon, nClear );
148             break;
149         }
150     }
151
152     if( state_data != 0 ) {
153         DoSetWindowText( which, nStateData, state_data );
154     }
155 }
156
157 // back end, now the front-end wrapper ClearMemo is used, and ed no longer contains handles.
158 void
159 SetProgramStats (FrontEndProgramStats * stats) // now directly called by back-end
160 {
161     EngineOutputData ed;
162     int clearMemo = FALSE;
163     int which, depth, multi;
164
165     if( stats == 0 ) {
166         SetEngineState( 0, STATE_IDLE, "" );
167         SetEngineState( 1, STATE_IDLE, "" );
168         return;
169     }
170
171     if(gameMode == IcsObserving && !appData.icsEngineAnalyze)
172         return; // [HGM] kibitz: shut up engine if we are observing an ICS game
173
174     which = stats->which;
175     depth = stats->depth;
176
177     if( which < 0 || which > 1 || depth < 0 || stats->time < 0 || stats->pv == 0 ) {
178         return;
179     }
180
181     if( !EngineOutputDialogExists() ) {
182         return;
183     }
184
185     VerifyDisplayMode();
186
187     ed.which = which;
188     ed.depth = depth;
189     ed.nodes = stats->nodes;
190     ed.score = stats->score;
191     ed.time = stats->time;
192     ed.pv = stats->pv;
193     ed.hint = stats->hint;
194     ed.an_move_index = stats->an_move_index;
195     ed.an_move_count = stats->an_move_count;
196
197     /* Get target control. [HGM] this is moved to front end, which get them from a table */
198     if( which == 0 ) {
199         ed.name = first.tidy;
200     }
201     else {
202         ed.name = second.tidy;
203     }
204
205     if( ed.pv != 0 && ed.pv[0] == ' ' ) {
206         if( strncmp( ed.pv, " no PV", 6 ) == 0 ) { /* Hack on hack! :-O */
207             ed.pv = "";
208         }
209     }
210
211     /* Clear memo if needed */
212     if( lastDepth[which] > depth || (lastDepth[which] == depth && depth <= 1 && ed.pv[0]) ) { // no reason to clear if we won't add line
213         clearMemo = TRUE;
214     }
215
216     if( lastForwardMostMove[which] != forwardMostMove ) {
217         clearMemo = TRUE;
218     }
219
220     if( clearMemo ) {
221         DoClearMemo(which); nrVariations[which] = 0;
222         header[0] = NULLCHAR;
223         if(gameMode == AnalyzeMode) {
224           if((multi = MultiPV(&first)) >= 0) {
225             snprintf(header, MSG_SIZ, "\t%s viewpoint\t\tfewer / Multi-PV setting = %d / more\n",
226                                        appData.whitePOV || appData.scoreWhite ? "white" : "mover", first.option[multi].value);
227           }
228           snprintf(header+strlen(header), MSG_SIZ-strlen(header), exclusionHeader);
229           InsertIntoMemo( which, header, 0);
230         } else
231         if(appData.ponderNextMove && lastLine[which][0]) {
232             InsertIntoMemo( which, lastLine[which], 0 );
233             InsertIntoMemo( which, "\n", 0 );
234         }
235     }
236
237     /* Update */
238     lastDepth[which] = depth == 1 && ed.nodes == 0 ? 0 : depth; // [HGM] info-line kudge
239     lastForwardMostMove[which] = forwardMostMove;
240
241     UpdateControls( &ed );
242 }
243
244 #define ENGINE_COLOR_WHITE      'w'
245 #define ENGINE_COLOR_BLACK      'b'
246 #define ENGINE_COLOR_UNKNOWN    ' '
247
248 // pure back end
249 static char
250 GetEngineColor (int which)
251 {
252     char result = ENGINE_COLOR_UNKNOWN;
253
254     if( which == 0 || which == 1 ) {
255         ChessProgramState * cps;
256
257         switch (gameMode) {
258         case MachinePlaysBlack:
259         case IcsPlayingBlack:
260             result = ENGINE_COLOR_BLACK;
261             break;
262         case MachinePlaysWhite:
263         case IcsPlayingWhite:
264             result = ENGINE_COLOR_WHITE;
265             break;
266         case AnalyzeMode:
267         case AnalyzeFile:
268             result = WhiteOnMove(forwardMostMove) ? ENGINE_COLOR_WHITE : ENGINE_COLOR_BLACK;
269             break;
270         case TwoMachinesPlay:
271             cps = (which == 0) ? &first : &second;
272             result = cps->twoMachinesColor[0];
273             result = result == 'w' ? ENGINE_COLOR_WHITE : ENGINE_COLOR_BLACK;
274             break;
275         default: ; // does not happen, but suppresses pedantic warnings
276         }
277     }
278
279     return result;
280 }
281
282 // pure back end
283 static char
284 GetActiveEngineColor ()
285 {
286     char result = ENGINE_COLOR_UNKNOWN;
287
288     if( gameMode == TwoMachinesPlay ) {
289         result = WhiteOnMove(forwardMostMove) ? ENGINE_COLOR_WHITE : ENGINE_COLOR_BLACK;
290     }
291
292     return result;
293 }
294
295 // pure back end
296 static int
297 IsEnginePondering (int which)
298 {
299     int result = FALSE;
300
301     switch (gameMode) {
302     case MachinePlaysBlack:
303     case IcsPlayingBlack:
304         if( WhiteOnMove(forwardMostMove) ) result = TRUE;
305         break;
306     case MachinePlaysWhite:
307     case IcsPlayingWhite:
308         if( ! WhiteOnMove(forwardMostMove) ) result = TRUE;
309         break;
310     case TwoMachinesPlay:
311         if( GetActiveEngineColor() != ENGINE_COLOR_UNKNOWN ) {
312             if( GetEngineColor( which ) != GetActiveEngineColor() ) result = TRUE;
313         }
314         break;
315     default: ; // does not happen, but suppresses pedantic warnings
316     }
317
318     return result;
319 }
320
321 // back end
322 static void
323 SetDisplayMode (int mode)
324 {
325     if( windowMode != mode ) {
326         windowMode = mode;
327
328         ResizeWindowControls( mode );
329     }
330 }
331
332 // pure back end
333 static void
334 VerifyDisplayMode ()
335 {
336     int mode;
337
338     /* Get proper mode for current game */
339     switch( gameMode ) {
340     case IcsObserving:    // [HGM] ICS analyze
341         if(!appData.icsEngineAnalyze) return;
342     case AnalyzeMode:
343     case AnalyzeFile:
344     case MachinePlaysWhite:
345     case MachinePlaysBlack:
346         mode = 0;
347         break;
348     case IcsPlayingWhite:
349     case IcsPlayingBlack:
350         mode = appData.zippyPlay && opponentKibitzes; // [HGM] kibitz
351         break;
352     case TwoMachinesPlay:
353         mode = 1;
354         break;
355     default:
356         /* Do not change */
357         return;
358     }
359
360     SetDisplayMode( mode );
361 }
362
363 // back end. Determine what icon to set in the color-icon field, and print it
364 void
365 SetEngineColorIcon (int which)
366 {
367     char color = GetEngineColor(which);
368     int nicon = 0;
369
370     if( color == ENGINE_COLOR_BLACK )
371         nicon = nColorBlack;
372     else if( color == ENGINE_COLOR_WHITE )
373         nicon = nColorWhite;
374     else
375         nicon = nColorUnknown;
376
377     SetIcon( which, nColorIcon, nicon );
378 }
379
380 #define MAX_NAME_LENGTH 32
381
382 // [HGM] multivar: sort Thinking Output within one depth on score
383
384 static int
385 InsertionPoint (int len, EngineOutputData *ed)
386 {
387         int i, offs = 0, newScore = ed->score, n = ed->which;
388
389         if(ed->nodes == 0 && ed->score == 0 && ed->time == 0)
390                 newScore = 1e6; // info lines inserted on top
391         if(ed->depth != curDepth[n]) { // depth has changed
392                 curDepth[n] = ed->depth;
393                 nrVariations[n] = 0; // throw away everything we had
394         }
395         // loop through all lines. Note even / odd used for different panes
396         for(i=nrVariations[n]-2; i>=0; i-=2) {
397                 // put new item behind those we haven't looked at
398                 offs = textEnd[i+n];
399                 textEnd[i+n+2] = offs + len;
400                 scores[i+n+2] = newScore;
401                 if(newScore < scores[i+n]) break;
402                 // if it had higher score as previous, move previous in stead
403                 scores[i+n+2] = scores[i+n];
404                 textEnd[i+n+2] = textEnd[i+n] + len;
405         }
406         if(i<0) {
407                 offs = 0;
408                 textEnd[n] = offs + len;
409                 scores[n] = newScore;
410         }
411         nrVariations[n] += 2;
412       return offs + (gameMode == AnalyzeMode)*strlen(header);
413 }
414
415
416 // pure back end, now SetWindowText is called via wrapper DoSetWindowText
417 static void
418 UpdateControls (EngineOutputData *ed)
419 {
420 //    int isPondering = FALSE;
421
422     char s_label[MAX_NAME_LENGTH + 32];
423     int h;
424     char * name = ed->name;
425
426     /* Label */
427     if( name == 0 || *name == '\0' ) {
428         name = "?";
429     }
430
431     strncpy( s_label, name, MAX_NAME_LENGTH );
432     s_label[ MAX_NAME_LENGTH-1 ] = '\0';
433
434 #ifdef SHOW_PONDERING
435     if( IsEnginePondering( ed->which ) ) {
436         char buf[8];
437
438         buf[0] = '\0';
439
440         if( ed->hint != 0 && *ed->hint != '\0' ) {
441             strncpy( buf, ed->hint, sizeof(buf) );
442             buf[sizeof(buf)-1] = '\0';
443         }
444         else if( ed->pv != 0 && *ed->pv != '\0' ) {
445             char * sep = strchr( ed->pv, ' ' );
446             int buflen = sizeof(buf);
447
448             if( sep != NULL ) {
449                 buflen = sep - ed->pv + 1;
450                 if( buflen > sizeof(buf) ) buflen = sizeof(buf);
451             }
452
453             strncpy( buf, ed->pv, buflen );
454             buf[ buflen-1 ] = '\0';
455         }
456
457         SetEngineState( ed->which, STATE_PONDERING, buf );
458     }
459     else if( gameMode == TwoMachinesPlay ) {
460         SetEngineState( ed->which, STATE_THINKING, "" );
461     }
462     else if( gameMode == AnalyzeMode || gameMode == AnalyzeFile
463           || (gameMode == IcsObserving && appData.icsEngineAnalyze)) { // [HGM] ICS-analyze
464         char buf[64];
465         int time_secs = ed->time / 100;
466         int time_mins = time_secs / 60;
467
468         buf[0] = '\0';
469
470         if( ed->an_move_index != 0 && ed->an_move_count != 0 && *ed->hint != '\0' ) {
471             char mov[16];
472
473             strncpy( mov, ed->hint, sizeof(mov) );
474             mov[ sizeof(mov)-1 ] = '\0';
475
476             snprintf( buf, sizeof(buf)/sizeof(buf[0]), "[%d] %d/%d: %s [%02d:%02d:%02d]", ed->depth, ed->an_move_index,
477                         ed->an_move_count, mov, time_mins / 60, time_mins % 60, time_secs % 60 );
478         }
479
480         SetEngineState( ed->which, STATE_ANALYZING, buf );
481     }
482     else {
483         SetEngineState( ed->which, STATE_IDLE, "" );
484     }
485 #endif
486
487     DoSetWindowText( ed->which, nLabel, s_label );
488
489     s_label[0] = '\0';
490
491     if( ed->time > 0 && ed->nodes > 0 ) {
492         unsigned long nps_100 = ed->nodes / ed->time;
493
494         if( nps_100 < 100000 ) {
495           snprintf( s_label, sizeof(s_label)/sizeof(s_label[0]), "NPS: %lu", nps_100 * 100 );
496         }
497         else {
498           snprintf( s_label, sizeof(s_label)/sizeof(s_label[0]), "NPS: %.1fk", nps_100 / 10.0 );
499         }
500     }
501
502     DoSetWindowText( ed->which, nLabelNPS, s_label );
503
504     /* Memo */
505     if( ed->pv != 0 && *ed->pv != '\0' ) {
506         char s_nodes[24];
507         char s_score[16];
508         char s_time[24];
509         char buf[256];
510         int buflen;
511         int time_secs = ed->time / 100;
512         int time_cent = ed->time % 100;
513
514         /* Nodes */
515         if( ed->nodes < 1000000 ) {
516             snprintf( s_nodes, sizeof(s_nodes)/sizeof(s_nodes[0]), u64Display, ed->nodes );
517         }
518         else {
519             snprintf( s_nodes, sizeof(s_nodes)/sizeof(s_nodes[0]), "%.1fM", u64ToDouble(ed->nodes) / 1000000.0 );
520         }
521
522         /* Score */
523         h = ((gameMode == AnalyzeMode && appData.whitePOV || appData.scoreWhite) && !WhiteOnMove(currentMove) ? -1 : 1) * ed->score;
524         if( h > 0 ) {
525           snprintf( s_score, sizeof(s_score)/sizeof(s_score[0]), "+%.2f", h / 100.0 );
526         }
527         else {
528           snprintf( s_score, sizeof(s_score)/sizeof(s_score[0]), "%.2f", h / 100.0 );
529         }
530
531         /* Time */
532         snprintf( s_time, sizeof(s_time)/sizeof(s_time[0]), "%d:%02d.%02d", time_secs / 60, time_secs % 60, time_cent );
533
534         /* Put all together... */
535         if(ed->nodes == 0 && ed->score == 0 && ed->time == 0)
536           snprintf( buf, sizeof(buf)/sizeof(buf[0]), "%3d\t", ed->depth );
537         else
538           snprintf( buf, sizeof(buf)/sizeof(buf[0]), "%3d\t%s\t%s\t%s\t", ed->depth, s_score, s_nodes, s_time );
539
540         /* Add PV */
541         buflen = strlen(buf);
542
543         strncpy( buf + buflen, ed->pv, sizeof(buf) - buflen );
544
545         buf[ sizeof(buf) - 3 ] = '\0';
546
547         strcat( buf + buflen, "\r\n" );
548
549         /* Update memo */
550         InsertIntoMemo( ed->which, buf, InsertionPoint(strlen(buf), ed) );
551         strncpy(lastLine[ed->which], buf, MSG_SIZ);
552     }
553
554     /* Colors */
555     SetEngineColorIcon( ed->which );
556 }
557
558 // [HGM] kibitz: write kibitz line; split window for it if necessary
559 void
560 OutputKibitz (int window, char *text)
561 {
562         static int currentLineEnd[2];
563         int where = 0;
564         if(!EngineOutputIsUp()) return;
565         if(!opponentKibitzes) { // on first kibitz of game, clear memos
566             DoClearMemo(1); currentLineEnd[1] = 0;
567             if(gameMode == IcsObserving) { DoClearMemo(0); currentLineEnd[0] = 0; }
568         }
569         opponentKibitzes = TRUE; // this causes split window DisplayMode in ICS modes.
570         VerifyDisplayMode();
571         strncpy(text+strlen(text)-1, "\r\n",sizeof(text+strlen(text)-1)); // to not lose line breaks on copying
572         if(gameMode == IcsObserving) {
573             DoSetWindowText(0, nLabel, gameInfo.white);
574             SetIcon( 0, nColorIcon,  nColorWhite);
575             SetIcon( 0, nStateIcon,  nClear);
576         }
577         DoSetWindowText(1, nLabel, gameMode == IcsPlayingBlack ? gameInfo.white : gameInfo.black); // opponent name
578         SetIcon( 1, nColorIcon,  gameMode == IcsPlayingBlack ? nColorWhite : nColorBlack);
579         SetIcon( 1, nStateIcon,  nClear);
580         if(strstr(text, "\\  ") == text) where = currentLineEnd[window-1]; // continuation line
581 //if(appData.debugMode) fprintf(debugFP, "insert '%s' at %d (end = %d,%d)\n", text, where, currentLineEnd[0], currentLineEnd[1]);
582         InsertIntoMemo(window-1, text, where); // [HGM] multivar: always at top
583         currentLineEnd[window-1] = where + strlen(text);
584 }