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