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