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