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