Fix translation of EngineOutputTitle WB
[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 && (multi = MultiPV(&first)) >= 0) {
224             snprintf(header, MSG_SIZ, "\t%s viewpoint\t\tfewer / Multi-PV setting = %d / more\n",
225                                        appData.whitePOV || appData.scoreWhite ? "white" : "mover", first.option[multi].value);
226             InsertIntoMemo( which, header, 0);
227         } else
228         if(appData.ponderNextMove && lastLine[which][0]) {
229             InsertIntoMemo( which, lastLine[which], 0 );
230             InsertIntoMemo( which, "\n", 0 );
231         }
232     }
233
234     /* Update */
235     lastDepth[which] = depth == 1 && ed.nodes == 0 ? 0 : depth; // [HGM] info-line kudge
236     lastForwardMostMove[which] = forwardMostMove;
237
238     UpdateControls( &ed );
239 }
240
241 #define ENGINE_COLOR_WHITE      'w'
242 #define ENGINE_COLOR_BLACK      'b'
243 #define ENGINE_COLOR_UNKNOWN    ' '
244
245 // pure back end
246 static char
247 GetEngineColor (int which)
248 {
249     char result = ENGINE_COLOR_UNKNOWN;
250
251     if( which == 0 || which == 1 ) {
252         ChessProgramState * cps;
253
254         switch (gameMode) {
255         case MachinePlaysBlack:
256         case IcsPlayingBlack:
257             result = ENGINE_COLOR_BLACK;
258             break;
259         case MachinePlaysWhite:
260         case IcsPlayingWhite:
261             result = ENGINE_COLOR_WHITE;
262             break;
263         case AnalyzeMode:
264         case AnalyzeFile:
265             result = WhiteOnMove(forwardMostMove) ? ENGINE_COLOR_WHITE : ENGINE_COLOR_BLACK;
266             break;
267         case TwoMachinesPlay:
268             cps = (which == 0) ? &first : &second;
269             result = cps->twoMachinesColor[0];
270             result = result == 'w' ? ENGINE_COLOR_WHITE : ENGINE_COLOR_BLACK;
271             break;
272         default: ; // does not happen, but suppresses pedantic warnings
273         }
274     }
275
276     return result;
277 }
278
279 // pure back end
280 static char
281 GetActiveEngineColor ()
282 {
283     char result = ENGINE_COLOR_UNKNOWN;
284
285     if( gameMode == TwoMachinesPlay ) {
286         result = WhiteOnMove(forwardMostMove) ? ENGINE_COLOR_WHITE : ENGINE_COLOR_BLACK;
287     }
288
289     return result;
290 }
291
292 // pure back end
293 static int
294 IsEnginePondering (int which)
295 {
296     int result = FALSE;
297
298     switch (gameMode) {
299     case MachinePlaysBlack:
300     case IcsPlayingBlack:
301         if( WhiteOnMove(forwardMostMove) ) result = TRUE;
302         break;
303     case MachinePlaysWhite:
304     case IcsPlayingWhite:
305         if( ! WhiteOnMove(forwardMostMove) ) result = TRUE;
306         break;
307     case TwoMachinesPlay:
308         if( GetActiveEngineColor() != ENGINE_COLOR_UNKNOWN ) {
309             if( GetEngineColor( which ) != GetActiveEngineColor() ) result = TRUE;
310         }
311         break;
312     default: ; // does not happen, but suppresses pedantic warnings
313     }
314
315     return result;
316 }
317
318 // back end
319 static void
320 SetDisplayMode (int mode)
321 {
322     if( windowMode != mode ) {
323         windowMode = mode;
324
325         ResizeWindowControls( mode );
326     }
327 }
328
329 // pure back end
330 static void
331 VerifyDisplayMode ()
332 {
333     int mode;
334
335     /* Get proper mode for current game */
336     switch( gameMode ) {
337     case IcsObserving:    // [HGM] ICS analyze
338         if(!appData.icsEngineAnalyze) return;
339     case AnalyzeMode:
340     case AnalyzeFile:
341     case MachinePlaysWhite:
342     case MachinePlaysBlack:
343         mode = 0;
344         break;
345     case IcsPlayingWhite:
346     case IcsPlayingBlack:
347         mode = appData.zippyPlay && opponentKibitzes; // [HGM] kibitz
348         break;
349     case TwoMachinesPlay:
350         mode = 1;
351         break;
352     default:
353         /* Do not change */
354         return;
355     }
356
357     SetDisplayMode( mode );
358 }
359
360 // back end. Determine what icon to set in the color-icon field, and print it
361 void
362 SetEngineColorIcon (int which)
363 {
364     char color = GetEngineColor(which);
365     int nicon = 0;
366
367     if( color == ENGINE_COLOR_BLACK )
368         nicon = nColorBlack;
369     else if( color == ENGINE_COLOR_WHITE )
370         nicon = nColorWhite;
371     else
372         nicon = nColorUnknown;
373
374     SetIcon( which, nColorIcon, nicon );
375 }
376
377 #define MAX_NAME_LENGTH 32
378
379 // [HGM] multivar: sort Thinking Output within one depth on score
380
381 static int
382 InsertionPoint (int len, EngineOutputData *ed)
383 {
384         int i, offs = 0, newScore = ed->score, n = ed->which;
385
386         if(ed->nodes == 0 && ed->score == 0 && ed->time == 0)
387                 newScore = 1e6; // info lines inserted on top
388         if(ed->depth != curDepth[n]) { // depth has changed
389                 curDepth[n] = ed->depth;
390                 nrVariations[n] = 0; // throw away everything we had
391         }
392         // loop through all lines. Note even / odd used for different panes
393         for(i=nrVariations[n]-2; i>=0; i-=2) {
394                 // put new item behind those we haven't looked at
395                 offs = textEnd[i+n];
396                 textEnd[i+n+2] = offs + len;
397                 scores[i+n+2] = newScore;
398                 if(newScore < scores[i+n]) break;
399                 // if it had higher score as previous, move previous in stead
400                 scores[i+n+2] = scores[i+n];
401                 textEnd[i+n+2] = textEnd[i+n] + len;
402         }
403         if(i<0) {
404                 offs = 0;
405                 textEnd[n] = offs + len;
406                 scores[n] = newScore;
407         }
408         nrVariations[n] += 2;
409       return offs + (gameMode == AnalyzeMode)*strlen(header);
410 }
411
412
413 // pure back end, now SetWindowText is called via wrapper DoSetWindowText
414 static void
415 UpdateControls (EngineOutputData *ed)
416 {
417 //    int isPondering = FALSE;
418
419     char s_label[MAX_NAME_LENGTH + 32];
420     int h;
421     char * name = ed->name;
422
423     /* Label */
424     if( name == 0 || *name == '\0' ) {
425         name = "?";
426     }
427
428     strncpy( s_label, name, MAX_NAME_LENGTH );
429     s_label[ MAX_NAME_LENGTH-1 ] = '\0';
430
431 #ifdef SHOW_PONDERING
432     if( IsEnginePondering( ed->which ) ) {
433         char buf[8];
434
435         buf[0] = '\0';
436
437         if( ed->hint != 0 && *ed->hint != '\0' ) {
438             strncpy( buf, ed->hint, sizeof(buf) );
439             buf[sizeof(buf)-1] = '\0';
440         }
441         else if( ed->pv != 0 && *ed->pv != '\0' ) {
442             char * sep = strchr( ed->pv, ' ' );
443             int buflen = sizeof(buf);
444
445             if( sep != NULL ) {
446                 buflen = sep - ed->pv + 1;
447                 if( buflen > sizeof(buf) ) buflen = sizeof(buf);
448             }
449
450             strncpy( buf, ed->pv, buflen );
451             buf[ buflen-1 ] = '\0';
452         }
453
454         SetEngineState( ed->which, STATE_PONDERING, buf );
455     }
456     else if( gameMode == TwoMachinesPlay ) {
457         SetEngineState( ed->which, STATE_THINKING, "" );
458     }
459     else if( gameMode == AnalyzeMode || gameMode == AnalyzeFile
460           || (gameMode == IcsObserving && appData.icsEngineAnalyze)) { // [HGM] ICS-analyze
461         char buf[64];
462         int time_secs = ed->time / 100;
463         int time_mins = time_secs / 60;
464
465         buf[0] = '\0';
466
467         if( ed->an_move_index != 0 && ed->an_move_count != 0 && *ed->hint != '\0' ) {
468             char mov[16];
469
470             strncpy( mov, ed->hint, sizeof(mov) );
471             mov[ sizeof(mov)-1 ] = '\0';
472
473             snprintf( buf, sizeof(buf)/sizeof(buf[0]), "[%d] %d/%d: %s [%02d:%02d:%02d]", ed->depth, ed->an_move_index,
474                         ed->an_move_count, mov, time_mins / 60, time_mins % 60, time_secs % 60 );
475         }
476
477         SetEngineState( ed->which, STATE_ANALYZING, buf );
478     }
479     else {
480         SetEngineState( ed->which, STATE_IDLE, "" );
481     }
482 #endif
483
484     DoSetWindowText( ed->which, nLabel, s_label );
485
486     s_label[0] = '\0';
487
488     if( ed->time > 0 && ed->nodes > 0 ) {
489         unsigned long nps_100 = ed->nodes / ed->time;
490
491         if( nps_100 < 100000 ) {
492           snprintf( s_label, sizeof(s_label)/sizeof(s_label[0]), "NPS: %lu", nps_100 * 100 );
493         }
494         else {
495           snprintf( s_label, sizeof(s_label)/sizeof(s_label[0]), "NPS: %.1fk", nps_100 / 10.0 );
496         }
497     }
498
499     DoSetWindowText( ed->which, nLabelNPS, s_label );
500
501     /* Memo */
502     if( ed->pv != 0 && *ed->pv != '\0' ) {
503         char s_nodes[24];
504         char s_score[16];
505         char s_time[24];
506         char buf[256];
507         int buflen;
508         int time_secs = ed->time / 100;
509         int time_cent = ed->time % 100;
510
511         /* Nodes */
512         if( ed->nodes < 1000000 ) {
513             snprintf( s_nodes, sizeof(s_nodes)/sizeof(s_nodes[0]), u64Display, ed->nodes );
514         }
515         else {
516             snprintf( s_nodes, sizeof(s_nodes)/sizeof(s_nodes[0]), "%.1fM", u64ToDouble(ed->nodes) / 1000000.0 );
517         }
518
519         /* Score */
520         h = ((gameMode == AnalyzeMode && appData.whitePOV || appData.scoreWhite) && !WhiteOnMove(currentMove) ? -1 : 1) * ed->score;
521         if( h > 0 ) {
522           snprintf( s_score, sizeof(s_score)/sizeof(s_score[0]), "+%.2f", h / 100.0 );
523         }
524         else {
525           snprintf( s_score, sizeof(s_score)/sizeof(s_score[0]), "%.2f", h / 100.0 );
526         }
527
528         /* Time */
529         snprintf( s_time, sizeof(s_time)/sizeof(s_time[0]), "%d:%02d.%02d", time_secs / 60, time_secs % 60, time_cent );
530
531         /* Put all together... */
532         if(ed->nodes == 0 && ed->score == 0 && ed->time == 0)
533           snprintf( buf, sizeof(buf)/sizeof(buf[0]), "%3d\t", ed->depth );
534         else
535           snprintf( buf, sizeof(buf)/sizeof(buf[0]), "%3d\t%s\t%s\t%s\t", ed->depth, s_score, s_nodes, s_time );
536
537         /* Add PV */
538         buflen = strlen(buf);
539
540         strncpy( buf + buflen, ed->pv, sizeof(buf) - buflen );
541
542         buf[ sizeof(buf) - 3 ] = '\0';
543
544         strcat( buf + buflen, "\r\n" );
545
546         /* Update memo */
547         InsertIntoMemo( ed->which, buf, InsertionPoint(strlen(buf), ed) );
548         strncpy(lastLine[ed->which], buf, MSG_SIZ);
549     }
550
551     /* Colors */
552     SetEngineColorIcon( ed->which );
553 }
554
555 // [HGM] kibitz: write kibitz line; split window for it if necessary
556 void
557 OutputKibitz (int window, char *text)
558 {
559         static int currentLineEnd[2];
560         int where = 0;
561         if(!EngineOutputIsUp()) return;
562         if(!opponentKibitzes) { // on first kibitz of game, clear memos
563             DoClearMemo(1); currentLineEnd[1] = 0;
564             if(gameMode == IcsObserving) { DoClearMemo(0); currentLineEnd[0] = 0; }
565         }
566         opponentKibitzes = TRUE; // this causes split window DisplayMode in ICS modes.
567         VerifyDisplayMode();
568         strncpy(text+strlen(text)-1, "\r\n",sizeof(text+strlen(text)-1)); // to not lose line breaks on copying
569         if(gameMode == IcsObserving) {
570             DoSetWindowText(0, nLabel, gameInfo.white);
571             SetIcon( 0, nColorIcon,  nColorWhite);
572             SetIcon( 0, nStateIcon,  nClear);
573         }
574         DoSetWindowText(1, nLabel, gameMode == IcsPlayingBlack ? gameInfo.white : gameInfo.black); // opponent name
575         SetIcon( 1, nColorIcon,  gameMode == IcsPlayingBlack ? nColorWhite : nColorBlack);
576         SetIcon( 1, nStateIcon,  nClear);
577         if(strstr(text, "\\  ") == text) where = currentLineEnd[window-1]; // continuation line
578 //if(appData.debugMode) fprintf(debugFP, "insert '%s' at %d (end = %d,%d)\n", text, where, currentLineEnd[0], currentLineEnd[1]);
579         InsertIntoMemo(window-1, text, where); // [HGM] multivar: always at top
580         currentLineEnd[window-1] = where + strlen(text);
581 }