Prevent crash on specifying non-existent texture XB
[xboard.git] / draw.c
1 /*
2  * draw.c -- drawing routines for XBoard
3  *
4  * Copyright 1991 by Digital Equipment Corporation, Maynard,
5  * Massachusetts.
6  *
7  * Enhancements Copyright 1992-2001, 2002, 2003, 2004, 2005, 2006,
8  * 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 Free Software Foundation, Inc.
9  *
10  * The following terms apply to Digital Equipment Corporation's copyright
11  * interest in XBoard:
12  * ------------------------------------------------------------------------
13  * All Rights Reserved
14  *
15  * Permission to use, copy, modify, and distribute this software and its
16  * documentation for any purpose and without fee is hereby granted,
17  * provided that the above copyright notice appear in all copies and that
18  * both that copyright notice and this permission notice appear in
19  * supporting documentation, and that the name of Digital not be
20  * used in advertising or publicity pertaining to distribution of the
21  * software without specific, written prior permission.
22  *
23  * DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
24  * ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
25  * DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
26  * ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
27  * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
28  * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
29  * SOFTWARE.
30  * ------------------------------------------------------------------------
31  *
32  * The following terms apply to the enhanced version of XBoard
33  * distributed by the Free Software Foundation:
34  * ------------------------------------------------------------------------
35  *
36  * GNU XBoard is free software: you can redistribute it and/or modify
37  * it under the terms of the GNU General Public License as published by
38  * the Free Software Foundation, either version 3 of the License, or (at
39  * your option) any later version.
40  *
41  * GNU XBoard is distributed in the hope that it will be useful, but
42  * WITHOUT ANY WARRANTY; without even the implied warranty of
43  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
44  * General Public License for more details.
45  *
46  * You should have received a copy of the GNU General Public License
47  * along with this program. If not, see http://www.gnu.org/licenses/.  *
48  *
49  *------------------------------------------------------------------------
50  ** See the file ChangeLog for a revision history.  */
51
52 #include "config.h"
53
54 #include <stdio.h>
55 #include <math.h>
56 #include <cairo/cairo.h>
57 #include <cairo/cairo-xlib.h>
58 #include <librsvg/rsvg.h>
59 #include <librsvg/rsvg-cairo.h>
60
61 #if STDC_HEADERS
62 # include <stdlib.h>
63 # include <string.h>
64 #else /* not STDC_HEADERS */
65 extern char *getenv();
66 # if HAVE_STRING_H
67 #  include <string.h>
68 # else /* not HAVE_STRING_H */
69 #  include <strings.h>
70 # endif /* not HAVE_STRING_H */
71 #endif /* not STDC_HEADERS */
72
73 #if ENABLE_NLS
74 #include <locale.h>
75 #endif
76
77 #include "common.h"
78
79 #include "backend.h"
80 #include "board.h"
81 #include "menus.h"
82 #include "dialogs.h"
83 #include "evalgraph.h"
84 #include "gettext.h"
85 #include "draw.h"
86
87
88 #ifdef __EMX__
89 #ifndef HAVE_USLEEP
90 #define HAVE_USLEEP
91 #endif
92 #define usleep(t)   _sleep2(((t)+500)/1000)
93 #endif
94
95 #ifdef ENABLE_NLS
96 # define  _(s) gettext (s)
97 # define N_(s) gettext_noop (s)
98 #else
99 # define  _(s) (s)
100 # define N_(s)  s
101 #endif
102
103 #define SOLID 0
104 #define OUTLINE 1
105 Boolean cairoAnimate;
106 Option *currBoard;
107 cairo_surface_t *csBoardWindow;
108 static cairo_surface_t *pngPieceImages[2][(int)BlackPawn+4];   // png 256 x 256 images
109 static cairo_surface_t *pngPieceBitmaps[2][(int)BlackPawn];    // scaled pieces as used
110 static cairo_surface_t *pngPieceBitmaps2[2][(int)BlackPawn+4]; // scaled pieces in store
111 static RsvgHandle *svgPieces[2][(int)BlackPawn+4]; // vector pieces in store
112 static cairo_surface_t *pngBoardBitmap[2], *pngOriginalBoardBitmap[2];
113 int useTexture, textureW[2], textureH[2];
114
115 #define pieceToSolid(piece) &pieceBitmap[SOLID][(piece) % (int)BlackPawn]
116 #define pieceToOutline(piece) &pieceBitmap[OUTLINE][(piece) % (int)BlackPawn]
117
118 #define White(piece) ((int)(piece) < (int)BlackPawn)
119
120 char svgDir[MSG_SIZ] = SVGDIR;
121
122 char *crWhite = "#FFFFB0";
123 char *crBlack = "#AD5D3D";
124
125 struct {
126   int x1, x2, y1, y2;
127 } gridSegments[BOARD_RANKS + BOARD_FILES + 2];
128
129 void
130 SwitchWindow (int main)
131 {
132     currBoard = (main ? &mainOptions[W_BOARD] : &dualOptions[3]);
133     csBoardWindow = DRAWABLE(currBoard);
134 }
135
136 void
137 SelectPieces(VariantClass v)
138 {
139     int i;
140     for(i=0; i<2; i++) {
141         int p;
142         for(p=0; p<=(int)WhiteKing; p++)
143            pngPieceBitmaps[i][p] = pngPieceBitmaps2[i][p]; // defaults
144         if(v == VariantShogi && BOARD_HEIGHT != 7) { // no exceptions in Tori Shogi
145            pngPieceBitmaps[i][(int)WhiteCannon] = pngPieceBitmaps2[i][(int)WhiteTokin];
146            pngPieceBitmaps[i][(int)WhiteNightrider] = pngPieceBitmaps2[i][(int)WhiteKing+2];
147            pngPieceBitmaps[i][(int)WhiteGrasshopper] = pngPieceBitmaps2[i][(int)WhiteKing+3];
148            pngPieceBitmaps[i][(int)WhiteSilver] = pngPieceBitmaps2[i][(int)WhiteKing+4];
149            pngPieceBitmaps[i][(int)WhiteQueen] = pngPieceBitmaps2[i][(int)WhiteLance];
150            pngPieceBitmaps[i][(int)WhiteFalcon] = pngPieceBitmaps2[i][(int)WhiteMonarch]; // for Sho Shogi
151         }
152 #ifdef GOTHIC
153         if(v == VariantGothic) {
154            pngPieceBitmaps[i][(int)WhiteMarshall] = pngPieceBitmaps2[i][(int)WhiteSilver];
155         }
156 #endif
157         if(v == VariantSChess) {
158            pngPieceBitmaps[i][(int)WhiteAngel]    = pngPieceBitmaps2[i][(int)WhiteFalcon];
159            pngPieceBitmaps[i][(int)WhiteMarshall] = pngPieceBitmaps2[i][(int)WhiteAlfil];
160         }
161         if(v == VariantChuChess) {
162            pngPieceBitmaps[i][(int)WhiteNightrider] = pngPieceBitmaps2[i][(int)WhiteLion];
163         }
164         if(v == VariantChu) {
165            pngPieceBitmaps[i][(int)WhiteNightrider] = pngPieceBitmaps2[i][(int)WhiteKing+1];
166            pngPieceBitmaps[i][(int)WhiteUnicorn] = pngPieceBitmaps2[i][(int)WhiteCat];
167            pngPieceBitmaps[i][(int)WhiteSilver]  = pngPieceBitmaps2[i][(int)WhiteSword];
168            pngPieceBitmaps[i][(int)WhiteFalcon]  = pngPieceBitmaps2[i][(int)WhiteDagger];
169         }
170     }
171 }
172
173 #define BoardSize int
174 void
175 InitDrawingSizes (BoardSize boardSize, int flags)
176 {   // [HGM] resize is functional now, but for board format changes only (nr of ranks, files)
177     int boardWidth, boardHeight;
178     static int oldWidth, oldHeight;
179     static VariantClass oldVariant;
180     static int oldTwoBoards = 0, oldNrOfFiles = 0;
181
182     if(!mainOptions[W_BOARD].handle) return;
183
184     if(boardSize == -2 && gameInfo.variant != oldVariant
185                        && oldNrOfFiles && oldNrOfFiles != BOARD_WIDTH) { // called because variant switch changed board format
186         squareSize = ((squareSize + lineGap) * oldNrOfFiles + 0.5*BOARD_WIDTH) / BOARD_WIDTH; // keep total width fixed
187         if(appData.overrideLineGap < 0) lineGap = squareSize < 37 ? 1 : squareSize < 59 ? 2 : squareSize < 116 ? 3 : 4;
188         squareSize -= lineGap;
189         CreatePNGPieces();
190         CreateGrid();
191     }
192     oldNrOfFiles = BOARD_WIDTH;
193
194     if(oldTwoBoards && !twoBoards) PopDown(DummyDlg);
195     oldTwoBoards = twoBoards;
196
197     if(appData.overrideLineGap >= 0) lineGap = appData.overrideLineGap;
198     boardWidth = lineGap + BOARD_WIDTH * (squareSize + lineGap);
199     boardHeight = lineGap + BOARD_HEIGHT * (squareSize + lineGap);
200
201   if(boardWidth != oldWidth || boardHeight != oldHeight) { // do resizing stuff only if size actually changed
202
203     oldWidth = boardWidth; oldHeight = boardHeight;
204     CreateGrid();
205     CreateAnyPieces(0); // redo texture scaling
206
207     /*
208      * Inhibit shell resizing.
209      */
210     ResizeBoardWindow(boardWidth, boardHeight, 0);
211
212     DelayedDrag();
213   }
214
215     // [HGM] pieces: tailor piece bitmaps to needs of specific variant
216     // (only for xpm)
217
218   if(gameInfo.variant != oldVariant) { // and only if variant changed
219
220     SelectPieces(gameInfo.variant);
221
222     oldVariant = gameInfo.variant;
223   }
224   CreateAnimVars();
225 }
226
227 void
228 ExposeRedraw (Option *graph, int x, int y, int w, int h)
229 {   // copy a selected part of the buffer bitmap to the display
230     cairo_t *cr = cairo_create((cairo_surface_t *) graph->textValue);
231     cairo_set_source_surface(cr, (cairo_surface_t *) graph->choice, 0, 0);
232     cairo_set_antialias(cr, CAIRO_ANTIALIAS_NONE);
233     cairo_rectangle(cr, x, y, w, h);
234     cairo_fill(cr);
235     cairo_destroy(cr);
236 }
237
238 static void
239 CreatePNGBoard (char *s, int kind)
240 {
241     float w, h;
242     static float n[2] = { 1., 1. };
243     if(!appData.useBitmaps || s == NULL || *s == 0 || *s == '*') { useTexture &= ~(kind+1); return; }
244     textureW[kind] = 0; // prevents bitmap from being used if not succesfully loaded
245     if(strstr(s, ".png")) {
246         cairo_surface_t *img = cairo_image_surface_create_from_png (s);
247         if(img) {
248             char c, *p = s, *q;
249             int r, f;
250             if(pngOriginalBoardBitmap[kind]) cairo_surface_destroy(pngOriginalBoardBitmap[kind]);
251             if(n[kind] != 1.) cairo_surface_destroy(pngBoardBitmap[kind]);
252             useTexture |= kind + 1; pngOriginalBoardBitmap[kind] = img;
253             w = textureW[kind] = cairo_image_surface_get_width (img);
254             h = textureH[kind] = cairo_image_surface_get_height (img);
255             n[kind] = 1.;
256             while((q = strchr(p+1, '-'))) p = q; // find last '-'
257             if(strlen(p) < 11 && sscanf(p, "-%dx%d.pn%c", &f, &r, &c) == 3 && c == 'g') {
258                 if(f == 0 || r == 0) f = BOARD_WIDTH, r = BOARD_HEIGHT; // 0x0 means 'fits any', so make it fit
259                 textureW[kind] = (w*BOARD_WIDTH)/f; // sync cutting locations with square pattern
260                 textureH[kind] = (h*BOARD_HEIGHT)/r;
261                 n[kind] = r*squareSize/h; // scale to make it fit exactly vertically
262             } else
263             if((p = strstr(s, "xq")) && (p == s || p[-1] == '/')) { // assume full-board image for Xiangqi
264                 while(0.8*squareSize*BOARD_WIDTH > n[kind]*w || 0.8*squareSize*BOARD_HEIGHT > n[kind]*h) n[kind]++;
265             } else {
266                 while(squareSize > n[kind]*w || squareSize > n[kind]*h) n[kind]++;
267             }
268             if(n[kind] == 1.) pngBoardBitmap[kind] = img; else {
269                 // create scaled-up copy of the raw png image when it was too small
270                 cairo_surface_t *cs = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, n[kind]*w, n[kind]*h);
271                 cairo_t *cr = cairo_create(cs);
272                 pngBoardBitmap[kind] = cs; textureW[kind] *= n[kind]; textureH[kind] *= n[kind];
273 //              cairo_set_antialias(cr, CAIRO_ANTIALIAS_NONE);
274                 cairo_scale(cr, n[kind], n[kind]);
275                 cairo_set_source_surface (cr, img, 0, 0);
276                 cairo_paint (cr);
277                 cairo_destroy (cr);
278             }
279         }
280     }
281 }
282
283 char *pngPieceNames[] = // must be in same order as internal piece encoding
284 { "Pawn", "Knight", "Bishop", "Rook", "Queen", "Advisor", "Elephant", "Archbishop", "Marshall", "Gold", "Commoner",
285   "Canon", "Nightrider", "CrownedBishop", "CrownedRook", "Princess", "Chancellor", "Hawk", "Lance", "Cobra", "Unicorn", "Lion",
286   "GoldPawn", "HSword", "PromoHorse", "PromoDragon", "Leopard", "PromoSword", "Prince", "Phoenix", "Kylin", "PromoRook", "PromoHSword",
287   "Dolphin", "Chancellor", "Unicorn", "Hawk", "Sword", "Princess", "HCrown", "Knight", "Elephant", "PromoBishop", "King",
288   "Claw", "GoldKnight", "GoldLance", "GoldSilver", NULL
289 };
290
291 char *backupPiece[] = { "King", "Queen", "Lion" }; // pieces that map on other when not kanji
292
293 RsvgHandle *
294 LoadSVG (char *dir, int color, int piece, int retry)
295 {
296     char buf[MSG_SIZ];
297   RsvgHandle *svg=svgPieces[color][piece];
298   RsvgDimensionData svg_dimensions;
299   GError *svgerror=NULL;
300   cairo_surface_t *img;
301   cairo_t *cr;
302
303     snprintf(buf, MSG_SIZ, "%s/%s%s.svg", dir, color ? "Black" : "White",
304              retry ? backupPiece[piece - WhiteMonarch] : pngPieceNames[piece]);
305
306     if(svg || *dir && (svg = rsvg_handle_new_from_file(buf, &svgerror))) {
307
308       rsvg_handle_get_dimensions(svg, &svg_dimensions);
309       img = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, squareSize,  squareSize);
310
311       cr = cairo_create(img);
312       cairo_scale(cr, squareSize/(double) svg_dimensions.width, squareSize/(double) svg_dimensions.height);
313       rsvg_handle_render_cairo(svg, cr);
314       if(cairo_surface_status(img) == CAIRO_STATUS_SUCCESS) {
315         if(pngPieceImages[color][piece]) cairo_surface_destroy(pngPieceImages[color][piece]);
316         pngPieceImages[color][piece] = img;
317       }
318       cairo_destroy(cr);
319
320       return svg;
321     }
322     if(!retry && piece >= WhiteMonarch && piece <= WhiteNothing) // pieces that are only different in kanji sets
323         return LoadSVG(dir, color, piece, 1);
324     if(svgerror)
325         g_error_free(svgerror);
326     return NULL;
327 }
328
329 static void
330 ScaleOnePiece (int color, int piece)
331 {
332   float w, h;
333   char buf[MSG_SIZ];
334   cairo_surface_t *img, *cs;
335   cairo_t *cr;
336
337   g_type_init ();
338
339   svgPieces[color][piece] = LoadSVG("", color, piece, 0); // this fills pngPieceImages if we had cached svg with bitmap of wanted size
340
341   if(!pngPieceImages[color][piece]) { // we don't have cached bitmap (implying we did not have cached svg)
342     if(*appData.pieceDirectory) { // user specified piece directory
343       snprintf(buf, MSG_SIZ, "%s/%s%s.png", appData.pieceDirectory, color ? "Black" : "White", pngPieceNames[piece]);
344       img = cairo_image_surface_create_from_png (buf); // try if there are png pieces there
345       if(cairo_surface_status(img) != CAIRO_STATUS_SUCCESS) { // there were not
346         svgPieces[color][piece] = LoadSVG(appData.pieceDirectory, color, piece, 0); // so try if he has svg there
347       } else pngPieceImages[color][piece] = img;
348     }
349   }
350
351   if(!pngPieceImages[color][piece]) { // we still did not manage to acquire a piece bitmap
352     static int warned = 0;
353     if(!(svgPieces[color][piece] = LoadSVG(svgDir, color, piece, 0)) && !warned) { // try to fall back on installed svg 
354       char *msg = _("No default pieces installed!\nSelect your own using '-pieceImageDirectory'.");
355       printf("%s\n", msg); // give up
356       DisplayError(msg, 0);
357       warned = 1; // prevent error message being repeated for each piece type
358     }
359   }
360
361   img = pngPieceImages[color][piece];
362
363   // create new bitmap to hold scaled piece image (and remove any old)
364   if(pngPieceBitmaps2[color][piece]) cairo_surface_destroy (pngPieceBitmaps2[color][piece]);
365   pngPieceBitmaps2[color][piece] = cs = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, squareSize, squareSize);
366
367   if(!img) return;
368
369   // scaled copying of the raw png image
370   cr = cairo_create(cs);
371   w = cairo_image_surface_get_width (img);
372   h = cairo_image_surface_get_height (img);
373   cairo_scale(cr, squareSize/w, squareSize/h);
374   cairo_set_source_surface (cr, img, 0, 0);
375   cairo_paint (cr);
376   cairo_destroy (cr);
377
378   if(!appData.trueColors || !*appData.pieceDirectory) { // operate on bitmap to color it (king-size hack...)
379     int stride = cairo_image_surface_get_stride(cs)/4;
380     int *buf = (int *) cairo_image_surface_get_data(cs);
381     int i, j, p;
382     sscanf(color ? appData.blackPieceColor+1 : appData.whitePieceColor+1, "%x", &p); // replacement color
383     cairo_surface_flush(cs);
384     for(i=0; i<squareSize; i++) for(j=0; j<squareSize; j++) {
385         int r, a;
386         float f;
387         unsigned int c = buf[i*stride + j];
388         a = c >> 24; r = c >> 16 & 255;     // alpha and red, where red is the 'white' weight, since white is #FFFFCC in the source images
389         f = (color ? a - r : r)/255.;       // fraction of black or white in the mix that has to be replaced
390         buf[i*stride + j] = c & 0xFF000000; // alpha channel is kept at same opacity
391         buf[i*stride + j] += ((int)(f*(p&0xFF0000)) & 0xFF0000) + ((int)(f*(p&0xFF00)) & 0xFF00) + (int)(f*(p&0xFF)); // add desired fraction of new color
392         if(color) buf[i*stride + j] += r | r << 8 | r << 16; // details on black pieces get their weight added in pure white
393         if(appData.monoMode) {
394             if(a < 64) buf[i*stride + j] = 0; // if not opaque enough, totally transparent
395             else if(2*r < a) buf[i*stride + j] = 0xFF000000; // if not light enough, totally black
396             else buf[i*stride + j] = 0xFFFFFFFF; // otherwise white
397         }
398     }
399     cairo_surface_mark_dirty(cs);
400   }
401 }
402
403 void
404 CreatePNGPieces ()
405 {
406   int p;
407
408   for(p=0; pngPieceNames[p]; p++) {
409     ScaleOnePiece(0, p);
410     ScaleOnePiece(1, p);
411   }
412   SelectPieces(gameInfo.variant);
413 }
414
415 void
416 CreateAnyPieces (int p)
417 {   // [HGM] taken out of main
418     if(p) CreatePNGPieces();
419     CreatePNGBoard(appData.liteBackTextureFile, 1);
420     CreatePNGBoard(appData.darkBackTextureFile, 0);
421 }
422
423 void
424 InitDrawingParams (int reloadPieces)
425 {
426     int i, p;
427     if(reloadPieces)
428     for(i=0; i<2; i++) for(p=0; p<BlackPawn+4; p++) {
429         if(pngPieceImages[i][p]) cairo_surface_destroy(pngPieceImages[i][p]);
430         pngPieceImages[i][p] = NULL;
431         if(svgPieces[i][p]) rsvg_handle_close(svgPieces[i][p], NULL);
432         svgPieces[i][p] = NULL;
433     }
434     CreateAnyPieces(1);
435 }
436
437 // [HGM] seekgraph: some low-level drawing routines (by JC, mostly)
438
439 float
440 Color (char *col, int n)
441 {
442   int c;
443   sscanf(col, "#%x", &c);
444   c = c >> 4*n & 255;
445   return c/255.;
446 }
447
448 void
449 SetPen (cairo_t *cr, float w, char *col, int dash)
450 {
451   static const double dotted[] = {4.0, 4.0};
452   static int len  = sizeof(dotted) / sizeof(dotted[0]);
453   cairo_set_line_width (cr, w);
454   cairo_set_source_rgba (cr, Color(col, 4), Color(col, 2), Color(col, 0), 1.0);
455   if(dash) cairo_set_dash (cr, dotted, len, 0.0);
456 }
457
458 void DrawSeekAxis( int x, int y, int xTo, int yTo )
459 {
460     cairo_t *cr;
461
462     /* get a cairo_t */
463     cr = cairo_create (csBoardWindow);
464
465     cairo_move_to (cr, x, y);
466     cairo_line_to(cr, xTo, yTo );
467
468     SetPen(cr, 2, "#000000", 0);
469     cairo_stroke(cr);
470
471     /* free memory */
472     cairo_destroy (cr);
473     GraphExpose(currBoard, x-1, yTo-1, xTo-x+2, y-yTo+2);
474 }
475
476 void DrawSeekBackground( int left, int top, int right, int bottom )
477 {
478     cairo_t *cr = cairo_create (csBoardWindow);
479
480     cairo_rectangle (cr, left, top, right-left, bottom-top);
481
482     cairo_set_source_rgba(cr, 0.8, 0.8, 0.4,1.0);
483     cairo_fill(cr);
484
485     /* free memory */
486     cairo_destroy (cr);
487     GraphExpose(currBoard, left, top, right-left, bottom-top);
488 }
489
490 void DrawSeekText(char *buf, int x, int y)
491 {
492     cairo_t *cr = cairo_create (csBoardWindow);
493
494     cairo_select_font_face (cr, "Sans",
495                             CAIRO_FONT_SLANT_NORMAL,
496                             CAIRO_FONT_WEIGHT_NORMAL);
497
498     cairo_set_font_size (cr, 12.0);
499
500     cairo_move_to (cr, x, y+4);
501     cairo_set_source_rgba(cr, 0, 0, 0,1.0);
502     cairo_show_text( cr, buf);
503
504     /* free memory */
505     cairo_destroy (cr);
506     GraphExpose(currBoard, x-5, y-10, 60, 15);
507 }
508
509 void DrawSeekDot(int x, int y, int colorNr)
510 {
511     cairo_t *cr = cairo_create (csBoardWindow);
512     int square = colorNr & 0x80;
513     colorNr &= 0x7F;
514
515     if(square)
516         cairo_rectangle (cr, x-squareSize/9, y-squareSize/9, 2*(squareSize/9), 2*(squareSize/9));
517     else
518         cairo_arc(cr, x, y, squareSize/9, 0.0, 2*M_PI);
519
520     SetPen(cr, 2, "#000000", 0);
521     cairo_stroke_preserve(cr);
522     switch (colorNr) {
523       case 0: cairo_set_source_rgba(cr, 1.0, 0, 0,1.0); break;
524       case 1: cairo_set_source_rgba (cr, 0.0, 0.7, 0.2, 1.0); break;
525       default: cairo_set_source_rgba (cr, 1.0, 1.0, 0.0, 1.0); break;
526     }
527     cairo_fill(cr);
528
529     /* free memory */
530     cairo_destroy (cr);
531     GraphExpose(currBoard, x-squareSize/8, y-squareSize/8, 2*(squareSize/8), 2*(squareSize/8));
532 }
533
534 void
535 InitDrawingHandle (Option *opt)
536 {
537     csBoardWindow = DRAWABLE(opt);
538 }
539
540 void
541 CreateGrid ()
542 {
543     int i, j;
544
545     if (lineGap == 0) return;
546
547     /* [HR] Split this into 2 loops for non-square boards. */
548
549     for (i = 0; i < BOARD_HEIGHT + 1; i++) {
550         gridSegments[i].x1 = 0;
551         gridSegments[i].x2 =
552           lineGap + BOARD_WIDTH * (squareSize + lineGap);
553         gridSegments[i].y1 = gridSegments[i].y2
554           = lineGap / 2 + (i * (squareSize + lineGap));
555     }
556
557     for (j = 0; j < BOARD_WIDTH + 1; j++) {
558         gridSegments[j + i].y1 = 0;
559         gridSegments[j + i].y2 =
560           lineGap + BOARD_HEIGHT * (squareSize + lineGap);
561         gridSegments[j + i].x1 = gridSegments[j + i].x2
562           = lineGap / 2 + (j * (squareSize + lineGap));
563     }
564 }
565
566 void
567 DrawGrid()
568 {
569   /* draws a grid starting around Nx, Ny squares starting at x,y */
570   int i;
571   float odd = (lineGap & 1)/2.;
572   cairo_t *cr;
573
574   /* get a cairo_t */
575   cr = cairo_create (csBoardWindow);
576
577   cairo_set_antialias (cr, CAIRO_ANTIALIAS_NONE);
578   SetPen(cr, lineGap, "#000000", 0);
579
580   /* lines in X */
581   for (i = 0; i < BOARD_WIDTH + BOARD_HEIGHT + 2; i++)
582     {
583       int h = (gridSegments[i].y1 == gridSegments[i].y2); // horizontal
584       cairo_move_to (cr, gridSegments[i].x1 + !h*odd, gridSegments[i].y1 + h*odd);
585       cairo_line_to (cr, gridSegments[i].x2 + !h*odd, gridSegments[i].y2 + h*odd);
586       cairo_stroke (cr);
587     }
588
589   /* free memory */
590   cairo_destroy (cr);
591
592   return;
593 }
594
595 void
596 DrawBorder (int x, int y, int type, int odd)
597 {
598     cairo_t *cr;
599     char *col;
600
601     switch(type) {
602         case 0: col = "#000000"; break;
603         case 1: col = appData.highlightSquareColor; break;
604         case 2: col = appData.premoveHighlightColor; break;
605         default: col = "#808080"; break; // cannot happen
606     }
607     cr = cairo_create(csBoardWindow);
608     cairo_set_antialias(cr, CAIRO_ANTIALIAS_NONE);
609     cairo_rectangle(cr, x+odd/2., y+odd/2., squareSize+lineGap, squareSize+lineGap);
610     SetPen(cr, lineGap, col, 0);
611     cairo_stroke(cr);
612     cairo_destroy(cr);
613     GraphExpose(currBoard, x - lineGap/2, y - lineGap/2, squareSize+2*lineGap+odd, squareSize+2*lineGap+odd);
614 }
615
616 static int
617 CutOutSquare (int x, int y, int *x0, int *y0, int  kind)
618 {
619     int W = BOARD_WIDTH, H = BOARD_HEIGHT;
620     int nx = x/(squareSize + lineGap), ny = y/(squareSize + lineGap);
621     *x0 = 0; *y0 = 0;
622     if(textureW[kind] < squareSize || textureH[kind] < squareSize) return 0;
623     if(textureW[kind] < W*squareSize)
624         *x0 = (textureW[kind] - squareSize) * nx/(W-1);
625     else
626         *x0 = textureW[kind]*nx / W + (textureW[kind] - W*squareSize) / (2*W);
627     if(textureH[kind] < H*squareSize)
628         *y0 = (textureH[kind] - squareSize) * ny/(H-1);
629     else
630         *y0 = textureH[kind]*ny / H + (textureH[kind] - H*squareSize) / (2*H);
631     return 1;
632 }
633
634 void
635 DrawLogo (Option *opt, void *logo)
636 {
637     cairo_surface_t *img;
638     cairo_t *cr;
639     int w, h;
640
641     if(!logo || !opt) return;
642     img = cairo_image_surface_create_from_png (logo);
643     w = cairo_image_surface_get_width (img);
644     h = cairo_image_surface_get_height (img);
645     cr = cairo_create(DRAWABLE(opt));
646 //    cairo_scale(cr, (float)appData.logoSize/w, appData.logoSize/(2.*h));
647     cairo_scale(cr, (float)opt->max/w, (float)opt->value/h);
648     cairo_set_source_surface (cr, img, 0, 0);
649     cairo_paint (cr);
650     cairo_destroy (cr);
651     cairo_surface_destroy (img);
652     GraphExpose(opt, 0, 0, appData.logoSize, appData.logoSize/2);
653 }
654
655 static void
656 BlankSquare (cairo_surface_t *dest, int x, int y, int color, ChessSquare piece, int fac)
657 {   // [HGM] extra param 'fac' for forcing destination to (0,0) for copying to animation buffer
658     int x0, y0;
659     cairo_t *cr;
660
661     cr = cairo_create (dest);
662
663     if ((useTexture & color+1) && CutOutSquare(x, y, &x0, &y0, color)) {
664             cairo_set_source_surface (cr, pngBoardBitmap[color], x*fac - x0, y*fac - y0);
665             cairo_set_antialias (cr, CAIRO_ANTIALIAS_NONE);
666             cairo_rectangle (cr, x*fac, y*fac, squareSize, squareSize);
667             cairo_fill (cr);
668             cairo_destroy (cr);
669     } else { // evenly colored squares
670         char *col = NULL;
671         switch (color) {
672           case 0: col = appData.darkSquareColor; break;
673           case 1: col = appData.lightSquareColor; break;
674           case 2: col = "#000000"; break;
675           default: col = "#808080"; break; // cannot happen
676         }
677         SetPen(cr, 2.0, col, 0);
678         cairo_rectangle (cr, fac*x, fac*y, squareSize, squareSize);
679         cairo_set_antialias (cr, CAIRO_ANTIALIAS_NONE);
680         cairo_fill (cr);
681         cairo_destroy (cr);
682     }
683 }
684
685 static void
686 pngDrawPiece (cairo_surface_t *dest, ChessSquare piece, int square_color, int x, int y)
687 {
688     int kind;
689     cairo_t *cr;
690
691     if ((int)piece < (int) BlackPawn) {
692         kind = 0;
693     } else {
694         kind = 1;
695         piece -= BlackPawn;
696     }
697     if(appData.upsideDown && flipView) kind = 1 - kind; // swap white and black pieces
698     BlankSquare(dest, x, y, square_color, piece, 1); // erase previous contents with background
699     cr = cairo_create (dest);
700     cairo_set_source_surface (cr, pngPieceBitmaps[kind][piece], x, y);
701     cairo_paint(cr);
702     cairo_destroy (cr);
703 }
704
705 static char *markerColor[8] = { "#FFFF00", "#FF0000", "#00FF00", "#0000FF", "#00FFFF", "#FF00FF", "#FFFFFF", "#000000" };
706
707 void
708 DoDrawDot (cairo_surface_t *cs, int marker, int x, int y, int r)
709 {
710         cairo_t *cr;
711
712         cr = cairo_create(cs);
713         cairo_arc(cr, x+r/2, y+r/2, r/2, 0.0, 2*M_PI);
714         if(appData.monoMode) {
715             SetPen(cr, 2, marker == 2 ? "#000000" : "#FFFFFF", 0);
716             cairo_stroke_preserve(cr);
717             SetPen(cr, 2, marker == 2 ? "#FFFFFF" : "#000000", 0);
718         } else {
719             SetPen(cr, 2, markerColor[marker-1], 0);
720         }
721         cairo_fill(cr);
722
723         cairo_destroy(cr);
724 }
725
726 void
727 DrawDot (int marker, int x, int y, int r)
728 { // used for atomic captures; no need to draw on backup
729   DoDrawDot(csBoardWindow, marker, x, y, r);
730   GraphExpose(currBoard, x-r, y-r, 2*r, 2*r);
731 }
732
733 static void
734 DrawText (char *string, int x, int y, int align)
735 {
736         int xx = x, yy = y;
737         cairo_text_extents_t te;
738         cairo_t *cr;
739
740         cr = cairo_create (csBoardWindow);
741         cairo_select_font_face (cr, "Sans",
742                     CAIRO_FONT_SLANT_NORMAL,
743                     CAIRO_FONT_WEIGHT_BOLD);
744
745         cairo_set_font_size (cr, align < 0 ? 2*squareSize/3 : squareSize/4);
746         // calculate where it goes
747         cairo_text_extents (cr, string, &te);
748
749         if (align == 1) {
750             xx += squareSize - te.width - te.x_bearing - 1;
751             yy += squareSize - te.height - te.y_bearing - 1;
752         } else if (align == 2) {
753             xx += te.x_bearing + 1, yy += -te.y_bearing + 1;
754         } else if (align == 3) {
755             xx += squareSize - te.width -te.x_bearing - 1;
756             yy += -te.y_bearing + 3;
757         } else if (align == 4) {
758             xx += te.x_bearing + 1, yy += -te.y_bearing + 3;
759         } else if (align < 0) {
760             xx += squareSize/2 - te.width/2, yy += 9*squareSize/16 - te.y_bearing/2;
761         }
762
763         cairo_move_to (cr, xx-1, yy);
764         if(align == -2) cairo_set_source_rgb (cr, 1.0, 0.0, 0.0); else
765         if(align < 3) cairo_set_source_rgb (cr, 0.0, 0.0, 0.0);
766         else          cairo_set_source_rgb (cr, 1.0, 1.0, 1.0);
767         cairo_show_text (cr, string);
768         cairo_destroy (cr);
769 }
770
771 void
772 InscribeKanji (ChessSquare piece, int x, int y)
773 {
774     char *p, *q, buf[10];
775     int n;
776     if(piece == EmptySquare) return;
777     if(piece >= BlackPawn) piece = BLACK_TO_WHITE piece;
778     p = appData.inscriptions;
779     n = piece;
780     while(piece > WhitePawn) {
781       if(*p++ == NULLCHAR) {
782         if(n != WhiteKing) return;
783         p = q;
784         break;
785       }
786       q = p - 1;
787       while((*p & 0xC0) == 0x80) p++; // skip UTF-8 continuation bytes
788       piece--;
789     }
790     strncpy(buf, p, 10);
791     for(q=buf; (*++q & 0xC0) == 0x80;);
792     *q = NULLCHAR;
793     DrawText(buf, x, y, n > WhiteLion ? -2 : -1);
794 }
795
796 void
797 DrawOneSquare (int x, int y, ChessSquare piece, int square_color, int marker, char *tString, char *bString, int align)
798 {   // basic front-end board-draw function: takes care of everything that can be in square:
799     // piece, background, coordinate/count, marker dot
800
801     if (piece == EmptySquare) {
802         BlankSquare(csBoardWindow, x, y, square_color, piece, 1);
803     } else {
804         pngDrawPiece(csBoardWindow, piece, square_color, x, y);
805         if(appData.inscriptions[0]) InscribeKanji(piece, x, y);
806     }
807
808     if(align) { // square carries inscription (coord or piece count)
809         if(align > 1) DrawText(tString, x, y, align);       // top (rank or count)
810         if(bString && *bString) DrawText(bString, x, y, 1); // bottom (always lower right file ID)
811     }
812
813     if(marker) { // print fat marker dot, if requested
814         DoDrawDot(csBoardWindow, marker, x + squareSize/4, y+squareSize/4, squareSize/2);
815     }
816 }
817
818 /****   Animation code by Hugh Fisher, DCS, ANU. ****/
819
820 /*      Masks for XPM pieces. Black and white pieces can have
821         different shapes, but in the interest of retaining my
822         sanity pieces must have the same outline on both light
823         and dark squares, and all pieces must use the same
824         background square colors/images.                */
825
826 static cairo_surface_t *c_animBufs[3*NrOfAnims]; // newBuf, saveBuf
827
828 static void
829 InitAnimState (AnimNr anr)
830 {
831     if(c_animBufs[anr]) cairo_surface_destroy (c_animBufs[anr]);
832     if(c_animBufs[anr+2]) cairo_surface_destroy (c_animBufs[anr+2]);
833     c_animBufs[anr+4] = csBoardWindow;
834     c_animBufs[anr+2] = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, squareSize, squareSize);
835     c_animBufs[anr] = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, squareSize, squareSize);
836 }
837
838 void
839 CreateAnimVars ()
840 {
841   InitAnimState(Game);
842   InitAnimState(Player);
843 }
844
845 static void
846 CairoOverlayPiece (ChessSquare piece, cairo_surface_t *dest)
847 {
848   static cairo_t *pieceSource;
849   pieceSource = cairo_create (dest);
850   cairo_set_source_surface (pieceSource, pngPieceBitmaps[!White(piece)][piece % BlackPawn], 0, 0);
851   if(doubleClick) cairo_paint_with_alpha (pieceSource, 0.6);
852   else cairo_paint(pieceSource);
853   cairo_destroy (pieceSource);
854 }
855
856 void
857 InsertPiece (AnimNr anr, ChessSquare piece)
858 {
859     CairoOverlayPiece(piece, c_animBufs[anr]);
860 }
861
862 void
863 DrawBlank (AnimNr anr, int x, int y, int startColor)
864 {
865     BlankSquare(c_animBufs[anr+2], x, y, startColor, EmptySquare, 0);
866 }
867
868 void CopyRectangle (AnimNr anr, int srcBuf, int destBuf,
869                  int srcX, int srcY, int width, int height, int destX, int destY)
870 {
871         cairo_t *cr;
872         c_animBufs[anr+4] = csBoardWindow;
873         cr = cairo_create (c_animBufs[anr+destBuf]);
874         cairo_set_source_surface (cr, c_animBufs[anr+srcBuf], destX - srcX, destY - srcY);
875         cairo_rectangle (cr, destX, destY, width, height);
876         cairo_fill (cr);
877         cairo_destroy (cr);
878         if(c_animBufs[anr+destBuf] == csBoardWindow) // suspect that GTK needs this!
879             GraphExpose(currBoard, destX, destY, width, height);
880 }
881
882 void
883 SetDragPiece (AnimNr anr, ChessSquare piece)
884 {
885 }
886
887 /* [AS] Arrow highlighting support */
888
889 void
890 DoDrawPolygon (cairo_surface_t *cs, Pnt arrow[], int nr)
891 {
892     cairo_t *cr;
893     int i;
894     cr = cairo_create (cs);
895     cairo_move_to (cr, arrow[nr-1].x, arrow[nr-1].y);
896     for (i=0;i<nr;i++) {
897         cairo_line_to(cr, arrow[i].x, arrow[i].y);
898     }
899     if(appData.monoMode) { // should we always outline arrow?
900         cairo_line_to(cr, arrow[0].x, arrow[0].y);
901         SetPen(cr, 2, "#000000", 0);
902         cairo_stroke_preserve(cr);
903     }
904     SetPen(cr, 2, appData.highlightSquareColor, 0);
905     cairo_fill(cr);
906
907     /* free memory */
908     cairo_destroy (cr);
909 }
910
911 void
912 DrawPolygon (Pnt arrow[], int nr)
913 {
914     DoDrawPolygon(csBoardWindow, arrow, nr);
915 //    if(!dual) DoDrawPolygon(csBoardBackup, arrow, nr);
916 }
917
918 //-------------------- Eval Graph drawing routines (formerly in xevalgraph.h) --------------------
919
920 static void
921 ChoosePen(cairo_t *cr, int i)
922 {
923   switch(i) {
924     case PEN_BLACK:
925       SetPen(cr, 1.0, "#000000", 0);
926       break;
927     case PEN_DOTTED:
928       SetPen(cr, 1.0, "#A0A0A0", 1);
929       break;
930     case PEN_BLUEDOTTED:
931       SetPen(cr, 1.0, "#0000FF", 1);
932       break;
933     case PEN_BOLDWHITE:
934       SetPen(cr, 3.0, crWhite, 0);
935       break;
936     case PEN_BOLDBLACK:
937       SetPen(cr, 3.0, crBlack, 0);
938       break;
939     case PEN_BACKGD:
940       SetPen(cr, 3.0, "#E0E0F0", 0);
941       break;
942   }
943 }
944
945 // [HGM] front-end, added as wrapper to avoid use of LineTo and MoveToEx in other routines (so they can be back-end)
946 void
947 DrawSegment (int x, int y, int *lastX, int *lastY, int penType)
948 {
949   static int curX, curY;
950
951   if(penType != PEN_NONE) {
952     cairo_t *cr = cairo_create(DRAWABLE(disp));
953     cairo_set_antialias (cr, CAIRO_ANTIALIAS_NONE);
954     cairo_move_to (cr, curX, curY);
955     cairo_line_to (cr, x,y);
956     ChoosePen(cr, penType);
957     cairo_stroke (cr);
958     cairo_destroy (cr);
959   }
960
961   if(lastX != NULL) { *lastX = curX; *lastY = curY; }
962   curX = x; curY = y;
963 }
964
965 // front-end wrapper for drawing functions to do rectangles
966 void
967 DrawRectangle (int left, int top, int right, int bottom, int side, int style)
968 {
969   cairo_t *cr;
970
971   cr = cairo_create (DRAWABLE(disp));
972   cairo_set_antialias (cr, CAIRO_ANTIALIAS_NONE);
973   cairo_rectangle (cr, left, top, right-left, bottom-top);
974   switch(side)
975     {
976     case 0: ChoosePen(cr, PEN_BOLDWHITE); break;
977     case 1: ChoosePen(cr, PEN_BOLDBLACK); break;
978     case 2: ChoosePen(cr, PEN_BACKGD); break;
979     }
980   cairo_fill (cr);
981
982   if(style != FILLED)
983     {
984       cairo_rectangle (cr, left, top, right-left-1, bottom-top-1);
985       ChoosePen(cr, PEN_BLACK);
986       cairo_stroke (cr);
987     }
988
989   cairo_destroy(cr);
990 }
991
992 // front-end wrapper for putting text in graph
993 void
994 DrawEvalText (char *buf, int cbBuf, int y)
995 {
996     // the magic constants 8 and 5 should really be derived from the font size somehow
997   cairo_text_extents_t extents;
998   cairo_t *cr = cairo_create(DRAWABLE(disp));
999
1000   /* GTK-TODO this has to go into the font-selection */
1001   cairo_select_font_face (cr, "Sans",
1002                           CAIRO_FONT_SLANT_NORMAL,
1003                           CAIRO_FONT_WEIGHT_NORMAL);
1004   cairo_set_font_size (cr, 12.0);
1005
1006
1007   cairo_text_extents (cr, buf, &extents);
1008
1009   cairo_move_to (cr, MarginX - 2 - 8*cbBuf, y+5);
1010   cairo_text_path (cr, buf);
1011   cairo_set_source_rgb (cr, 0.0, 0.0, 0);
1012   cairo_fill_preserve (cr);
1013   cairo_set_source_rgb (cr, 0, 1.0, 0);
1014   cairo_set_line_width (cr, 0.1);
1015   cairo_stroke (cr);
1016
1017   /* free memory */
1018   cairo_destroy (cr);
1019 }