add DIFFSTAT and SHORTLOG to tar-ball
[xboard.git] / xengineoutput.c
1 /*
2  * Engine output (PV)
3  *
4  * Author: Alessandro Scotti (Dec 2005)
5  *
6  * Copyright 2005 Alessandro Scotti
7  *
8  * Enhancements Copyright 2009 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 #include "config.h"
29
30 #include <stdio.h>
31 #include <ctype.h>
32 #include <errno.h>
33 #include <sys/types.h>
34
35 #if STDC_HEADERS
36 # include <stdlib.h>
37 # include <string.h>
38 #else /* not STDC_HEADERS */
39 extern char *getenv();
40 # if HAVE_STRING_H
41 #  include <string.h>
42 # else /* not HAVE_STRING_H */
43 #  include <strings.h>
44 # endif /* not HAVE_STRING_H */
45 #endif /* not STDC_HEADERS */
46
47 #if HAVE_UNISTD_H
48 # include <unistd.h>
49 #endif
50
51 #include <X11/Intrinsic.h>
52 #include <X11/StringDefs.h>
53 #include <X11/Shell.h>
54 #include <X11/Xaw/Dialog.h>
55 #include <X11/Xaw/Form.h>
56 #include <X11/Xaw/List.h>
57 #include <X11/Xaw/Label.h>
58 #include <X11/Xaw/SimpleMenu.h>
59 #include <X11/Xaw/SmeBSB.h>
60 #include <X11/Xaw/SmeLine.h>
61 #include <X11/Xaw/Box.h>
62 #include <X11/Xaw/Paned.h>
63 #include <X11/Xaw/MenuButton.h>
64 #include <X11/cursorfont.h>
65 #include <X11/Xaw/Text.h>
66 #include <X11/Xaw/AsciiText.h>
67 #include <X11/Xaw/Viewport.h>
68
69 #include "common.h"
70 #include "frontend.h"
71 #include "backend.h"
72 #include "xboard.h"
73 // Add xengineo.h later
74 #include "gettext.h"
75
76 #ifdef ENABLE_NLS
77 # define  _(s) gettext (s)
78 # define N_(s) gettext_noop (s)
79 #else
80 # define  _(s) (s)
81 # define N_(s)  s
82 #endif
83
84 #include <X11/xpm.h>
85
86 // [HGM] pixmaps of some ICONS used in the engine-outut window
87 #include "pixmaps/WHITE_14.xpm"
88 #include "pixmaps/BLACK_14.xpm"
89 #include "pixmaps/CLEAR_14.xpm"
90 #include "pixmaps/UNKNOWN_14.xpm"
91 #include "pixmaps/THINKING_14.xpm"
92 #include "pixmaps/PONDER_14.xpm"
93 #include "pixmaps/ANALYZING_14.xpm"
94
95 #ifdef SNAP
96 #include "wsnap.h"
97 #endif
98
99 #define _LL_ 100
100
101 // imports from xboard.c
102 extern Widget formWidget, shellWidget, boardWidget, menuBarWidget;
103 extern Display *xDisplay;
104 extern Window xBoardWindow;
105 extern int squareSize;
106 extern Pixmap xMarkPixmap, wIconPixmap, bIconPixmap;
107 extern char *layoutName;
108
109 // temporary kludge to avoid compile errors untill all Windows code has been replaced
110 #define HICON int *
111 #define HWND  int *
112
113 // [HGM] define numbers to indicate icons, for referring to them in platform-independent way
114 #define nColorBlack   1
115 #define nColorWhite   2
116 #define nColorUnknown 3
117 #define nClear        4
118 #define nPondering    5
119 #define nThinking     6
120 #define nAnalyzing    7
121
122 Pixmap icons[8]; // [HGM] this front-end array translates back-end icon indicator to handle
123
124 // [HGM] same for output fields (note that there are two of each type, one per color)
125 #define nColorIcon 1
126 #define nStateIcon 2
127 #define nLabel     3
128 #define nStateData 4
129 #define nLabelNPS  5
130 #define nMemo      6
131
132 Widget outputField[2][7]; // [HGM] front-end array to translate output field to window handle
133
134 void EngineOutputPopDown();
135 void engineOutputPopUp();
136 int  EngineOutputIsUp();
137 static void SetEngineColorIcon( int which );
138
139 #define SHOW_PONDERING
140
141 /* Imports from backend.c */
142 char * SavePart(char *str);
143 extern int opponentKibitzes;
144
145 /* Imports from winboard.c */
146 //extern HWND engineOutputDialog;
147 extern Arg layoutArgs[2], formArgs[2], messageArgs[4];
148
149 //extern WindowPlacement wpEngineOutput;
150
151 Position engineOutputX = -1, engineOutputY = -1;
152 Dimension engineOutputW, engineOutputH;
153 Widget engineOutputShell;
154 int engineOutputDialogUp;
155
156 /* Module variables */
157 #define H_MARGIN            2
158 #define V_MARGIN            2
159 #define LABEL_V_DISTANCE    1   /* Distance between label and memo */
160 #define SPLITTER_SIZE       4   /* Distance between first memo and second label */
161
162 #define ICON_SIZE           14
163
164 #define STATE_UNKNOWN   -1
165 #define STATE_THINKING   0
166 #define STATE_IDLE       1
167 #define STATE_PONDERING  2
168 #define STATE_ANALYZING  3
169
170 static int  windowMode = 1;
171
172 static int  needInit = TRUE;
173
174 static int  lastDepth[2] = { -1, -1 };
175 static int  lastForwardMostMove[2] = { -1, -1 };
176 static int  engineState[2] = { -1, -1 };
177
178 typedef struct {
179     char * name;
180     int which;
181     int depth;
182     u64 nodes;
183     int score;
184     int time;
185     char * pv;
186     char * hint;
187     int an_move_index;
188     int an_move_count;
189 } EngineOutputData;
190
191 static void VerifyDisplayMode();
192 static void UpdateControls( EngineOutputData * ed );
193 static void SetEngineState( int which, int state, char * state_data );
194
195 void ReadIcon(char *pixData[], int iconNr)
196 {
197     int r;
198
199         if ((r=XpmCreatePixmapFromData(xDisplay, XtWindow(outputField[0][nColorIcon]),
200                                        pixData,
201                                        &(icons[iconNr]),
202                                        NULL, NULL /*&attr*/)) != 0) {
203           fprintf(stderr, _("Error %d loading icon image\n"), r);
204           exit(1); 
205         }       
206 }
207
208 static void InitializeEngineOutput()
209 { int i;
210
211         ReadIcon(WHITE_14,   nColorWhite);
212         ReadIcon(BLACK_14,   nColorBlack);
213         ReadIcon(UNKNOWN_14, nColorUnknown);
214
215         ReadIcon(CLEAR_14,   nClear);
216         ReadIcon(PONDER_14,  nPondering);
217         ReadIcon(THINK_14,   nThinking);
218         ReadIcon(ANALYZE_14, nAnalyzing);
219 }
220
221 void DoSetWindowText(int which, int field, char *s_label)
222
223         Arg arg;
224
225         XtSetArg(arg, XtNlabel, (XtArgVal) s_label);
226         XtSetValues(outputField[which][field], &arg, 1);
227 }
228
229 static void InsertIntoMemo( int which, char * text )
230 {
231         Arg arg; XawTextBlock t; Widget edit;
232
233         /* the backend adds \r\n, which is needed for winboard, 
234          * for xboard we delete them again over here */
235         if(t.ptr = strchr(text, '\r')) *t.ptr = ' ';
236
237         t.ptr = text; t.firstPos = 0; t.length = strlen(text); t.format = XawFmt8Bit;
238         edit = XtNameToWidget(engineOutputShell, which ? "*form2.text" : "*form.text");
239         XawTextReplace(edit, 0, 0, &t);
240 //      XtSetArg(arg, XtNstring, (XtArgVal) text);
241 //      XtSetValues(outputField[which][nMemo], &arg, 1);
242 }
243
244 static void SetIcon( int which, int field, int nIcon )
245 {
246     Arg arg;
247
248     if( nIcon != 0 ) {
249         XtSetArg(arg, XtNleftBitmap, (XtArgVal) icons[nIcon]);
250         XtSetValues(outputField[which][field], &arg, 1);
251     }
252 }
253
254 void DoClearMemo(int which)
255
256     Arg args[16];
257     int j;
258     Widget edit;
259
260         edit = XtNameToWidget(engineOutputShell, which ? "*form2.text" : "*form.text");
261         XtCallActionProc(edit, "select-all", NULL, NULL, 0);
262         XtCallActionProc(edit, "kill-selection", NULL, NULL, 0);
263 }
264
265 // The following routines are mutated clones of the commentPopUp routines
266
267 void PositionControlSet(which, form, bw_width)
268      int which;
269      Widget form;
270      Dimension bw_width;
271 {
272     Arg args[16];
273     Widget edit, NameWidget, ColorWidget, ModeWidget, MoveWidget, NodesWidget;
274     int j, mutable=1;
275     j = 0;
276     XtSetArg(args[j], XtNborderWidth, (XtArgVal) 0); j++;
277     XtSetArg(args[j], XtNlabel,     (XtArgVal) ""); j++;
278     XtSetArg(args[j], XtNtop,       XtChainTop); j++;
279     XtSetArg(args[j], XtNbottom,    XtChainTop); j++;
280     XtSetArg(args[j], XtNleft,      XtChainLeft); j++;
281     XtSetArg(args[j], XtNright,     XtChainLeft); j++;
282     XtSetArg(args[j], XtNheight,    (XtArgVal) 16); j++;
283     XtSetArg(args[j], XtNwidth,     (XtArgVal) 17); j++;
284     outputField[which][nColorIcon] = ColorWidget =
285       XtCreateManagedWidget("Color", labelWidgetClass,
286                      form, args, j);
287
288     j = 0;
289     XtSetArg(args[j], XtNborderWidth, (XtArgVal) 0); j++;
290     XtSetArg(args[j], XtNjustify,   (XtArgVal) XtJustifyLeft); j++;
291     XtSetArg(args[j], XtNfromHoriz, (XtArgVal) ColorWidget); j++;
292     XtSetArg(args[j], XtNtop,       XtChainTop); j++;
293     XtSetArg(args[j], XtNbottom,    XtChainTop); j++;
294     XtSetArg(args[j], XtNleft,      XtChainLeft); j++;
295     XtSetArg(args[j], XtNheight,    (XtArgVal) 16); j++;
296     XtSetArg(args[j], XtNwidth,     (XtArgVal) bw_width/2 - 57); j++;
297     outputField[which][nLabel] = NameWidget =
298       XtCreateManagedWidget("Engine", labelWidgetClass,
299                      form, args, j);
300
301     j = 0;
302     XtSetArg(args[j], XtNborderWidth, (XtArgVal) 0); j++;
303     XtSetArg(args[j], XtNlabel,     (XtArgVal) ""); j++;
304     XtSetArg(args[j], XtNfromHoriz, (XtArgVal) NameWidget); j++;
305     XtSetArg(args[j], XtNtop,       XtChainTop); j++;
306     XtSetArg(args[j], XtNbottom,    XtChainTop); j++;
307     XtSetArg(args[j], XtNheight,    (XtArgVal) 16); j++;
308     XtSetArg(args[j], XtNwidth,     (XtArgVal) 20); j++;
309     outputField[which][nStateIcon] = ModeWidget =
310       XtCreateManagedWidget("Mode", labelWidgetClass,
311                      form, args, j);
312
313     j = 0;
314     XtSetArg(args[j], XtNborderWidth, (XtArgVal) 0); j++;
315     XtSetArg(args[j], XtNjustify,   (XtArgVal) XtJustifyLeft); j++;
316     XtSetArg(args[j], XtNlabel,     (XtArgVal) ""); j++;
317     XtSetArg(args[j], XtNfromHoriz, (XtArgVal) ModeWidget); j++;
318     XtSetArg(args[j], XtNtop,       XtChainTop); j++;
319     XtSetArg(args[j], XtNbottom,    XtChainTop); j++;
320     XtSetArg(args[j], XtNright,     XtChainRight); j++;
321     XtSetArg(args[j], XtNheight,    (XtArgVal) 16); j++;
322     XtSetArg(args[j], XtNwidth,     (XtArgVal) bw_width/2 - 102); j++;
323     outputField[which][nStateData] = MoveWidget =
324       XtCreateManagedWidget("Move", labelWidgetClass,
325                      form, args, j);
326
327     j = 0;
328     XtSetArg(args[j], XtNborderWidth, (XtArgVal) 0); j++;
329     XtSetArg(args[j], XtNjustify,   (XtArgVal) XtJustifyRight); j++;
330     XtSetArg(args[j], XtNlabel,     (XtArgVal) _("NPS")); j++;
331     XtSetArg(args[j], XtNfromHoriz, (XtArgVal) MoveWidget); j++;
332     XtSetArg(args[j], XtNtop,       XtChainTop); j++;
333     XtSetArg(args[j], XtNbottom,    XtChainTop); j++;
334     XtSetArg(args[j], XtNleft,      XtChainRight); j++;
335     XtSetArg(args[j], XtNright,     XtChainRight); j++;
336     XtSetArg(args[j], XtNheight,    (XtArgVal) 16); j++;
337     XtSetArg(args[j], XtNwidth,     (XtArgVal) 100); j++;
338     outputField[which][nLabelNPS] = NodesWidget =
339       XtCreateManagedWidget("Nodes", labelWidgetClass,
340                      form, args, j);
341
342     // create "text" within "form"
343     j = 0;
344     if (mutable) {
345         XtSetArg(args[j], XtNeditType, XawtextEdit);  j++;
346         XtSetArg(args[j], XtNuseStringInPlace, False);  j++;
347     }
348     XtSetArg(args[j], XtNstring, "");  j++;
349     XtSetArg(args[j], XtNdisplayCaret, False);  j++;
350     XtSetArg(args[j], XtNtop, XtChainTop);  j++;
351     XtSetArg(args[j], XtNbottom, XtChainBottom);  j++;
352     XtSetArg(args[j], XtNleft, XtChainLeft);  j++;
353     XtSetArg(args[j], XtNright, XtChainRight);  j++;
354     XtSetArg(args[j], XtNresizable, True);  j++;
355     XtSetArg(args[j], XtNwidth, bw_width);  j++; /*force wider than buttons*/
356     /* !!Work around an apparent bug in XFree86 4.0.1 (X11R6.4.3) */
357     XtSetArg(args[j], XtNscrollVertical, XawtextScrollAlways);  j++;
358     XtSetArg(args[j], XtNscrollHorizontal, XawtextScrollWhenNeeded);  j++;
359 //    XtSetArg(args[j], XtNautoFill, True);  j++;
360 //    XtSetArg(args[j], XtNwrap, XawtextWrapWord); j++;
361     outputField[which][nMemo] = edit =
362       XtCreateManagedWidget("text", asciiTextWidgetClass, form, args, j);
363
364     j = 0;
365     XtSetArg(args[j], XtNfromVert, ColorWidget); j++;
366 //    XtSetArg(args[j], XtNresizable, (XtArgVal) True); j++;
367     XtSetValues(edit, args, j);
368 }
369
370 Widget EngineOutputCreate(name, text)
371      char *name, *text;
372 {
373     Arg args[16];
374     Widget shell, layout, form, form2, edit;
375     Dimension bw_width, bw_height;
376     int j;
377
378     // get board width
379     j = 0;
380     XtSetArg(args[j], XtNwidth,  &bw_width);  j++;
381     XtSetArg(args[j], XtNheight, &bw_height);  j++;
382     XtGetValues(boardWidget, args, j);
383
384     // define form within layout within shell.
385     j = 0;
386     XtSetArg(args[j], XtNresizable, True);  j++;
387     shell =
388 #if TOPLEVEL 
389      XtCreatePopupShell(name, topLevelShellWidgetClass,
390 #else
391       XtCreatePopupShell(name, transientShellWidgetClass,
392 #endif
393                          shellWidget, args, j);
394     layout =
395       XtCreateManagedWidget(layoutName, formWidgetClass, shell,
396                             layoutArgs, XtNumber(layoutArgs));
397     // divide window vertically into two equal parts, by creating two forms
398     form =
399       XtCreateManagedWidget("form", formWidgetClass, layout,
400                             formArgs, XtNumber(formArgs));
401     form2 =
402       XtCreateManagedWidget("form2", formWidgetClass, layout,
403                             formArgs, XtNumber(formArgs));
404     j = 0;
405     XtSetArg(args[j], XtNfromVert,  (XtArgVal) form); j++;
406     XtSetValues(form2, args, j);
407     // make sure width is known in advance, for better placement of child widgets
408     j = 0;
409     XtSetArg(args[j], XtNwidth,     (XtArgVal) bw_width-16); j++;
410     XtSetArg(args[j], XtNheight,    (XtArgVal) bw_height/2); j++;
411     XtSetValues(shell, args, j);
412
413     // fill up both forms with control elements
414     PositionControlSet(0, form,  bw_width);
415     PositionControlSet(1, form2, bw_width);
416
417     XtRealizeWidget(shell);
418
419     if (engineOutputX == -1) {
420         int xx, yy;
421         Window junk;
422         Dimension pw_height;
423         Dimension ew_height;
424         engineOutputH = bw_height/2;
425         engineOutputW = bw_width-16;
426
427         XSync(xDisplay, False);
428 #ifdef NOTDEF
429         /* This code seems to tickle an X bug if it is executed too soon
430            after xboard starts up.  The coordinates get transformed as if
431            the main window was positioned at (0, 0).
432            */
433         XtTranslateCoords(shellWidget,
434                           (bw_width - engineOutputW) / 2, 0 - engineOutputH / 2,
435                           &engineOutputX, &engineOutputY);
436 #else  /*!NOTDEF*/
437         XTranslateCoordinates(xDisplay, XtWindow(shellWidget),
438                               RootWindowOfScreen(XtScreen(shellWidget)),
439                               (bw_width - engineOutputW) / 2, 0 - engineOutputH / 2,
440                               &xx, &yy, &junk);
441         engineOutputX = xx;
442         engineOutputY = yy;
443 #endif /*!NOTDEF*/
444         if (engineOutputY < 0) engineOutputY = 0; /*avoid positioning top offscreen*/
445     }
446     j = 0;
447     XtSetArg(args[j], XtNheight, engineOutputH);  j++;
448     XtSetArg(args[j], XtNwidth, engineOutputW);  j++;
449     XtSetArg(args[j], XtNx, engineOutputX);  j++;
450     XtSetArg(args[j], XtNy, engineOutputY);  j++;
451     XtSetValues(shell, args, j);
452 //    XtSetKeyboardFocus(shell, edit);
453
454     return shell;
455 }
456
457 void ResizeWindowControls(shell, mode)
458         Widget shell;
459         int mode;
460 {
461     Widget form1, form2;
462     Arg args[16];
463     int j;
464     Dimension ew_height, tmp;
465
466     form1 = XtNameToWidget(shell, "*form");
467     form2 = XtNameToWidget(shell, "*form2");
468
469     j = 0;
470     XtSetArg(args[j], XtNheight, (XtArgVal) &ew_height); j++;
471     XtGetValues(form1, args, j);
472     j = 0;
473     XtSetArg(args[j], XtNheight, (XtArgVal) &tmp); j++;
474     XtGetValues(form2, args, j);
475     ew_height += tmp; // total height
476
477     if(mode==0) {
478         j = 0;
479         XtSetArg(args[j], XtNheight, (XtArgVal) 5); j++;
480         XtSetValues(form2, args, j);
481         j = 0;
482         XtSetArg(args[j], XtNheight, (XtArgVal) (ew_height-5)); j++;
483         XtSetValues(form1, args, j);
484     } else {
485         j = 0;
486         XtSetArg(args[j], XtNheight, (XtArgVal) (ew_height/2)); j++;
487         XtSetValues(form1, args, j);
488         j = 0;
489         XtSetArg(args[j], XtNheight, (XtArgVal) (ew_height/2)); j++;
490         XtSetValues(form2, args, j);
491     }
492 }
493
494 void 
495 EngineOutputPopUp()
496 {
497     Arg args[16];
498     int j;
499     Widget edit;
500     static char *title = _("Engine output"), *text = _("This feature is experimental");
501
502     if (engineOutputShell == NULL) {
503         engineOutputShell =
504           EngineOutputCreate(title, text);
505         XtRealizeWidget(engineOutputShell);
506         CatchDeleteWindow(engineOutputShell, "EngineOutputPopDown");
507         if( needInit ) {
508             InitializeEngineOutput();
509             needInit = FALSE;
510         }
511         SetEngineColorIcon( 0 );
512         SetEngineColorIcon( 1 );
513         SetEngineState( 0, STATE_IDLE, "" );
514         SetEngineState( 1, STATE_IDLE, "" );
515     } else {
516         edit = XtNameToWidget(engineOutputShell, "*form.text");
517         j = 0;
518         XtSetArg(args[j], XtNstring, text); j++;
519         XtSetValues(edit, args, j);
520         j = 0;
521         XtSetArg(args[j], XtNiconName, (XtArgVal) title);   j++;
522         XtSetArg(args[j], XtNtitle, (XtArgVal) title);      j++;
523         XtSetValues(engineOutputShell, args, j);
524     }
525
526     XtPopup(engineOutputShell, XtGrabNone);
527     XSync(xDisplay, False);
528
529     j=0;
530     XtSetArg(args[j], XtNleftBitmap, xMarkPixmap); j++;
531     XtSetValues(XtNameToWidget(menuBarWidget, "menuMode.Show Engine Output"),
532                 args, j);
533
534     engineOutputDialogUp = True;
535     ShowThinkingEvent(); // [HGM] thinking: might need to prompt engine for thinking output
536 }
537
538 void EngineOutputPopDown()
539 {
540     Arg args[16];
541     int j;
542
543     if (!engineOutputDialogUp) return;
544     DoClearMemo(1);
545     j = 0;
546     XtSetArg(args[j], XtNx, &engineOutputX); j++;
547     XtSetArg(args[j], XtNy, &engineOutputY); j++;
548     XtSetArg(args[j], XtNwidth, &engineOutputW); j++;
549     XtSetArg(args[j], XtNheight, &engineOutputH); j++;
550     XtGetValues(engineOutputShell, args, j);
551     XtPopdown(engineOutputShell);
552     XSync(xDisplay, False);
553     j=0;
554     XtSetArg(args[j], XtNleftBitmap, None); j++;
555     XtSetValues(XtNameToWidget(menuBarWidget, "menuMode.Show Engine Output"),
556                 args, j);
557
558     engineOutputDialogUp = False;
559     ShowThinkingEvent(); // [HGM] thinking: might need to shut off thinking output
560 }
561
562 //------------------------ pure back-end routines -------------------------------
563
564
565 // back end, due to front-end wrapper for SetWindowText, and new SetIcon arguments
566 static void SetEngineState( int which, int state, char * state_data )
567 {
568     int x_which = 1 - which;
569
570     if( engineState[ which ] != state ) {
571         engineState[ which ] = state;
572
573         switch( state ) {
574         case STATE_THINKING:
575             SetIcon( which, nStateIcon, nThinking );
576             if( engineState[ x_which ] == STATE_THINKING ) {
577                 SetEngineState( x_which, STATE_IDLE, "" );
578             }
579             break;
580         case STATE_PONDERING:
581             SetIcon( which, nStateIcon, nPondering );
582             break;
583         case STATE_ANALYZING:
584             SetIcon( which, nStateIcon, nAnalyzing );
585             break;
586         default:
587             SetIcon( which, nStateIcon, nClear );
588             break;
589         }
590     }
591
592     if( state_data != 0 ) {
593         DoSetWindowText( which, nStateData, state_data );
594     }
595 }
596
597 // back end, now the front-end wrapper ClearMemo is used, and ed no longer contains handles.
598 void EngineOutputUpdate( FrontEndProgramStats * stats )
599 {
600     EngineOutputData ed;
601     int clearMemo = FALSE;
602     int which;
603     int depth;
604
605     if( stats == 0 ) {
606         SetEngineState( 0, STATE_IDLE, "" );
607         SetEngineState( 1, STATE_IDLE, "" );
608         return;
609     }
610
611     if(gameMode == IcsObserving && !appData.icsEngineAnalyze)
612         return; // [HGM] kibitz: shut up engine if we are observing an ICS game
613
614     which = stats->which;
615     depth = stats->depth;
616
617     if( which < 0 || which > 1 || depth < 0 || stats->time < 0 || stats->pv == 0 ) {
618         return;
619     }
620
621     if( engineOutputShell == NULL ) {
622         return;
623     }
624
625     VerifyDisplayMode();
626
627     ed.which = which;
628     ed.depth = depth;
629     ed.nodes = stats->nodes;
630     ed.score = stats->score;
631     ed.time = stats->time;
632     ed.pv = stats->pv;
633     ed.hint = stats->hint;
634     ed.an_move_index = stats->an_move_index;
635     ed.an_move_count = stats->an_move_count;
636
637     /* Get target control. [HGM] this is moved to front end, which get them from a table */
638     if( which == 0 ) {
639         ed.name = first.tidy;
640     }
641     else {
642         ed.name = second.tidy;
643     }
644
645     /* Clear memo if needed */
646     if( lastDepth[which] > depth || (lastDepth[which] == depth && depth <= 1) ) {
647         clearMemo = TRUE;
648     }
649
650     if( lastForwardMostMove[which] != forwardMostMove ) {
651         clearMemo = TRUE;
652     }
653
654     if( clearMemo ) DoClearMemo(which);
655
656     /* Update */
657     lastDepth[which] = depth == 1 && ed.nodes == 0 ? 0 : depth; // [HGM] info-line kudge
658     lastForwardMostMove[which] = forwardMostMove;
659
660     if( ed.pv != 0 && ed.pv[0] == ' ' ) {
661         if( strncmp( ed.pv, " no PV", 6 ) == 0 ) { /* Hack on hack! :-O */
662             ed.pv = "";
663         }
664     }
665
666     UpdateControls( &ed );
667 }
668
669 #define ENGINE_COLOR_WHITE      'w'
670 #define ENGINE_COLOR_BLACK      'b'
671 #define ENGINE_COLOR_UNKNOWN    ' '
672
673 // pure back end
674 char GetEngineColor( int which )
675 {
676     char result = ENGINE_COLOR_UNKNOWN;
677
678     if( which == 0 || which == 1 ) {
679         ChessProgramState * cps;
680
681         switch (gameMode) {
682         case MachinePlaysBlack:
683         case IcsPlayingBlack:
684             result = ENGINE_COLOR_BLACK;
685             break;
686         case MachinePlaysWhite:
687         case IcsPlayingWhite:
688             result = ENGINE_COLOR_WHITE;
689             break;
690         case AnalyzeMode:
691         case AnalyzeFile:
692             result = WhiteOnMove(forwardMostMove) ? ENGINE_COLOR_WHITE : ENGINE_COLOR_BLACK;
693             break;
694         case TwoMachinesPlay:
695             cps = (which == 0) ? &first : &second;
696             result = cps->twoMachinesColor[0];
697             result = result == 'w' ? ENGINE_COLOR_WHITE : ENGINE_COLOR_BLACK;
698             break;
699         }
700     }
701
702     return result;
703 }
704
705 // pure back end
706 char GetActiveEngineColor()
707 {
708     char result = ENGINE_COLOR_UNKNOWN;
709
710     if( gameMode == TwoMachinesPlay ) {
711         result = WhiteOnMove(forwardMostMove) ? ENGINE_COLOR_WHITE : ENGINE_COLOR_BLACK;
712     }
713
714     return result;
715 }
716
717 // pure back end
718 static int IsEnginePondering( int which )
719 {
720     int result = FALSE;
721
722     switch (gameMode) {
723     case MachinePlaysBlack:
724     case IcsPlayingBlack:
725         if( WhiteOnMove(forwardMostMove) ) result = TRUE;
726         break;
727     case MachinePlaysWhite:
728     case IcsPlayingWhite:
729         if( ! WhiteOnMove(forwardMostMove) ) result = TRUE;
730         break;
731     case TwoMachinesPlay:
732         if( GetActiveEngineColor() != ENGINE_COLOR_UNKNOWN ) {
733             if( GetEngineColor( which ) != GetActiveEngineColor() ) result = TRUE;
734         }
735         break;
736     }
737
738     return result;
739 }
740
741 // back end
742 static void SetDisplayMode( int mode )
743 {
744     if( windowMode != mode ) {
745         windowMode = mode;
746
747         ResizeWindowControls( engineOutputShell, mode );
748     }
749 }
750
751 // pure back end
752 void VerifyDisplayMode()
753 {
754     int mode;
755
756     /* Get proper mode for current game */
757     switch( gameMode ) {
758     case IcsObserving:    // [HGM] ICS analyze
759         if(!appData.icsEngineAnalyze) return;
760     case AnalyzeMode:
761     case AnalyzeFile:
762     case MachinePlaysWhite:
763     case MachinePlaysBlack:
764         mode = 0;
765         break;
766     case IcsPlayingWhite:
767     case IcsPlayingBlack:
768         mode = appData.zippyPlay && opponentKibitzes; // [HGM] kibitz
769         break;
770     case TwoMachinesPlay:
771         mode = 1;
772         break;
773     default:
774         /* Do not change */
775         return;
776     }
777
778     SetDisplayMode( mode );
779 }
780
781 // back end. Determine what icon to se in the color-icon field, and print it
782 static void SetEngineColorIcon( int which )
783 {
784     char color = GetEngineColor(which);
785     int nicon = 0;
786
787     if( color == ENGINE_COLOR_BLACK )
788         nicon = nColorBlack;
789     else if( color == ENGINE_COLOR_WHITE )
790         nicon = nColorWhite;
791     else
792         nicon = nColorUnknown;
793
794     SetIcon( which, nColorIcon, nicon );
795 }
796
797 #define MAX_NAME_LENGTH 32
798
799 // pure back end, now SetWindowText is called via wrapper DoSetWindowText
800 static void UpdateControls( EngineOutputData * ed )
801 {
802     int isPondering = FALSE;
803
804     char s_label[MAX_NAME_LENGTH + 32];
805     
806     char * name = ed->name;
807
808     /* Label */
809     if( name == 0 || *name == '\0' ) {
810         name = "?";
811     }
812
813     strncpy( s_label, name, MAX_NAME_LENGTH );
814     s_label[ MAX_NAME_LENGTH-1 ] = '\0';
815
816 #ifdef SHOW_PONDERING
817     if( IsEnginePondering( ed->which ) ) {
818         char buf[8];
819
820         buf[0] = '\0';
821
822         if( ed->hint != 0 && *ed->hint != '\0' ) {
823             strncpy( buf, ed->hint, sizeof(buf) );
824             buf[sizeof(buf)-1] = '\0';
825         }
826         else if( ed->pv != 0 && *ed->pv != '\0' ) {
827             char * sep = strchr( ed->pv, ' ' );
828             int buflen = sizeof(buf);
829
830             if( sep != NULL ) {
831                 buflen = sep - ed->pv + 1;
832                 if( buflen > sizeof(buf) ) buflen = sizeof(buf);
833             }
834
835             strncpy( buf, ed->pv, buflen );
836             buf[ buflen-1 ] = '\0';
837         }
838
839         SetEngineState( ed->which, STATE_PONDERING, buf );
840     }
841     else if( gameMode == TwoMachinesPlay ) {
842         SetEngineState( ed->which, STATE_THINKING, "" );
843     }
844     else if( gameMode == AnalyzeMode || gameMode == AnalyzeFile 
845           || gameMode == IcsObserving && appData.icsEngineAnalyze) { // [HGM] ICS-analyze
846         char buf[64];
847         int time_secs = ed->time / 100;
848         int time_mins = time_secs / 60;
849
850         buf[0] = '\0';
851
852         if( ed->an_move_index != 0 && ed->an_move_count != 0 && *ed->hint != '\0' ) {
853             char mov[16];
854
855             strncpy( mov, ed->hint, sizeof(mov) );
856             mov[ sizeof(mov)-1 ] = '\0';
857
858             sprintf( buf, "[%d] %d/%d: %s [%02d:%02d:%02d]", ed->depth, ed->an_move_index,
859                         ed->an_move_count, mov, time_mins / 60, time_mins % 60, time_secs % 60 );
860         }
861
862         SetEngineState( ed->which, STATE_ANALYZING, buf );
863     }
864     else {
865         SetEngineState( ed->which, STATE_IDLE, "" );
866     }
867 #endif
868
869     DoSetWindowText( ed->which, nLabel, s_label );
870
871     s_label[0] = '\0';
872
873     if( ed->time > 0 && ed->nodes > 0 ) {
874         unsigned long nps_100 = ed->nodes / ed->time;
875
876         if( nps_100 < 100000 ) {
877             sprintf( s_label, _("NPS: %lu"), nps_100 * 100 );
878         }
879         else {
880             sprintf( s_label, _("NPS: %.1fk"), nps_100 / 10.0 );
881         }
882     }
883
884     DoSetWindowText( ed->which, nLabelNPS, s_label );
885
886     /* Memo */
887     if( ed->pv != 0 && *ed->pv != '\0' ) {
888         char s_nodes[24];
889         char s_score[16];
890         char s_time[24];
891         char buf[256];
892         int buflen;
893         int time_secs = ed->time / 100;
894         int time_cent = ed->time % 100;
895
896         /* Nodes */
897         if( ed->nodes < 1000000 ) {
898             sprintf( s_nodes, u64Display, ed->nodes );
899         }
900         else {
901             sprintf( s_nodes, "%.1fM", u64ToDouble(ed->nodes) / 1000000.0 );
902         }
903
904         /* Score */
905         if( ed->score > 0 ) {
906             sprintf( s_score, "+%.2f", ed->score / 100.0 );
907         } else
908             sprintf( s_score, "%.2f", ed->score / 100.0 );
909
910         /* Time */
911         sprintf( s_time, "%d:%02d.%02d", time_secs / 60, time_secs % 60, time_cent );
912
913         /* Put all together... */
914         if(ed->nodes == 0 && ed->score == 0 && ed->time == 0) sprintf( buf, "%3d\t", ed->depth ); else 
915         sprintf( buf, "%3d  %s  %s\t%s\t", ed->depth, s_score, s_nodes, s_time );
916
917         /* Add PV */
918         buflen = strlen(buf);
919
920         strncpy( buf + buflen, ed->pv, sizeof(buf) - buflen );
921
922         buf[ sizeof(buf) - 3 ] = '\0';
923
924         strcat( buf + buflen, "\n" );
925
926         /* Update memo */
927         InsertIntoMemo( ed->which, buf );
928     }
929
930     /* Colors */
931     SetEngineColorIcon( ed->which );
932 }
933
934 // back end
935 int EngineOutputIsUp()
936 {
937     return engineOutputDialogUp;
938 }
939
940 void
941 EngineOutputProc(w, event, prms, nprms)
942      Widget w;
943      XEvent *event;
944      String *prms;
945      Cardinal *nprms;
946 {
947   if (engineOutputDialogUp) {
948     EngineOutputPopDown();
949   } else {
950     EngineOutputPopUp();
951   }
952 //  ToNrEvent(currentMove);
953 }
954
955 // [HGM] kibitz: write kibitz line; split window for it if necessary
956 void OutputKibitz(int window, char *text)
957 {
958         if(!EngineOutputIsUp()) return;
959         if(!opponentKibitzes) { // on first kibitz of game, clear memos
960             DoClearMemo(1);
961             if(gameMode == IcsObserving) DoClearMemo(0);
962         }
963         opponentKibitzes = TRUE; // this causes split window DisplayMode in ICS modes.
964         VerifyDisplayMode();
965         if(gameMode == IcsObserving) {
966             DoSetWindowText(0, nLabel, gameInfo.white);
967             SetIcon( 0, nColorIcon,  nColorWhite);
968             SetIcon( 0, nStateIcon,  nClear);
969         }
970         DoSetWindowText(1, nLabel, gameMode == IcsPlayingBlack ? gameInfo.white : gameInfo.black); // opponent name
971         SetIcon( 1, nColorIcon,  gameMode == IcsPlayingBlack ? nColorWhite : nColorBlack);
972         SetIcon( 1, nStateIcon,  nClear);
973         InsertIntoMemo(window-1, text);
974 }