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