Add support for Multi-PV Margin
[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, 2013, 2014, 2015 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 #include <ctype.h>
34
35 #if STDC_HEADERS
36 # include <stdlib.h>
37 # include <string.h>
38 #else /* not STDC_HEADERS */
39 # if HAVE_STRING_H
40 #  include <string.h>
41 # else /* not HAVE_STRING_H */
42 #  include <strings.h>
43 # endif /* not HAVE_STRING_H */
44 #endif /* not STDC_HEADERS */
45
46 #include "common.h"
47 #include "frontend.h"
48 #include "backend.h"
49 #include "moves.h"
50 #include "engineoutput.h"
51 #include "gettext.h"
52
53 #ifdef ENABLE_NLS
54 # define  _(s) gettext (s)
55 # define N_(s) gettext_noop (s)
56 #else
57 # ifdef WIN32
58 #  define  _(s) T_(s)
59 #  undef  ngettext
60 #  define  ngettext(s,p,n) T_(p)
61 # else
62 #  define  _(s) (s)
63 # endif
64 # define N_(s)  s
65 #endif
66
67 typedef struct {
68     char * name;
69     int which;
70     int depth;
71     u64 nodes;
72     int score;
73     int time;
74     char * pv;
75     char * hint;
76     int an_move_index;
77     int an_move_count;
78     int moveKey;
79 } EngineOutputData;
80
81 // called by other front-end
82 void EngineOutputUpdate( FrontEndProgramStats * stats );
83 void OutputKibitz(int window, char *text);
84
85 // module back-end routines
86 static void VerifyDisplayMode();
87 static void UpdateControls( EngineOutputData * ed );
88
89 static int  lastDepth[2] = { -1, -1 };
90 static int  lastForwardMostMove[2] = { -1, -1 };
91 static int  engineState[2] = { -1, -1 };
92 static char lastLine[2][MSG_SIZ];
93 static char header[2][MSG_SIZ];
94 static char columnHeader[MSG_SIZ] = "dep\tscore\tnodes\ttime\t(not shown:  tbhits\tknps\tseldep)\n";
95 static int  columnMask = 0xF0;
96
97 #define MAX_VAR 400
98 static int scores[MAX_VAR], textEnd[MAX_VAR], keys[MAX_VAR], curDepth[2], nrVariations[2];
99 static char fail[MAX_VAR];
100
101 extern int initialRulePlies;
102
103 void
104 MakeEngineOutputTitle ()
105 {
106         static char buf[MSG_SIZ];
107         static char oldTitle[MSG_SIZ];
108         char title[MSG_SIZ];
109         int count, rule = 2*appData.ruleMoves;
110
111         snprintf(title, MSG_SIZ, _("Engine Output") );
112
113         if(!EngineOutputIsUp()) return;
114         // figure out value of 50-move counter
115         count = currentMove;
116         while( (signed char)boards[count][EP_STATUS] <= EP_NONE && count > backwardMostMove ) count--;
117         if( count == backwardMostMove ) count -= initialRulePlies;
118         count = currentMove - count;
119         if(!rule) rule = 100;
120         if(count >= rule - 40 && (!appData.icsActive || gameMode == IcsObserving || appData.zippyPlay)) {
121                 snprintf(buf, MSG_SIZ, ngettext("%s (%d reversible ply)", "%s (%d reversible plies)", count), title, count);
122                 safeStrCpy(title, buf, MSG_SIZ);
123         }
124         if(!strcmp(oldTitle, title)) return;
125         safeStrCpy(oldTitle, title, MSG_SIZ);
126         SetEngineOutputTitle(title);
127 }
128
129 // back end, due to front-end wrapper for SetWindowText, and new SetIcon arguments
130 void
131 SetEngineState (int which, enum ENGINE_STATE state, char * state_data)
132 {
133     int x_which = 1 - which;
134
135     if( engineState[ which ] != state ) {
136         engineState[ which ] = state;
137
138         switch( state ) {
139         case STATE_THINKING:
140             SetIcon( which, nStateIcon, nThinking );
141             if( engineState[ x_which ] == STATE_THINKING ) {
142                 SetEngineState( x_which, STATE_IDLE, "" );
143             }
144             break;
145         case STATE_PONDERING:
146             SetIcon( which, nStateIcon, nPondering );
147             break;
148         case STATE_ANALYZING:
149             SetIcon( which, nStateIcon, nAnalyzing );
150             break;
151         default:
152             SetIcon( which, nStateIcon, nClear );
153             break;
154         }
155     }
156
157     if( state_data != 0 ) {
158         DoSetWindowText( which, nStateData, state_data );
159     }
160 }
161
162 // back end, now the front-end wrapper ClearMemo is used, and ed no longer contains handles.
163 void
164 SetProgramStats (FrontEndProgramStats * stats) // now directly called by back-end
165 {
166     EngineOutputData ed;
167     int clearMemo = FALSE;
168     int which, depth, multi;
169     ChessMove moveType;
170     int ff, ft, rf, rt;
171     char pc;
172
173     if( stats == 0 ) {
174         SetEngineState( 0, STATE_IDLE, "" );
175         SetEngineState( 1, STATE_IDLE, "" );
176         return;
177     }
178
179     if(gameMode == IcsObserving && !appData.icsEngineAnalyze)
180         return; // [HGM] kibitz: shut up engine if we are observing an ICS game
181
182     which = stats->which;
183     depth = stats->depth;
184
185     if( which < 0 || which > 1 || depth < 0 || stats->time < 0 || stats->pv == 0 ) {
186         return;
187     }
188
189     if( !EngineOutputDialogExists() ) {
190         return;
191     }
192
193     VerifyDisplayMode();
194
195     ed.which = which;
196     ed.depth = depth;
197     ed.nodes = stats->nodes;
198     ed.score = stats->score;
199     ed.time = stats->time;
200     ed.pv = stats->pv;
201     ed.hint = stats->hint;
202     ed.an_move_index = stats->an_move_index;
203     ed.an_move_count = stats->an_move_count;
204
205     /* Get target control. [HGM] this is moved to front end, which get them from a table */
206     if( which == 0 ) {
207         ed.name = first.tidy;
208     }
209     else {
210         ed.name = second.tidy;
211     }
212
213     if( ed.pv != 0 && ed.pv[0] == ' ' ) {
214         if( strncmp( ed.pv, " no PV", 6 ) == 0 ) { /* Hack on hack! :-O */
215             ed.pv = "";
216         }
217     }
218
219     /* Clear memo if needed */
220     if( lastDepth[which] > depth || (lastDepth[which] == depth && depth <= 1 && ed.pv[0]) ) { // no reason to clear if we won't add line
221         clearMemo = TRUE;
222     }
223
224     if( lastForwardMostMove[which] != forwardMostMove ) {
225         clearMemo = TRUE;
226     }
227
228     if( clearMemo ) {
229         if(!appData.headers) columnHeader[0] = NULLCHAR;
230         DoClearMemo(which); nrVariations[which] = 0;
231         header[which][0] = NULLCHAR;
232         if(gameMode == AnalyzeMode) {
233           ChessProgramState *cps = (which ? &second : &first);
234           char *exclu = cps->excludeMoves ? exclusionHeader : "";
235           if((multi = MultiPV(cps, 3)) != -1) {
236             char *s = "setting";
237             if(multi < -1) multi = -2 - multi, s = "margin";
238             snprintf(header[which], MSG_SIZ, "\t%s viewpoint\t\tfewer / Multi-PV %s = %d / more\n",
239                                        appData.whitePOV || appData.scoreWhite ? "white" : "mover", s, cps->option[multi].value);
240           }
241           if(!which) snprintf(header[which]+strlen(header[which]), MSG_SIZ-strlen(header[which]), "%s%s", exclu, columnHeader);
242           InsertIntoMemo( which, header[which], 0);
243         } else {
244           snprintf(header[which], MSG_SIZ, "%s", columnHeader);
245           if(appData.ponderNextMove && lastLine[which][0]) {
246             InsertIntoMemo( which, lastLine[which], 0 );
247             InsertIntoMemo( which, "\n", 0 );
248           }
249           InsertIntoMemo( which, header[which], 0);
250         }
251     }
252
253     if(ed.pv && ed.pv[0] && ParseOneMove(ed.pv, currentMove, &moveType, &ff, &rf, &ft, &rt, &pc))
254         ed.moveKey = (ff<<24 | rf << 16 | ft << 8 | rt) ^ pc*87161;
255     else ed.moveKey = ed.nodes; // kludge to get unique key unlikely to match any move
256
257     /* Update */
258     lastDepth[which] = depth == 1 && ed.nodes == 0 ? 0 : depth; // [HGM] info-line kudge
259     lastForwardMostMove[which] = forwardMostMove;
260
261     UpdateControls( &ed );
262 }
263
264 #define ENGINE_COLOR_WHITE      'w'
265 #define ENGINE_COLOR_BLACK      'b'
266 #define ENGINE_COLOR_UNKNOWN    ' '
267
268 // pure back end
269 static char
270 GetEngineColor (int which)
271 {
272     char result = ENGINE_COLOR_UNKNOWN;
273
274     if( which == 0 || which == 1 ) {
275         ChessProgramState * cps;
276
277         switch (gameMode) {
278         case MachinePlaysBlack:
279         case IcsPlayingBlack:
280             result = ENGINE_COLOR_BLACK;
281             break;
282         case MachinePlaysWhite:
283         case IcsPlayingWhite:
284             result = ENGINE_COLOR_WHITE;
285             break;
286         case AnalyzeMode:
287         case AnalyzeFile:
288             result = WhiteOnMove(forwardMostMove) ? ENGINE_COLOR_WHITE : ENGINE_COLOR_BLACK;
289             break;
290         case TwoMachinesPlay:
291             cps = (which == 0) ? &first : &second;
292             result = cps->twoMachinesColor[0];
293             result = result == 'w' ? ENGINE_COLOR_WHITE : ENGINE_COLOR_BLACK;
294             break;
295         default: ; // does not happen, but suppresses pedantic warnings
296         }
297     }
298
299     return result;
300 }
301
302 // pure back end
303 static char
304 GetActiveEngineColor ()
305 {
306     char result = ENGINE_COLOR_UNKNOWN;
307
308     if( gameMode == TwoMachinesPlay ) {
309         result = WhiteOnMove(forwardMostMove) ? ENGINE_COLOR_WHITE : ENGINE_COLOR_BLACK;
310     }
311
312     return result;
313 }
314
315 // pure back end
316 static int
317 IsEnginePondering (int which)
318 {
319     int result = FALSE;
320
321     switch (gameMode) {
322     case MachinePlaysBlack:
323     case IcsPlayingBlack:
324         if( WhiteOnMove(forwardMostMove) ) result = TRUE;
325         break;
326     case MachinePlaysWhite:
327     case IcsPlayingWhite:
328         if( ! WhiteOnMove(forwardMostMove) ) result = TRUE;
329         break;
330     case TwoMachinesPlay:
331         if( GetActiveEngineColor() != ENGINE_COLOR_UNKNOWN ) {
332             if( GetEngineColor( which ) != GetActiveEngineColor() ) result = TRUE;
333         }
334         break;
335     default: ; // does not happen, but suppresses pedantic warnings
336     }
337
338     return result;
339 }
340
341 // back end
342 static void
343 SetDisplayMode (int mode)
344 {
345     if( windowMode != mode ) {
346         windowMode = mode;
347
348         ResizeWindowControls( mode );
349     }
350 }
351
352 // pure back end
353 static void
354 VerifyDisplayMode ()
355 {
356     int mode;
357
358     /* Get proper mode for current game */
359     switch( gameMode ) {
360     case IcsObserving:    // [HGM] ICS analyze
361         if(!appData.icsEngineAnalyze) return;
362     case AnalyzeFile:
363     case MachinePlaysWhite:
364     case MachinePlaysBlack:
365         mode = 0;
366         break;
367     case AnalyzeMode:
368         mode = second.analyzing;
369         break;
370     case IcsPlayingWhite:
371     case IcsPlayingBlack:
372         mode = appData.zippyPlay && opponentKibitzes; // [HGM] kibitz
373         break;
374     case TwoMachinesPlay:
375         mode = 1;
376         break;
377     default:
378         /* Do not change */
379         return;
380     }
381
382     SetDisplayMode( mode );
383 }
384
385 // back end. Determine what icon to set in the color-icon field, and print it
386 void
387 SetEngineColorIcon (int which)
388 {
389     char color = GetEngineColor(which);
390     int nicon = 0;
391
392     if( color == ENGINE_COLOR_BLACK )
393         nicon = nColorBlack;
394     else if( color == ENGINE_COLOR_WHITE )
395         nicon = nColorWhite;
396     else
397         nicon = nColorUnknown;
398
399     SetIcon( which, nColorIcon, nicon );
400 }
401
402 #define MAX_NAME_LENGTH 32
403
404 // [HGM] multivar: sort Thinking Output within one depth on score
405
406 static int
407 MateFlip (int n)
408 {   // map mate-score to monotonous scale, so sorting compares them correctly
409     if(n >=  MATE_SCORE) return 2*MATE_SCORE - n;
410     if(n <= -MATE_SCORE) return -2*MATE_SCORE - n;
411     return n;
412 }
413
414 static int
415 InsertionPoint (int len, EngineOutputData *ed)
416 {
417         int i, offs = 0, newScore = ed->score, n = ed->which;
418         char failType;
419
420         if(ed->nodes == 0 && ed->score == 0 && ed->time == 0)
421                 newScore = 1e6; // info lines inserted on top
422         if(ed->depth != curDepth[n]) { // depth has changed
423                 curDepth[n] = ed->depth;
424                 nrVariations[n] = 0; // throw away everything we had
425         }
426         i = strlen(ed->pv); if(i > 0) i--;
427         failType = ed->pv[i];
428         if(failType != '?' && failType != '!') failType = ' ';
429         // loop through all lines. Note even / odd used for different panes
430         for(i=nrVariations[n]-2; i>=0; i-=2) {
431                 // put new item behind those we haven't looked at
432                 offs = textEnd[i+n];
433                 textEnd[i+n+2] = offs + len;
434                 scores[i+n+2] = newScore;
435                 keys[i+n+2] = ed->moveKey;
436                 fail[i+n+2] = failType;
437                 if(ed->moveKey != keys[i+n] && // same move always tops previous one (as a higher score must be a fail low)
438                    MateFlip(newScore) < MateFlip(scores[i+n]) && fail[i+n] == ' ') break;
439                 // if it had higher score as previous, move previous in stead
440                 scores[i+n+2] = ed->moveKey == keys[i+n] ? newScore : scores[i+n]; // correct scores of fail-low/high searches
441                 textEnd[i+n+2] = textEnd[i+n] + len;
442                 keys[i+n+2] = keys[i+n];
443                 fail[i+n+2] = fail[i+n];
444         }
445         if(i<0) {
446                 offs = 0;
447                 textEnd[n] = offs + len;
448                 scores[n] = newScore;
449                 keys[n] = ed->moveKey;
450                 fail[n] = failType;
451         }
452         nrVariations[n] += 2;
453       return offs + strlen(header[ed->which]);
454 }
455
456 static char spaces[] = "            "; // [HGM] align: spaces for padding
457
458 static void
459 Format(char *buf, int val)
460 { // [HGM] tbhits: print a positive integer with trailing whitespace to give it fixed width
461         if( val < 1000000 ) {
462             int h = val, i=0;
463             while(h > 0) h /= 10, i++;
464             snprintf( buf, 24, "%d%s\t", val, spaces + 2*i);
465         }
466         else {
467             char unit = 'M';
468             if(val >= 1e9) val /= 1e3, unit = 'G';
469             snprintf( buf, 24, "%.*f%c%s\t", 1 + (val < 1e7), val/1e6, unit, spaces + 10 + 2*(val >= 1e8));
470         }
471 }
472
473 // pure back end, now SetWindowText is called via wrapper DoSetWindowText
474 static void
475 UpdateControls (EngineOutputData *ed)
476 {
477 //    int isPondering = FALSE;
478
479     char s_label[MAX_NAME_LENGTH + 32];
480     int h;
481     char * name = ed->name;
482     char *q, *pvStart = ed->pv;
483
484     /* Label */
485     if( name == 0 || *name == '\0' ) {
486         name = "?";
487     }
488
489     strncpy( s_label, name, MAX_NAME_LENGTH );
490     s_label[ MAX_NAME_LENGTH-1 ] = '\0';
491
492     if(pvStart) { // [HGM] tbhits: plit up old PV into extra infos and real PV
493         while(strchr(pvStart, '\t')) { // locate last tab before non-int (real PV starts after that)
494             for(q=pvStart; isdigit(*q) || *q == ' '; q++);
495             if(*q != '\t') break;
496             pvStart = q + 1;
497         }
498     }
499
500 #ifdef SHOW_PONDERING
501     if( IsEnginePondering( ed->which ) ) {
502         char buf[12];
503
504         buf[0] = '\0';
505
506         if( ed->hint != 0 && *ed->hint != '\0' ) {
507             strncpy( buf, ed->hint, sizeof(buf) );
508             buf[sizeof(buf)-1] = '\0';
509         }
510         else if( pvStart != 0 && *pvStart != '\0' ) {
511             char * sep;
512             int buflen = sizeof(buf);
513
514             sep = strchr( pvStart, ' ' );
515             if( sep != NULL ) {
516                 buflen = sep - pvStart + 1;
517                 if( buflen > sizeof(buf) ) buflen = sizeof(buf);
518             }
519
520             strncpy( buf, pvStart, buflen );
521             buf[ buflen-1 ] = '\0';
522         }
523
524         SetEngineState( ed->which, STATE_PONDERING, buf );
525     }
526     else if( gameMode == TwoMachinesPlay ) {
527         SetEngineState( ed->which, STATE_THINKING, "" );
528     }
529     else if( gameMode == AnalyzeMode || gameMode == AnalyzeFile
530           || (gameMode == IcsObserving && appData.icsEngineAnalyze)) { // [HGM] ICS-analyze
531         char buf[64];
532         int time_secs = ed->time / 100;
533         int time_mins = time_secs / 60;
534
535         buf[0] = '\0';
536
537         if( ed->an_move_index != 0 && ed->an_move_count != 0 && *ed->hint != '\0' ) {
538             char mov[16];
539
540             strncpy( mov, ed->hint, sizeof(mov) );
541             mov[ sizeof(mov)-1 ] = '\0';
542
543             snprintf( buf, sizeof(buf)/sizeof(buf[0]), "[%d] %d/%d: %s [%02d:%02d:%02d]", ed->depth, ed->an_move_index,
544                         ed->an_move_count, mov, time_mins / 60, time_mins % 60, time_secs % 60 );
545         }
546
547         SetEngineState( ed->which, STATE_ANALYZING, buf );
548     }
549     else {
550         SetEngineState( ed->which, STATE_IDLE, "" );
551     }
552 #endif
553
554     DoSetWindowText( ed->which, nLabel, s_label );
555
556     s_label[0] = '\0';
557
558     if( ed->time > 0 && ed->nodes > 0 ) {
559         unsigned long nps_100 = ed->nodes / ed->time;
560
561         if( nps_100 < 100000 ) {
562           snprintf( s_label, sizeof(s_label)/sizeof(s_label[0]), "%s: %lu", _("NPS"), nps_100 * 100 );
563         }
564         else {
565           snprintf( s_label, sizeof(s_label)/sizeof(s_label[0]), "%s: %.1fk", _("NPS"), nps_100 / 10.0 );
566         }
567     }
568
569     DoSetWindowText( ed->which, nLabelNPS, s_label );
570
571     /* Memo */
572     if( pvStart != 0 && *pvStart != '\0' ) {
573         char s_nodes[24];
574         char s_score[16];
575         char s_time[24];
576         char s_hits[24];
577         char s_seld[24];
578         char s_knps[24];
579         char buf[256], fail;
580         int buflen, hits, i, params[5], extra;
581         int time_secs = ed->time / 100;
582         int time_cent = ed->time % 100;
583
584         /* Nodes */
585         if( ed->nodes < 1000000 ) {
586             int h = ed->nodes, i=0;
587             while(h > 0) h /= 10, i++; // [HGM] align: count digits; pad with 2 spaces for every missing digit
588             snprintf( s_nodes, sizeof(s_nodes)/sizeof(s_nodes[0]), u64Display "%s\t", ed->nodes, spaces + 2*i);
589         }
590         else {
591             double x = u64ToDouble(ed->nodes);
592             char unit = 'M';
593             if(x >= 1e9) x /= 1e3, unit = 'G';
594             snprintf( s_nodes, sizeof(s_nodes)/sizeof(s_nodes[0]), "%.*f%c%s\t", 1 + (x < 1e7), x / 1e6,
595                       unit, spaces + 10 + 2*(ed->nodes >= 1e8));
596         }
597
598         /* TB Hits etc. */
599         for(i=hits=0; i<5; i++) params[i] = 0;
600 //fprintf(stderr, "%s\n%s\n", ed->pv, pvStart);
601         if(pvStart != ed->pv) { // check if numbers before PV
602             strncpy(buf, ed->pv, 256); buf[pvStart - ed->pv] = NULLCHAR;
603             extra = sscanf(buf, "%d %d %d %d %d", params, params+1, params+2, params+3, params+4);
604 //fprintf(stderr, "extra=%d len=%d\n", extra, pvStart - ed->pv);
605             if(extra) hits = params[extra-1], params[extra-1] = 0; // last one is tbhits
606         }
607         Format(s_seld, params[0]); Format(s_knps, params[1]); Format(s_hits, hits); 
608
609         if(*ed->pv) fail = ed->pv[strlen(ed->pv)-1]; else fail = ' ';
610         if(fail != '?' && fail != '!') fail = ' ';
611
612         /* Score */
613         h = ((gameMode == AnalyzeMode && appData.whitePOV || appData.scoreWhite) && !WhiteOnMove(currentMove) ? -1 : 1) * ed->score;
614         if( h == 0 ) {
615           snprintf( s_score, sizeof(s_score)/sizeof(s_score[0]), "  0.00%c\t", fail );
616         } else
617         if( h >= MATE_SCORE) snprintf(s_score, 16, "  %s#%d%c\t", ( h > MATE_SCORE+9 ? "" : "  "),  h - MATE_SCORE, fail ); else
618         if(-h >= MATE_SCORE) snprintf(s_score, 16, " %s#-%d%c\t", (-h > MATE_SCORE+9 ? "" : "  "), -h - MATE_SCORE, fail ); else
619         if( h > 0 ) {
620           snprintf( s_score, sizeof(s_score)/sizeof(s_score[0]), "+%.2f%c\t", h / 100.0, fail );
621         }
622         else {
623           snprintf( s_score, sizeof(s_score)/sizeof(s_score[0]), " %.2f%c\t", h / 100.0, fail );
624         }
625
626         /* Time */
627         if(time_secs >= 3600)
628             snprintf( s_time, sizeof(s_time)/sizeof(s_time[0]), "%d:%02d:%02d\t", time_secs / 3600, (time_secs / 60) % 60, time_secs % 60 );
629         else
630         snprintf( s_time, sizeof(s_time)/sizeof(s_time[0]), "%d:%02d.%02d\t", time_secs / 60, time_secs % 60, time_cent );
631
632         if(columnMask & 2) s_score[0] = NULLCHAR; // [HGM] hide: erase columns the user has hidden
633         if(columnMask & 4) s_nodes[0] = NULLCHAR;
634         if(columnMask & 8) s_time[0]  = NULLCHAR;
635         if(columnMask & 16) s_hits[0]  = NULLCHAR;
636         if(columnMask & 32) s_knps[0]  = NULLCHAR;
637         if(columnMask & 64) s_seld[0]  = NULLCHAR;
638
639         /* Put all together... */
640         if(ed->nodes == 0 && ed->score == 0 && ed->time == 0)
641           snprintf( buf, sizeof(buf)/sizeof(buf[0]), "%3d\t", ed->depth );
642         else
643           snprintf( buf, sizeof(buf)/sizeof(buf[0]), "%3d\t%s%s%s%s%s%s", ed->depth, s_score, s_nodes, s_time, s_hits, s_knps, s_seld );
644
645         /* Add PV */
646         buflen = strlen(buf);
647
648         strncpy( buf + buflen, pvStart, sizeof(buf) - buflen );
649
650         buf[ sizeof(buf) - 3 ] = '\0';
651
652         strcat( buf + buflen, "\r\n" );
653
654         /* Update memo */
655         InsertIntoMemo( ed->which, buf, InsertionPoint(strlen(buf), ed) );
656         strncpy(lastLine[ed->which], buf, MSG_SIZ);
657     }
658
659     /* Colors */
660     SetEngineColorIcon( ed->which );
661 }
662
663 static char *titles[] = { "score\t", "nodes\t", "time\t", "tbhits\t", "knps\t", "seldep\t" };
664
665 void
666 Collapse(int n)
667 {   // handle click on column headers, to hide / show them
668     int i, j, nr=0, m=~columnMask, Ncol=7;
669     for(i=0; columnHeader[i] && i<n; i++) nr += (columnHeader[i] == '\t');
670     if(!nr) return; // depth always shown, so clicks on it ignored
671     for(i=j=0; i<Ncol; i++) if(m & 1<<i) j++; // count hidden columns
672     if(nr < j) { // shown column clicked: hide it
673         for(i=j=0; i<Ncol; i++) if(m & 1<<i && j++ == nr) break;
674         columnMask |= 1<<i;
675     } else { // hidden column clicked: show it
676         m = ~m; nr -= j;
677         for(i=j=0; i<Ncol; i++) if(m & 1<<i && j++ == nr) break;
678         columnMask &= ~(1<<i);
679     }
680     // create new header line
681     strcpy(columnHeader, "dep\t");
682     m = ~columnMask;
683     for(i=j=1; i<Ncol; i++) if(m & 1<<i) strcat(columnHeader, titles[i-1]), j++;
684     if(j != Ncol) { // list hidden columns, so user ca click them
685         m = ~m; strcat(columnHeader, "(not shown:  ");
686         for(i=1; i<Ncol; i++) if(m & 1<<i) strcat(columnHeader, titles[i-1]);
687         strcat(columnHeader, ")");
688     }
689     strcat(columnHeader, "\n");
690 }
691
692 // [HGM] kibitz: write kibitz line; split window for it if necessary
693 void
694 OutputKibitz (int window, char *text)
695 {
696         static int currentLineEnd[2];
697         int where = 0;
698         if(!EngineOutputIsUp()) return;
699         if(!opponentKibitzes) { // on first kibitz of game, clear memos
700             DoClearMemo(1); currentLineEnd[1] = 0;
701             if(gameMode == IcsObserving) { DoClearMemo(0); currentLineEnd[0] = 0; }
702         }
703         opponentKibitzes = TRUE; // this causes split window DisplayMode in ICS modes.
704         VerifyDisplayMode();
705         strncpy(text+strlen(text)-1, "\r\n",sizeof(text+strlen(text)-1)); // to not lose line breaks on copying
706         if(gameMode == IcsObserving) {
707             DoSetWindowText(0, nLabel, gameInfo.white);
708             SetIcon( 0, nColorIcon,  nColorWhite);
709             SetIcon( 0, nStateIcon,  nClear);
710         }
711         DoSetWindowText(1, nLabel, gameMode == IcsPlayingBlack ? gameInfo.white : gameInfo.black); // opponent name
712         SetIcon( 1, nColorIcon,  gameMode == IcsPlayingBlack ? nColorWhite : nColorBlack);
713         SetIcon( 1, nStateIcon,  nClear);
714         if(strstr(text, "\\  ") == text) where = currentLineEnd[window-1]; // continuation line
715 //if(appData.debugMode) fprintf(debugFP, "insert '%s' at %d (end = %d,%d)\n", text, where, currentLineEnd[0], currentLineEnd[1]);
716         InsertIntoMemo(window-1, text, where); // [HGM] multivar: always at top
717         currentLineEnd[window-1] = where + strlen(text);
718 }