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