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