Also use a single definition of the Error string.
[cboard.git] / src / cboard.c
blobe8589b4d5191da33694435b39b5a3dd83b43b287
1 /* vim:tw=78:ts=8:sw=4:set ft=c: */
2 /*
3 Copyright (C) 2002-2013 Ben Kibbey <bjk@luxsci.net>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #ifdef HAVE_CONFIG_H
20 #include <config.h>
21 #endif
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <unistd.h>
26 #include <sys/types.h>
27 #include <sys/socket.h>
28 #include <sys/stat.h>
29 #include <string.h>
30 #include <errno.h>
31 #include <ctype.h>
32 #include <pwd.h>
33 #include <signal.h>
34 #include <time.h>
35 #include <err.h>
36 #include <locale.h>
38 #ifdef HAVE_STDARG_H
39 #include <stdarg.h>
40 #endif
42 #ifdef HAVE_SYS_WAIT_H
43 #include <sys/wait.h>
44 #endif
46 #ifdef HAVE_REGEX_H
47 #include <regex.h>
48 #endif
50 #ifdef WITH_LIBPERL
51 #include "perl-plugin.h"
52 #endif
54 #include "common.h"
55 #include "conf.h"
56 #include "window.h"
57 #include "message.h"
58 #include "colors.h"
59 #include "input.h"
60 #include "misc.h"
61 #include "engine.h"
62 #include "strings.h"
63 #include "menu.h"
64 #include "keys.h"
65 #include "rcfile.h"
66 #include "filebrowser.h"
68 #ifdef DEBUG
69 #include <debug.h>
70 #endif
72 #define COPYRIGHT "Copyright (C) 2002-2013 " PACKAGE_BUGREPORT
73 #define LINE_GRAPHIC(c) ((!config.linegraphics) ? ' ' : c)
74 #define ROWTOMATRIX(r) ((8 - r) * 2 + 2 - 1)
75 #define COLTOMATRIX(c) ((c == 1) ? 1 : c * 4 - 3)
76 #define STATUS_HEIGHT 12
77 #define MEGA_BOARD (LINES >= 50 && COLS >= 144)
78 #define BOARD_HEIGHT_MB (50)
79 #define BOARD_WIDTH_MB (98)
80 #define STATUS_WIDTH_MB (COLS - BOARD_WIDTH_MB)
81 #define TAG_HEIGHT_MB (20)
82 #define TAG_WIDTH_MB (COLS - BOARD_WIDTH_MB)
83 #define HISTORY_HEIGHT_MB (LINES - (STATUS_HEIGHT + TAG_HEIGHT_MB + 1))
84 #define HISTORY_WIDTH_MB (COLS - BOARD_WIDTH_MB)
85 #define BIG_BOARD (LINES >= 40 && COLS >= 112)
86 #define BOARD_HEIGHT ((MEGA_BOARD) ? BOARD_HEIGHT_MB : (BIG_BOARD) ? 34 : 18)
87 #define BOARD_WIDTH ((MEGA_BOARD) ? BOARD_WIDTH_MB : (BIG_BOARD) ? 66 : 34)
88 #define STATUS_WIDTH ((MEGA_BOARD) ? STATUS_WIDTH_MB : COLS - BOARD_WIDTH)
89 #define TAG_HEIGHT ((MEGA_BOARD) ? TAG_HEIGHT_MB : LINES - STATUS_HEIGHT - 1)
90 #define TAG_WIDTH ((MEGA_BOARD) ? TAG_WIDTH_MB : COLS - BOARD_WIDTH)
91 #define HISTORY_HEIGHT ((MEGA_BOARD) ? HISTORY_HEIGHT_MB : LINES - BOARD_HEIGHT)
92 #define HISTORY_WIDTH ((MEGA_BOARD) ? HISTORY_WIDTH_MB : COLS - STATUS_WIDTH)
93 #define MAX_VALUE_WIDTH (COLS - 8)
95 enum {
96 UP, DOWN, LEFT, RIGHT
99 static WINDOW *boardw;
100 static PANEL *boardp;
101 static WINDOW *tagw;
102 static PANEL *tagp;
103 static WINDOW *statusw;
104 static PANEL *statusp;
105 static WINDOW *historyw;
106 static PANEL *historyp;
107 static WINDOW *loadingw;
108 static PANEL *loadingp;
109 static WINDOW *enginew;
110 static PANEL *enginep;
112 static char gameexp[255];
113 static char moveexp[255];
114 static struct itimerval clock_timer;
115 static int delete_count = 0;
116 static int markstart = -1, markend = -1;
117 static int keycount;
118 static char loadfile[FILENAME_MAX];
119 static int quit;
120 static wint_t input_c;
122 // Loaded filename from the command line or from the file input dialog.
123 static int filetype;
124 enum {
125 FILE_NONE, FILE_PGN, FILE_FEN, FILE_EPD
128 static char **nags;
129 static int nag_total;
130 static int macro_match;
132 // Primer movimiento de juego cargado
133 // First move loaded game
134 static char fm_loaded_file = FALSE;
135 // Movimiento resultado de la función 'do_play_go'
136 // Movement function result 'do_play_go'
137 static int go_move = 0;
138 // Controla rotación de tablero
139 // Rotation control board
140 static int rotate = FALSE;
142 static int COLS_OLD, LINES_OLD;
144 // Status window.
145 static struct {
146 wchar_t *notify; // The status window notification line buffer.
147 } status;
149 static int curses_initialized;
151 // When in history mode a full step is to the next move of the same playing
152 // side. Half stepping is alternating sides.
153 static int movestep;
155 static wchar_t *w_pawn_wchar;
156 static wchar_t *w_rook_wchar;
157 static wchar_t *w_bishop_wchar;
158 static wchar_t *w_knight_wchar;
159 static wchar_t *w_queen_wchar;
160 static wchar_t *w_king_wchar;
161 static wchar_t *b_pawn_wchar;
162 static wchar_t *b_rook_wchar;
163 static wchar_t *b_bishop_wchar;
164 static wchar_t *b_knight_wchar;
165 static wchar_t *b_queen_wchar;
166 static wchar_t *b_king_wchar;
167 static wchar_t *empty_wchar;
168 static wchar_t *enpassant_wchar;
170 static wchar_t *yes_wchar;
171 static wchar_t *all_wchar; // do_save_game_overwrite_confirm()
172 static wchar_t *overwrite_wchar; // do_save_game_overwrite_confirm()
173 static wchar_t *resume_wchar; // do_history_mode_confirm()
174 static wchar_t *current_wchar; // do_game_save_multi_confirm()
175 static wchar_t *append_wchar; // save_pgn()
177 static const char piece_chars[] = "PpRrNnBbQqKkxx";
178 static char *translatable_tag_names[7];
179 static const char *f_pieces[] = {
180 " ", // 0
181 " O ",
182 " /_\\ ",
183 " |-|-| ", // 3
184 " ] [ ",
185 " /___\\ ",
186 " /?M ", // 6
187 " (@/)) ",
188 " /__))",
189 " O ", // 9
190 " (+) ",
191 " /_\\ ",
192 "•°°°°°•",// 12
193 " \\\\|// ",
194 " |___| ",
195 " __+__ ", // 15
196 "(__|__)",
197 " |___| ",
198 " \\ / ", // 18
199 " X ",
200 " / \\ "
203 static const bool cb[8][8] = {
204 {1,0,1,0,1,0,1,0},
205 {0,1,0,1,0,1,0,1},
206 {1,0,1,0,1,0,1,0},
207 {0,1,0,1,0,1,0,1},
208 {1,0,1,0,1,0,1,0},
209 {0,1,0,1,0,1,0,1},
210 {1,0,1,0,1,0,1,0},
211 {0,1,0,1,0,1,0,1}
214 static void free_userdata_once(GAME g);
216 // Posición por rotación de tablero.
217 // Rotation board position.
218 static void rotate_position(int p)
220 struct userdata_s *d = gp->data;
221 char fr, fc;
222 char fr2 = 8, fc2 = 8;
224 for (fr = 1; fr < 9; fr++) {
225 if (fr2 < 1)
226 fr2 = 8;
227 for (fc = 1; fc < 9; fc++){
228 if (fc2 < 1)
229 fc2 = 8;
230 if (p == CURSOR_POSITION &&
231 d->c_row == fr && d->c_col == fc) {
232 d->c_row = fr2;
233 d->c_col = fc2;
234 return;
236 else if (p == SP_POSITION &&
237 d->sp.row == fr && d->sp.col == fc) {
238 d->sp.row = fr2;
239 d->sp.col = fc2;
240 return;
242 else if (p == SPS_POSITION &&
243 d->sp.srow == fr && d->sp.scol == fc) {
244 d->sp.srow = fr2;
245 d->sp.scol = fc2;
246 return;
248 fc2--;
250 fr2--;
254 void update_cursor(GAME g, int idx)
256 char *p;
257 int len;
258 int t = pgn_history_total(g->hp);
259 struct userdata_s *d = g->data;
262 * If not deincremented then r and c would be the next move.
264 idx--;
266 if (idx > t || idx < 0 || !t || !g->hp[idx]->move) {
267 d->c_row = 2, d->c_col = 5;
268 goto historyrotate;
269 // return;
272 p = g->hp[idx]->move;
273 len = strlen(p);
275 if (*p == 'O') {
276 if (len <= 4)
277 d->c_col = rotate ? 3 : 7;
278 else
279 d->c_col = rotate ? 6 : 3;
281 if (rotate)
282 d->c_row = (g->turn == WHITE) ? 1 : 8;
283 else
284 d->c_row = (g->turn == WHITE) ? 8 : 1;
286 return;
289 p += len;
291 while (!isdigit(*p))
292 p--;
294 d->c_row = RANKTOINT(*p--);
295 d->c_col = FILETOINT(*p);
297 historyrotate:
298 if (d->mode == MODE_HISTORY && rotate)
299 rotate_position(CURSOR_POSITION);
302 static int init_nag()
304 FILE *fp;
305 char line[LINE_MAX];
306 int i = 0;
308 if ((fp = fopen(config.nagfile, "r")) == NULL) {
309 cmessage(ERROR_STR, ANY_KEY_STR, "%s: %s", config.nagfile, strerror(errno));
310 return 1;
313 nags = Realloc(nags, (i+2) * sizeof(char *));
314 nags[i++] = strdup(_("none"));
315 nags[i] = NULL;
317 while (!feof(fp)) {
318 if (fscanf(fp, " %[^\n] ", line) == 1) {
319 nags = Realloc(nags, (i + 2) * sizeof(char *));
320 nags[i++] = strdup(line);
324 nags[i] = NULL;
325 nag_total = i;
326 return 0;
329 void edit_nag_toggle_item(struct menu_input_s *m)
331 struct input_s *in = m->data;
332 struct input_data_s *id = in->data;
333 HISTORY *h = id->data;
334 int i;
336 if (m->selected == 0) {
337 for (i = 0; i < MAX_PGN_NAG; i++)
338 h->nag[i] = 0;
340 for (i = 0; m->items[i]; i++)
341 m->items[i]->selected = 0;
343 return;
346 for (i = 0; i < MAX_PGN_NAG; i++) {
347 if (h->nag[i] == m->selected)
348 h->nag[i] = m->selected = 0;
349 else {
350 if (!h->nag[i]) {
351 h->nag[i] = m->selected;
352 break;
358 void edit_nag_save(struct menu_input_s *m)
360 pushkey = -1;
363 void edit_nag_help(struct menu_input_s *m)
365 message(_("NAG Menu Keys"), ANY_KEY_STR, "%s",
367 " UP/DOWN - previous/next menu item\n"
368 " HOME/END - first/last menu item\n"
369 " PGDN/PGUP - next/previous page\n"
370 " a-zA-Z0-9 - jump to item\n"
371 " SPACE - toggle selected item\n"
372 " CTRL-X - quit with changes"
376 struct menu_item_s **get_nag_items(WIN *win)
378 int i, n;
379 struct menu_input_s *m = win->data;
380 struct input_s *in = m->data;
381 struct input_data_s *id = in->data;
382 struct menu_item_s **items = m->items;
383 HISTORY *h = id->data;
385 if (items) {
386 for (i = 0; items[i]; i++)
387 free(items[i]);
390 for (i = 0; nags[i]; i++) {
391 items = Realloc(items, (i+2) * sizeof(struct menu_item_s *));
392 items[i] = Malloc(sizeof(struct menu_item_s));
393 items[i]->name = nags[i];
394 items[i]->value = NULL;
396 for (n = 0; n < MAX_PGN_NAG; n++) {
397 if (h->nag[n] == i) {
398 items[i]->selected = 1;
399 n = -1;
400 break;
404 if (n >= 0)
405 items[i]->selected = 0;
408 items[i] = NULL;
409 m->nofree = 1;
410 m->items = items;
411 return items;
414 void nag_print(WIN *win)
416 struct menu_input_s *m = win->data;
418 mvwprintw(win->w, m->print_line, 1, "%-*s", win->cols - 2, m->item->name);
421 void edit_nag(void *arg)
423 struct menu_key_s **keys = NULL;
425 if (!nags) {
426 if (init_nag())
427 return;
430 add_menu_key(&keys, ' ', edit_nag_toggle_item);
431 add_menu_key(&keys, CTRL_KEY('x'), edit_nag_save);
432 add_menu_key(&keys, KEY_F(1), edit_nag_help);
433 construct_menu(0, 0, -1, -1, _("Numeric Annotation Glyphs"), 1, get_nag_items, keys, arg,
434 nag_print, NULL);
435 return;
438 static void *view_nag(void *arg)
440 HISTORY *h = (HISTORY *)arg;
441 char buf[80];
442 char line[LINE_MAX] = {0};
443 int i = 0;
445 snprintf(buf, sizeof(buf), "%s \"%s\"", _("Viewing NAG for"), h->move);
447 if (!nags) {
448 if (init_nag())
449 return NULL;
452 for (i = 0; i < MAX_PGN_NAG; i++) {
453 char buf2[16];
455 if (!h->nag[i])
456 break;
458 if (h->nag[i] >= nag_total)
459 strncat(line, itoa(h->nag[i], buf2), sizeof(line)-1);
460 else
461 strncat(line, nags[h->nag[i]], sizeof(line)-1);
463 strncat(line, "\n", sizeof(line)-1);
466 line[strlen(line) - 1] = 0;
467 message(buf, ANY_KEY_STR, "%s", line);
468 return NULL;
471 void view_annotation(HISTORY *h)
473 char buf[MAX_SAN_MOVE_LEN + strlen(_("Viewing Annotation for")) + 4];
474 int nag = 0, comment = 0;
476 if (!h)
477 return;
479 if (h->comment && h->comment[0])
480 comment++;
482 if (h->nag[0])
483 nag++;
485 if (!nag && !comment)
486 return;
488 snprintf(buf, sizeof(buf), "%s \"%s\"", _("Viewing Annotation for"), h->move);
490 if (comment)
491 construct_message(buf, (nag) ? _("Any other key to continue") : ANY_KEY_STR, 0, 1,
492 (nag) ? _("Press 'n' to view NAG") : NULL,
493 (nag) ? view_nag : NULL, (nag) ? h : NULL, NULL,
494 (nag) ? 'n' : 0, 0, "%s", h->comment);
495 else
496 construct_message(buf, _("Any other key to continue"), 0, 1, _("Press 'n' to view NAG"), view_nag, h, NULL,
497 'n', 0, "%s", _("No comment text for this move"));
500 int do_game_write(char *filename, char *mode, int start, int end)
502 int i;
503 struct userdata_s *d;
504 PGN_FILE *pgn;
506 i = pgn_open(filename, mode, &pgn);
508 if (i == E_PGN_ERR) {
509 cmessage(ERROR_STR, ANY_KEY_STR, "%s\n%s", filename, strerror(errno));
510 return 1;
512 else if (i == E_PGN_INVALID) {
513 cmessage(ERROR_STR, ANY_KEY_STR, "%s\n%s", filename, _("Not a regular file"));
514 return 1;
517 for (i = (start == -1) ? 0 : start; i < end; i++) {
518 d = game[i]->data;
519 pgn_write(pgn, game[i]);
520 CLEAR_FLAG(d->flags, CF_MODIFIED);
523 if (pgn_close(pgn) != E_PGN_OK)
524 message(ERROR_STR, ANY_KEY_STR, "%s", strerror(errno));
526 if (start == -1) {
527 strncpy(loadfile, filename, sizeof(loadfile));
528 loadfile[sizeof(loadfile)-1] = 0;
531 return 0;
534 struct save_game_s {
535 char *filename;
536 char *mode;
537 int start;
538 int end;
541 void do_save_game_overwrite_confirm(WIN *win)
543 char *mode = "w";
544 struct save_game_s *s = win->data;
545 wchar_t str[] = { win->c, 0 };
547 if (!wcscmp (str, append_wchar))
548 mode = "a";
549 else if (!wcscmp (str, overwrite_wchar))
550 mode = "w";
551 else
552 goto done;
554 if (do_game_write(s->filename, mode, s->start, s->end))
555 update_status_notify(gp, "%s", _("Save game failed."));
556 else
557 update_status_notify(gp, "%s", _("Game saved."));
559 done:
560 free(s->filename);
561 free(s);
564 /* If the saveindex argument is -1, all games will be saved. Otherwise it's a
565 * game index number.
567 void save_pgn(char *filename, int saveindex)
569 char buf[FILENAME_MAX];
570 struct stat st;
571 int end = (saveindex == -1) ? gtotal : saveindex + 1;
572 struct save_game_s *s;
574 if (filename[0] != '/' && config.savedirectory) {
575 if (stat(config.savedirectory, &st) == -1) {
576 if (errno == ENOENT) {
577 if (mkdir(config.savedirectory, 0755) == -1) {
578 cmessage(ERROR_STR, ANY_KEY_STR, "%s: %s", config.savedirectory,
579 strerror(errno));
580 return;
583 else {
584 cmessage(ERROR_STR, ANY_KEY_STR, "%s: %s", config.savedirectory,
585 strerror(errno));
586 return;
590 stat(config.savedirectory, &st);
592 if (!S_ISDIR(st.st_mode)) {
593 cmessage(ERROR_STR, ANY_KEY_STR, "%s: %s", config.savedirectory, _("Not a directory."));
594 return;
597 snprintf(buf, sizeof(buf), "%s/%s", config.savedirectory, filename);
598 filename = buf;
601 if (access(filename, W_OK) == 0) {
602 s = Malloc(sizeof(struct save_game_s));
603 s->filename = strdup(filename);
604 s->start = saveindex;
605 s->end = end;
606 construct_message(NULL, _("What would you like to do?"), 0, 1, NULL,
607 NULL, s, do_save_game_overwrite_confirm, 0, 0,
608 "%s \"%s\"\nPress \"%ls\" to append to this file, \"%ls\" to overwrite or any other key to cancel.",
609 _("File exists:"), filename, append_wchar,
610 overwrite_wchar);
611 return;
614 if (do_game_write(filename, "a", saveindex, end))
615 update_status_notify(gp, "%s", _("Save game failed."));
616 else
617 update_status_notify(gp, "%s", _("Game saved."));
620 static int castling_state(GAME g, BOARD b, int row, int col, int piece, int mod)
622 if (pgn_piece_to_int(piece) == ROOK && col == 7
623 && row == 7 &&
624 (TEST_FLAG(g->flags, GF_WK_CASTLE) || mod) &&
625 pgn_piece_to_int(b[7][4].icon) == KING && isupper(piece)) {
626 if (mod)
627 TOGGLE_FLAG(g->flags, GF_WK_CASTLE);
628 return 1;
630 else if (pgn_piece_to_int(piece) == ROOK && col == 0
631 && row == 7 &&
632 (TEST_FLAG(g->flags, GF_WQ_CASTLE) || mod) &&
633 pgn_piece_to_int(b[7][4].icon) == KING && isupper(piece)) {
634 if (mod)
635 TOGGLE_FLAG(g->flags, GF_WQ_CASTLE);
636 return 1;
638 else if (pgn_piece_to_int(piece) == ROOK && col == 7
639 && row == 0 &&
640 (TEST_FLAG(g->flags, GF_BK_CASTLE) || mod) &&
641 pgn_piece_to_int(b[0][4].icon) == KING && islower(piece)) {
642 if (mod)
643 TOGGLE_FLAG(g->flags, GF_BK_CASTLE);
644 return 1;
646 else if (pgn_piece_to_int(piece) == ROOK && col == 0
647 && row == 0 &&
648 (TEST_FLAG(g->flags, GF_BQ_CASTLE) || mod) &&
649 pgn_piece_to_int(b[0][4].icon) == KING && islower(piece)) {
650 if (mod)
651 TOGGLE_FLAG(g->flags, GF_BQ_CASTLE);
652 return 1;
654 else if (pgn_piece_to_int(piece) == KING && col == 4
655 && row == 7 &&
656 (mod || (pgn_piece_to_int(b[7][7].icon) == ROOK &&
657 TEST_FLAG(g->flags, GF_WK_CASTLE))
659 (pgn_piece_to_int(b[7][0].icon) == ROOK &&
660 TEST_FLAG(g->flags, GF_WQ_CASTLE))) && isupper(piece)) {
661 if (mod) {
662 if (TEST_FLAG(g->flags, GF_WK_CASTLE) ||
663 TEST_FLAG(g->flags, GF_WQ_CASTLE))
664 CLEAR_FLAG(g->flags, GF_WK_CASTLE|GF_WQ_CASTLE);
665 else
666 SET_FLAG(g->flags, GF_WK_CASTLE|GF_WQ_CASTLE);
668 return 1;
670 else if (pgn_piece_to_int(piece) == KING && col == 4
671 && row == 0 &&
672 (mod || (pgn_piece_to_int(b[0][7].icon) == ROOK &&
673 TEST_FLAG(g->flags, GF_BK_CASTLE))
675 (pgn_piece_to_int(b[0][0].icon) == ROOK &&
676 TEST_FLAG(g->flags, GF_BQ_CASTLE))) && islower(piece)) {
677 if (mod) {
678 if (TEST_FLAG(g->flags, GF_BK_CASTLE) ||
679 TEST_FLAG(g->flags, GF_BQ_CASTLE))
680 CLEAR_FLAG(g->flags, GF_BK_CASTLE|GF_BQ_CASTLE);
681 else
682 SET_FLAG(g->flags, GF_BK_CASTLE|GF_BQ_CASTLE);
684 return 1;
687 return 0;
690 #define IS_ENPASSANT(c) (c == 'x') ? CP_BOARD_ENPASSANT : isupper(c) ? CP_BOARD_WHITE : CP_BOARD_BLACK
691 #define ATTRS(cp) (cp & (A_BOLD|A_STANDOUT|A_BLINK|A_DIM|A_UNDERLINE|A_INVIS|A_REVERSE))
693 static void
694 init_wchar_pieces ()
696 w_pawn_wchar = str_to_wchar (config.utf8_pieces ? "♙" : "P");
697 w_rook_wchar = str_to_wchar (config.utf8_pieces ? "♖" : "R");
698 w_bishop_wchar = str_to_wchar (config.utf8_pieces ? "♗" : "B");
699 w_knight_wchar = str_to_wchar (config.utf8_pieces ? "♘" : "N");
700 w_queen_wchar = str_to_wchar (config.utf8_pieces ? "♕" : "Q");
701 w_king_wchar = str_to_wchar (config.utf8_pieces ? "♔" : "K");
702 b_pawn_wchar = str_to_wchar (config.utf8_pieces ? "♟" : "p");
703 b_rook_wchar = str_to_wchar (config.utf8_pieces ? "♜" : "r");
704 b_bishop_wchar = str_to_wchar (config.utf8_pieces ? "♝" : "b");
705 b_knight_wchar = str_to_wchar (config.utf8_pieces ? "♞" : "n");
706 b_queen_wchar = str_to_wchar (config.utf8_pieces ? "♛" : "q");
707 b_king_wchar = str_to_wchar (config.utf8_pieces ? "♚" : "k");
708 empty_wchar = str_to_wchar (" ");
709 enpassant_wchar = str_to_wchar ("x");
712 static wchar_t *
713 piece_to_wchar (unsigned char p)
715 switch (p)
717 case 'P':
718 return w_pawn_wchar;
719 case 'p':
720 return b_pawn_wchar;
721 case 'R':
722 return w_rook_wchar;
723 case 'r':
724 return b_rook_wchar;
725 case 'B':
726 return w_bishop_wchar;
727 case 'b':
728 return b_bishop_wchar;
729 case 'N':
730 return w_knight_wchar;
731 case 'n':
732 return b_knight_wchar;
733 case 'Q':
734 return w_queen_wchar;
735 case 'q':
736 return b_queen_wchar;
737 case 'K':
738 return w_king_wchar;
739 case 'k':
740 return b_king_wchar;
741 case 'x':
742 return enpassant_wchar;
745 return empty_wchar;
748 static int piece_can_attack (GAME g, int rank, int file)
750 struct userdata_s *d = g->data;
751 char *m, *frfr = NULL;
752 pgn_error_t e;
753 int row, col, p;
754 int v = d->b[RANKTOBOARD (d->c_row)][FILETOBOARD (d->c_col)].valid;
755 int pi = pgn_piece_to_int (d->b[RANKTOBOARD (rank)][FILETOBOARD (file)].icon);
756 int cpi = d->sp.icon
757 ? pgn_piece_to_int (d->b[RANKTOBOARD (d->sp.srow)][FILETOBOARD (d->sp.scol)].icon)
758 : pgn_piece_to_int (d->b[RANKTOBOARD (d->c_row)][FILETOBOARD (d->c_col)].icon);
760 if (pi == OPEN_SQUARE || cpi == OPEN_SQUARE || !VALIDFILE (file)
761 || !VALIDRANK (rank))
762 return 0;
764 if (d->sp.icon) {
765 col = v ? d->c_col : d->sp.scol;
766 row = v ? d->c_row : d->sp.srow;
768 else {
769 col = d->c_col;
770 row = d->c_row;
773 m = malloc(MAX_SAN_MOVE_LEN+1);
774 m[0] = INTTOFILE (file);
775 m[1] = INTTORANK (rank);
776 m[2] = INTTOFILE (col);
777 m[3] = INTTORANK (row);
778 m[4] = 0;
780 if (d->sp.icon && v) {
781 BOARD b;
783 memcpy (b, d->b, sizeof(BOARD));
784 p = b[RANKTOBOARD (d->sp.srow)][FILETOBOARD (d->sp.scol)].icon;
785 b[RANKTOBOARD (d->sp.srow)][FILETOBOARD (d->sp.scol)].icon =
786 pgn_int_to_piece (WHITE, OPEN_SQUARE);
787 b[RANKTOBOARD (row)][FILETOBOARD (col)].icon = p;
788 pgn_switch_turn(g);
789 e = pgn_validate_move (g, b, &m, &frfr);
790 pgn_switch_turn (g);
791 free (m);
792 free (frfr);
793 return e == E_PGN_OK ? 1 : 0;
796 pgn_switch_turn(g);
797 e = pgn_validate_move (g, d->b, &m, &frfr);
798 pgn_switch_turn (g);
800 if (!strcmp (m, "O-O") || !strcmp (m, "O-O-O"))
801 e = E_PGN_INVALID;
803 if (e == E_PGN_OK) {
804 int sf = FILETOINT (frfr[0]), sr = RANKTOINT (frfr[1]);
805 int df = FILETOINT (frfr[2]);
807 pi = d->b[RANKTOBOARD (sr)][FILETOBOARD (sf)].icon;
808 pi = pgn_piece_to_int (pi);
809 if (pi == PAWN && sf == df)
810 e = E_PGN_INVALID;
813 free (m);
814 free (frfr);
815 return e == E_PGN_OK ? 1 : 0;
818 void print_piece(WINDOW *w, int l, int c, char p)
820 int i, y, ff = 0;
822 for (i = 0; i < 13; i += 2) {
823 if (p == piece_chars[i] || p == piece_chars[i + 1]) {
824 for (y = 0; y < 3; y++)
825 mvwprintw(w, l + y, c, "%s", f_pieces[i + ff + y]);
826 return;
829 ff++;
832 for (y = 0; y < 3; y++)
833 mvwprintw(w, l + y, c, f_pieces[0]);
836 int inv_int(int x)
838 int fx, fx2 = 8;
840 for (fx = 1; fx < 9; fx++) {
841 if (x == fx)
842 break;
843 fx2--;
846 return fx2;
849 // FIXME: BIG_BOARD - start in dwm monocle layout.
850 // Example: lxterminal -e cboard (dmenu, geany, etc.)
851 void update_board_window(GAME g)
853 int row, col;
854 int bcol = 0, brow = 0;
855 int l = config.coordsyleft;
856 int maxy = BOARD_HEIGHT, maxx = BOARD_WIDTH;
857 int ncols = 0, offset = 1;
858 int rowr = (MEGA_BOARD) ? 6 : (BIG_BOARD) ? 4 : 2;
859 int colr = (MEGA_BOARD) ? 12 : (BIG_BOARD) ? 8 : 4;
860 unsigned coords_y = 8, cxgc = 0;
861 unsigned i, cpd = 0;
862 struct userdata_s *d = g->data;
864 if (d->mode != MODE_PLAY && d->mode != MODE_EDIT)
865 update_cursor(g, g->hindex);
867 if (BIG_BOARD) {
868 if (rotate) {
869 brow = 7;
870 coords_y = 1;
873 else {
874 if (rotate) {
875 brow = 1;
876 coords_y = 1;
878 else
879 brow = 8;
882 for (row = 0; row < maxy; row++) {
883 if (BIG_BOARD) {
884 if (rotate)
885 bcol = 7;
886 else
887 bcol = 0;
889 else {
890 if (rotate)
891 bcol = 8;
892 else
893 bcol = 1;
896 for (col = 0; col < maxx; col++) {
897 int attrwhich = -1;
898 chtype attrs = 0, old_attrs = 0;
899 unsigned char p;
900 int can_attack = 0;
901 int valid = 0;
903 if (row == 0 || row == maxy - 2) {
904 if (col == 0)
905 mvwaddch(boardw, row, col + l,
906 LINE_GRAPHIC((row)
907 ? ACS_LLCORNER | CP_BOARD_GRAPHICS
908 : ACS_ULCORNER | CP_BOARD_GRAPHICS));
909 else if (col == maxx - 2)
910 mvwaddch(boardw, row, col + l,
911 LINE_GRAPHIC((row)
912 ? ACS_LRCORNER | CP_BOARD_GRAPHICS
913 : ACS_URCORNER | CP_BOARD_GRAPHICS));
914 else if (!(col % colr))
915 mvwaddch(boardw, row, col + l,
916 LINE_GRAPHIC((row)
917 ? ACS_BTEE | CP_BOARD_GRAPHICS
918 : ACS_TTEE | CP_BOARD_GRAPHICS));
919 else {
920 if (col != maxx - 1)
921 mvwaddch(boardw, row, col + l,
922 LINE_GRAPHIC(ACS_HLINE | CP_BOARD_GRAPHICS));
925 continue;
928 if ((row % 2) && col == maxx - 1 &&
929 (coords_y > 0 && coords_y < 9)) {
930 wattron(boardw, CP_BOARD_COORDS);
931 mvwprintw(boardw,
932 (BIG_BOARD) ? row * ((MEGA_BOARD) ? 3 : 2)
933 : row, (l) ? 0 : col, "%d",
934 (rotate) ? coords_y++ : coords_y--);
935 wattroff(boardw, CP_BOARD_COORDS);
936 continue;
939 if ((col == 0 || col == maxx - 2) && row != maxy - 1) {
940 if (!(row % rowr))
941 mvwaddch(boardw, row, col + l,
942 LINE_GRAPHIC((col) ?
943 ACS_RTEE | CP_BOARD_GRAPHICS :
944 ACS_LTEE | CP_BOARD_GRAPHICS));
945 else
946 mvwaddch(boardw, row, col + l,
947 LINE_GRAPHIC(ACS_VLINE | CP_BOARD_GRAPHICS));
949 continue;
952 if ((row % rowr) && !(col % colr) && row != maxy - 1) {
953 mvwaddch(boardw, row, col + l,
954 LINE_GRAPHIC(ACS_VLINE | CP_BOARD_GRAPHICS));
955 continue;
958 if (!(col % colr) && row != maxy - 1) {
959 mvwaddch(boardw, row, col + l,
960 LINE_GRAPHIC(ACS_PLUS | CP_BOARD_GRAPHICS));
961 continue;
964 if ((row % rowr)) {
965 if ((col % colr)) {
966 if (BIG_BOARD)
967 attrwhich = (cb[brow][bcol]) ? WHITE : BLACK;
968 else {
969 if (ncols++ == 8) {
970 offset++;
971 ncols = 1;
974 if (((ncols % 2) && !(offset % 2))
975 || (!(ncols % 2) && (offset % 2)))
976 attrwhich = BLACK;
977 else
978 attrwhich = WHITE;
981 if (BIG_BOARD && rotate) {
982 brow = inv_int(brow + 1) - 1;
983 bcol = inv_int(bcol + 1) - 1;
986 if (BIG_BOARD)
987 p = d->b[brow][bcol].icon;
988 else
989 p = d->b[RANKTOBOARD (brow)][FILETOBOARD (bcol)].icon;
991 int pi = pgn_piece_to_int(p);
993 if (config.details &&
994 ((!BIG_BOARD && d->b[RANKTOBOARD (brow)][FILETOBOARD (bcol)].enpassant)
995 || (BIG_BOARD && d->b[brow][bcol].enpassant))) {
996 p = pi = 'x';
997 attrs = mix_cp(CP_BOARD_ENPASSANT,
998 (attrwhich == WHITE) ? CP_BOARD_WHITE : CP_BOARD_BLACK,
999 ATTRS(CP_BOARD_ENPASSANT), A_FG_B_BG);
1002 // FIXME: showattacks - rotated board.
1003 if (config.showattacks && config.details
1004 && piece_can_attack (g,
1005 BIG_BOARD ? inv_int (brow+1) : brow,
1006 BIG_BOARD ? bcol+1 : bcol)) {
1007 attrs = CP_BOARD_ATTACK;
1008 old_attrs = attrs;
1009 can_attack = 1;
1012 if (config.validmoves &&
1013 ((!BIG_BOARD && d->b[RANKTOBOARD (brow)][FILETOBOARD (bcol)].valid)
1014 || (BIG_BOARD && d->b[brow][bcol].valid))) {
1015 old_attrs = -1;
1016 valid = 1;
1018 if (attrwhich == WHITE)
1019 attrs = mix_cp(CP_BOARD_MOVES_WHITE,
1020 IS_ENPASSANT(p),
1021 ATTRS(CP_BOARD_MOVES_WHITE),
1022 B_FG_A_BG);
1023 else
1024 attrs = mix_cp(CP_BOARD_MOVES_BLACK,
1025 IS_ENPASSANT(p),
1026 ATTRS(CP_BOARD_MOVES_BLACK),
1027 B_FG_A_BG);
1029 else if (p != 'x' && !can_attack)
1030 attrs = (attrwhich == WHITE) ? CP_BOARD_WHITE : CP_BOARD_BLACK;
1032 if (BIG_BOARD && rotate) {
1033 brow = inv_int(brow + 1) - 1;
1034 bcol = inv_int(bcol + 1) - 1;
1037 if ((!BIG_BOARD && row == ROWTOMATRIX(d->c_row)
1038 && col == COLTOMATRIX(d->c_col))
1039 || (BIG_BOARD && brow + 1 == inv_int(d->c_row)
1040 && bcol + 1 == d->c_col)) {
1041 attrs = mix_cp(CP_BOARD_CURSOR, IS_ENPASSANT(p),
1042 ATTRS(CP_BOARD_CURSOR), B_FG_A_BG);
1043 old_attrs = -1;
1045 else if ((!BIG_BOARD && row == ROWTOMATRIX(d->sp.srow) &&
1046 col == COLTOMATRIX(d->sp.scol)) ||
1047 (BIG_BOARD && brow + 1 == inv_int(d->sp.srow) &&
1048 bcol + 1 == d->sp.scol)) {
1049 attrs = mix_cp(CP_BOARD_SELECTED, IS_ENPASSANT(p),
1050 ATTRS(CP_BOARD_SELECTED), B_FG_A_BG);
1051 old_attrs = -1;
1054 if (row == maxy - 1)
1055 attrs = 0;
1057 if (can_attack) {
1058 attrs = mix_cp(CP_BOARD_ATTACK,
1059 valid ?
1060 (attrwhich == WHITE) ? CP_BOARD_MOVES_WHITE : CP_BOARD_MOVES_BLACK :
1061 (attrwhich == WHITE) ? CP_BOARD_WHITE : CP_BOARD_BLACK,
1062 ATTRS (CP_BOARD_ATTACK), A_FG_B_BG);
1065 if (BIG_BOARD)
1066 wmove(boardw, row, col + ((MEGA_BOARD) ? 5 : 3) + l);
1067 else
1068 mvwaddch(boardw, row, col + l, ' ' | attrs);
1070 if (row == maxy - 1 && cxgc < 8) {
1071 waddch(boardw, "abcdefgh"[(BIG_BOARD) ? bcol : bcol - 1] | CP_BOARD_COORDS);
1072 cxgc++;
1074 else {
1075 if (old_attrs == -1) {
1076 old_attrs = attrs;
1077 goto printc;
1080 old_attrs = attrs;
1082 if (pi != OPEN_SQUARE && p != 'x' && !can_attack) {
1083 if (attrwhich == WHITE) {
1084 if (isupper(p))
1085 attrs = CP_BOARD_W_W;
1086 else
1087 attrs = CP_BOARD_W_B;
1089 else {
1090 if (isupper(p))
1091 attrs = CP_BOARD_B_W;
1092 else
1093 attrs = CP_BOARD_B_B;
1097 printc:
1098 if (BIG_BOARD) {
1099 if (config.details && !can_attack
1100 && castling_state(g, d->b,
1101 (rotate) ? inv_int(brow + 1) - 1: brow,
1102 (rotate) ? inv_int(bcol + 1) - 1: bcol, p, 0))
1103 attrs = mix_cp(CP_BOARD_CASTLING, attrs,
1104 ATTRS(CP_BOARD_CASTLING),
1105 A_FG_B_BG);
1107 else {
1108 if (config.details && !can_attack
1109 && castling_state(g, d->b, RANKTOBOARD (brow),
1110 FILETOBOARD (bcol), p, 0)) {
1111 attrs = mix_cp(CP_BOARD_CASTLING, attrs,
1112 ATTRS(CP_BOARD_CASTLING),
1113 A_FG_B_BG);
1117 if (BIG_BOARD) {
1118 // FIXME: Reimpresión de piezas(+3).
1119 if (cpd < 67) {
1120 wattron (boardw, attrs);
1121 if (MEGA_BOARD){
1122 for (i = 0; i < 5; i++)
1123 mvwprintw(boardw, i + brow * 6 + 1,
1124 bcol * 12 + 1 + l,
1125 " ");
1126 if (pi != OPEN_SQUARE)
1127 print_piece(boardw, brow * 6 + 2,
1128 bcol * 12 + 3 + l, p);
1130 else {
1131 print_piece(boardw, brow * 4 + 1,
1132 bcol * 8 + 1 + l,
1133 (pi != OPEN_SQUARE) ? p : 0);
1136 wattroff (boardw, attrs);
1137 cpd++;
1140 else {
1141 wattron (boardw, attrs);
1142 waddwstr (boardw, piece_to_wchar (pi != OPEN_SQUARE ? p : 0));
1143 wattroff (boardw, attrs);
1146 attrs = old_attrs;
1149 if (BIG_BOARD)
1150 col += (MEGA_BOARD) ? 10 : 6;
1151 else {
1152 waddch(boardw, ' ' | attrs);
1153 col += 2;
1156 if (rotate)
1157 bcol--;
1158 else
1159 bcol++;
1161 if (BIG_BOARD) {
1162 if (bcol > 7)
1163 bcol = 0;
1164 if (bcol < 0)
1165 bcol = 7;
1169 else {
1170 if (col != maxx - 1)
1171 mvwaddch(boardw, row, col + l,
1172 LINE_GRAPHIC(ACS_HLINE | CP_BOARD_GRAPHICS));
1176 if (row % rowr) {
1177 if (rotate)
1178 brow++;
1179 else
1180 brow--;
1183 if (BIG_BOARD) {
1184 if (brow > 7)
1185 brow = 0;
1186 if (brow < 0)
1187 brow = 7;
1192 void invalid_move(int n, int e, const char *m)
1194 if (curses_initialized)
1195 cmessage(ERROR_STR, ANY_KEY_STR, "%s \"%s\" (round #%i)", (e == E_PGN_AMBIGUOUS)
1196 ? _("Ambiguous move") : _("Invalid move"), m, n);
1197 else
1198 warnx("%s: %s \"%s\" (round #%i)", loadfile, (e == E_PGN_AMBIGUOUS)
1199 ? _("Ambiguous move") : _("Invalid move"), m, n);
1202 void gameover(GAME g)
1204 struct userdata_s *d = g->data;
1206 SET_FLAG(g->flags, GF_GAMEOVER);
1207 d->mode = MODE_HISTORY;
1208 stop_engine(g);
1211 static void update_clock(GAME g, struct itimerval it)
1213 struct userdata_s *d = g->data;
1215 if (TEST_FLAG(d->flags, CF_CLOCK) && g->turn == WHITE) {
1216 d->wclock.elapsed.tv_sec += it.it_value.tv_sec;
1217 d->wclock.elapsed.tv_usec += it.it_value.tv_usec;
1219 if (d->wclock.elapsed.tv_usec > 1000000 - 1) {
1220 d->wclock.elapsed.tv_sec += d->wclock.elapsed.tv_usec / 1000000;
1221 d->wclock.elapsed.tv_usec = d->wclock.elapsed.tv_usec % 1000000;
1224 if (d->wclock.tc[d->wclock.tcn][1] &&
1225 d->wclock.elapsed.tv_sec >= d->wclock.tc[d->wclock.tcn][1]) {
1226 pgn_tag_add(&g->tag, "Result", "0-1");
1227 gameover(g);
1230 else if (TEST_FLAG(d->flags, CF_CLOCK) && g->turn == BLACK) {
1231 d->bclock.elapsed.tv_sec += it.it_value.tv_sec;
1232 d->bclock.elapsed.tv_usec += it.it_value.tv_usec;
1234 if (d->bclock.elapsed.tv_usec > 1000000 - 1) {
1235 d->bclock.elapsed.tv_sec += d->bclock.elapsed.tv_usec / 1000000;
1236 d->bclock.elapsed.tv_usec = d->bclock.elapsed.tv_usec % 1000000;
1239 if (d->bclock.tc[d->bclock.tcn][1] &&
1240 d->bclock.elapsed.tv_sec >= d->bclock.tc[d->bclock.tcn][1]) {
1241 pgn_tag_add(&g->tag, "Result", "1-0");
1242 gameover(g);
1246 d->elapsed.tv_sec += it.it_value.tv_sec;
1247 d->elapsed.tv_usec += it.it_value.tv_usec;
1249 if (d->elapsed.tv_usec > 1000000 - 1) {
1250 d->elapsed.tv_sec += d->elapsed.tv_usec / 1000000;
1251 d->elapsed.tv_usec = d->elapsed.tv_usec % 1000000;
1255 static void update_time_control(GAME g)
1257 struct userdata_s *d = g->data;
1258 struct clock_s *clk = (g->turn == WHITE) ? &d->wclock : &d->bclock;
1260 if (clk->incr)
1261 clk->tc[clk->tcn][1] += clk->incr;
1263 if (!clk->tc[clk->tcn][1])
1264 return;
1266 clk->move++;
1268 if (!clk->tc[clk->tcn][0] || clk->move >= clk->tc[clk->tcn][0]) {
1269 clk->move = 0;
1270 clk->tc[clk->tcn + 1][1] += abs(clk->elapsed.tv_sec - clk->tc[clk->tcn][1]);
1271 memset(&clk->elapsed, 0, sizeof(clk->elapsed));
1272 clk->tcn++;
1276 void update_history_window(GAME g)
1278 char buf[HISTORY_WIDTH - 1];
1279 HISTORY *h = NULL;
1280 int n, total;
1281 int t = pgn_history_total(g->hp);
1283 n = (g->hindex + 1) / 2;
1285 if (t % 2)
1286 total = (t + 1) / 2;
1287 else
1288 total = t / 2;
1290 if (t)
1291 snprintf(buf, sizeof(buf), "%u %s %u%s", n, _("of"), total,
1292 (movestep == 1) ? _(" (ply)") : "");
1293 else
1294 strncpy(buf, _("not available"), sizeof(buf)-1);
1296 buf[sizeof(buf)-1] = 0;
1297 mvwprintw(historyw, 2, 1, "%*s %-*s", 10, _("Move:"),
1298 HISTORY_WIDTH - 14, buf);
1300 h = pgn_history_by_n(g->hp, g->hindex);
1301 snprintf(buf, sizeof(buf), "%s",
1302 (h && h->move) ? h->move
1303 : (LINES < 24) ? _("empty") : _("not available"));
1304 n = 0;
1306 if (h && ((h->comment) || h->nag[0])) {
1307 strncat(buf, _(" (Annotated"), sizeof(buf)-1);
1308 n++;
1311 if (h && h->rav) {
1312 strncat(buf, (n) ? ",+" : " (+", sizeof(buf)-1);
1313 n++;
1316 if (g->ravlevel) {
1317 strncat(buf, (n) ? ",-" : " (-", sizeof(buf)-1);
1318 n++;
1321 if (n)
1322 strncat(buf, ")", sizeof(buf)-1);
1324 mvwprintw(historyw, 3, ((LINES < 24) ? 17 : 1), "%s %-*s",
1325 (LINES < 24) ? _("Next:") :_("Next move:"),
1326 HISTORY_WIDTH - ((LINES < 24) ? 26 : 14), buf);
1328 h = pgn_history_by_n(g->hp, g->hindex - 1);
1329 snprintf(buf, sizeof(buf), "%s",
1330 (h && h->move) ? h->move
1331 : (LINES < 24) ? _("empty") : _("not available"));
1332 n = 0;
1334 if (h && ((h->comment) || h->nag[0])) {
1335 strncat(buf, _(" (Annotated"), sizeof(buf)-1);
1336 n++;
1339 if (h && h->rav) {
1340 strncat(buf, (n) ? ",+" : " (+", sizeof(buf)-1);
1341 n++;
1344 if (g->ravlevel) {
1345 strncat(buf, (n) ? ",-" : " (-", sizeof(buf)-1);
1346 n++;
1349 if (n)
1350 strncat(buf, ")", sizeof(buf)-1);
1352 mvwprintw(historyw, ((LINES < 24) ? 3 : 4), 1, "%s %-*s",
1353 (LINES < 24) ? _("Prev.:") : _("Prev move:"),
1354 HISTORY_WIDTH - ((LINES < 24) ? 26 : 14), buf);
1357 void do_validate_move(char *move)
1359 struct userdata_s *d = gp->data;
1360 int n;
1361 char *frfr = NULL;
1363 if (TEST_FLAG(d->flags, CF_HUMAN)) {
1364 if ((n = pgn_parse_move(gp, d->b, &move, &frfr)) != E_PGN_OK) {
1365 invalid_move(d->n + 1, n, move);
1366 return;
1369 update_time_control(gp);
1370 pgn_history_add(gp, d->b, move);
1371 pgn_switch_turn(gp);
1373 else {
1374 if ((n = pgn_validate_move(gp, d->b, &move, &frfr)) != E_PGN_OK) {
1375 invalid_move(d->n + 1, n, move);
1376 return;
1379 add_engine_command(gp, ENGINE_THINKING, "%s\n",
1380 (config.engine_protocol == 1) ? frfr : move);
1383 d->sp.srow = d->sp.scol = d->sp.icon = 0;
1385 if (config.validmoves)
1386 pgn_reset_valid_moves(d->b);
1388 if (TEST_FLAG(gp->flags, GF_GAMEOVER))
1389 d->mode = MODE_HISTORY;
1390 else
1391 SET_FLAG(d->flags, CF_MODIFIED);
1393 free (frfr);
1394 d->paused = 0;
1395 update_history_window(gp);
1396 update_board_window(gp);
1397 return;
1400 void do_promotion_piece_finalize(WIN *win)
1402 char *p, *str = win->data;
1404 if (pgn_piece_to_int(win->c) == -1)
1405 return;
1407 p = str + strlen(str);
1408 *p++ = toupper(win->c);
1409 *p = '\0';
1410 do_validate_move(str);
1411 free (win->data);
1412 win->data = NULL;
1415 static void move_to_engine(GAME g)
1417 struct userdata_s *d = g->data;
1418 char *str;
1419 int piece;
1421 if (config.validmoves &&
1422 !d->b[RANKTOBOARD(d->sp.row)][FILETOBOARD(d->sp.col)].valid)
1423 return;
1425 str = Malloc(MAX_SAN_MOVE_LEN + 1);
1426 snprintf(str, MAX_SAN_MOVE_LEN + 1, "%c%i%c%i",
1427 _("abcdefgh")[d->sp.scol - 1],
1428 d->sp.srow, _("abcdefgh")[d->sp.col - 1], d->sp.row);
1430 piece = pgn_piece_to_int(d->b[RANKTOBOARD(d->sp.srow)][FILETOBOARD(d->sp.scol)].icon);
1432 if (piece == PAWN && (d->sp.row == 8 || d->sp.row == 1)) {
1433 construct_message(_("Select Pawn Promotion Piece"), _ ("R/N/B/Q"), 1, 1, NULL, NULL,
1434 str, do_promotion_piece_finalize, 0, 0, "%s", _("R = Rook, N = Knight, B = Bishop, Q = Queen"));
1435 return;
1438 do_validate_move(str);
1439 free (str);
1442 static char *clock_to_char(long n)
1444 static char buf[16];
1445 int h = 0, m = 0, s = 0;
1447 h = n / 3600;
1448 m = (n % 3600) / 60;
1449 s = (n % 3600) % 60;
1450 snprintf(buf, sizeof(buf), "%.2i:%.2i:%.2i", h, m, s);
1451 return buf;
1454 static char *timeval_to_char(struct timeval t, long limit)
1456 static char buf[9];
1457 int h = 0, m = 0, s = 0;
1458 int n = limit ? abs(limit - t.tv_sec) : 0;
1460 h = n / 3600;
1461 m = (n % 3600) / 60;
1462 s = (n % 3600) % 60;
1463 snprintf(buf, sizeof(buf), "%.2i:%.2i:%.2i", h, m, s);
1464 return buf;
1467 static char *time_control_status(struct clock_s *clk)
1469 static char buf[80] = {0};
1471 buf[0] = 0;
1473 if (clk->tc[clk->tcn][0] && clk->tc[clk->tcn + 1][1])
1474 snprintf(buf, sizeof(buf), " M%.2i/%s", abs(clk->tc[clk->tcn][0] - clk->move),
1475 clock_to_char(clk->tc[clk->tcn + 1][1]));
1476 else if (!clk->incr)
1477 return "";
1479 if (clk->incr) {
1480 char buf[16];
1481 strncat(buf, " I", sizeof(buf)-1);
1482 strncat(buf, itoa(clk->incr, buf), sizeof(buf)-1);
1485 return buf;
1488 void update_status_window(GAME g)
1490 int i = 0;
1491 char *buf;
1492 char tmp[15] = {0}, *engine, *mode;
1493 char t[COLS];
1494 int w;
1495 char *p;
1496 int maxy, maxx;
1497 int len;
1498 struct userdata_s *d = g->data;
1499 int y;
1500 int n;
1502 if (!curses_initialized)
1503 return;
1505 getmaxyx(statusw, maxy, maxx);
1506 (void)maxy;
1507 w = maxx - 2 - 8;
1508 len = maxx - 2;
1509 buf = Malloc(len);
1510 y = 2;
1512 wchar_t *loadfilew = loadfile[0] ? str_etc (loadfile, w, 1) : str_to_wchar (_ ("not available"));
1513 mvwprintw(statusw, y++, 1, "%*s %-*ls", 7, _("File:"), w, loadfilew);
1514 free (loadfilew);
1515 snprintf(buf, len, "%i %s %i", gindex + 1, _("of"), gtotal);
1516 mvwprintw(statusw, y++, 1, "%*s %-*s", 7, _("Game:"), w, buf);
1518 *tmp = '\0';
1519 p = tmp;
1521 if (config.details) {
1522 *p++ = 'D';
1523 i++;
1526 if (TEST_FLAG(d->flags, CF_DELETE)) {
1527 if (i)
1528 *p++ = '/';
1530 *p++ = 'X';
1531 i++;
1534 if (TEST_FLAG(g->flags, GF_PERROR)) {
1535 if (i)
1536 *p++ = '/';
1538 *p++ = '!';
1539 i++;
1542 if (TEST_FLAG(d->flags, CF_MODIFIED)) {
1543 if (i)
1544 *p++ = '/';
1546 *p++ = '*';
1547 i++;
1550 pgn_config_get(PGN_STRICT_CASTLING, &n);
1552 if (n == 1) {
1553 if (i)
1554 *p++ = '/';
1556 *p++ = 'C';
1557 i++;
1559 #ifdef WITH_LIBPERL
1560 if (TEST_FLAG(d->flags, CF_PERL)) {
1561 if (i)
1562 *p++ = '/';
1564 *p++ = 'P';
1565 i++;
1567 #endif
1569 *p = '\0';
1570 mvwprintw(statusw, y++, 1, "%*s %-*s", 7, _("Flags:"), w, (tmp[0]) ? tmp : "-");
1572 switch (d->mode) {
1573 case MODE_HISTORY:
1574 mode = _("move history");
1575 break;
1576 case MODE_EDIT:
1577 mode = _("edit");
1578 break;
1579 case MODE_PLAY:
1580 mode = _("play");
1581 break;
1582 default:
1583 mode = _("(empty value)");
1584 break;
1587 snprintf(buf, len - 1, "%*s %s", 7, _("Mode:"), mode);
1589 if (d->mode == MODE_PLAY) {
1590 if (TEST_FLAG(d->flags, CF_HUMAN))
1591 strncat(buf, _(" (human/human)"), len - 1);
1592 else if (TEST_FLAG(d->flags, CF_ENGINE_LOOP))
1593 strncat(buf, _(" (engine/engine)"), len - 1);
1594 else
1595 strncat(buf, (d->play_mode == PLAY_EH) ?
1596 _(" (engine/human)") : _(" (human/engine)"), len - 1);
1599 buf[len-1] = 0;
1600 mvwprintw(statusw, y++, 1, "%-*s", len, buf);
1601 free(buf);
1603 if (d->engine) {
1604 switch (d->engine->status) {
1605 case ENGINE_THINKING:
1606 engine = _("pondering...");
1607 break;
1608 case ENGINE_READY:
1609 engine = _("ready");
1610 break;
1611 case ENGINE_INITIALIZING:
1612 engine = _("initializing...");
1613 break;
1614 case ENGINE_OFFLINE:
1615 engine = _("offline");
1616 break;
1617 default:
1618 engine = _("(empty value)");
1619 break;
1622 else
1623 engine = _("offline");
1625 mvwprintw(statusw, y, 1, "%*s %-*s", 7, _("Engine:"), w, " ");
1626 wattron(statusw, CP_STATUS_ENGINE);
1627 mvwaddstr(statusw, y++, 9, engine);
1628 wattroff(statusw, CP_STATUS_ENGINE);
1630 mvwprintw(statusw, y++, 1, "%*s %-*s", 7, _("Turn:"), w,
1631 (g->turn == WHITE) ? _("white") : _("black"));
1633 strncpy(tmp, _("white"), sizeof(tmp)-1);
1634 tmp[0] = toupper(tmp[0]);
1635 snprintf(t, sizeof(t), "%s%s",
1636 timeval_to_char(d->wclock.elapsed, d->wclock.tc[d->wclock.tcn][1]),
1637 time_control_status(&d->wclock));
1638 mvwprintw(statusw, y++, 1, "%*s: %-*s", 6, tmp, w, t);
1640 strncpy(tmp, _("black"), sizeof(tmp)-1);
1641 tmp[0] = toupper(tmp[0]);
1642 snprintf(t, sizeof(t), "%s%s",
1643 timeval_to_char(d->bclock.elapsed, d->bclock.tc[d->bclock.tcn][1]),
1644 time_control_status(&d->bclock));
1645 mvwprintw(statusw, y++, 1, "%*s: %-*s", 6, tmp, w, t);
1647 mvwprintw(statusw, y++, 1, "%*s %-*s", 7, _("Total:"), w,
1648 clock_to_char(d->elapsed.tv_sec));
1650 // for (i = 0; i < STATUS_WIDTH; i++)
1651 // mvwprintw(stdscr, STATUS_HEIGHT, i, " ");
1653 if (!status.notify)
1654 status.notify = str_to_wchar(_("Type F1 for help"));
1656 wattron(stdscr, CP_STATUS_NOTIFY);
1657 for (i = (config.boardleft) ? BOARD_WIDTH : 0;
1658 i < ((config.boardleft) ? COLS : STATUS_WIDTH); i++)
1659 mvwprintw(stdscr, STATUS_HEIGHT, i, " ");
1660 mvwprintw(stdscr, STATUS_HEIGHT, CENTERX(STATUS_WIDTH, status.notify)
1661 + ((config.boardleft) ? BOARD_WIDTH : 0),
1662 "%ls", status.notify);
1663 wattroff(stdscr, CP_STATUS_NOTIFY);
1666 wchar_t *translate_tag_name(const char *tag)
1668 if (!strcmp (tag, "Event"))
1669 return str_to_wchar (translatable_tag_names[0]);
1670 else if (!strcmp (tag, "Site"))
1671 return str_to_wchar (translatable_tag_names[1]);
1672 else if (!strcmp (tag, "Date"))
1673 return str_to_wchar (translatable_tag_names[2]);
1674 else if (!strcmp (tag, "Round"))
1675 return str_to_wchar (translatable_tag_names[3]);
1676 else if (!strcmp (tag, "White"))
1677 return str_to_wchar (translatable_tag_names[4]);
1678 else if (!strcmp (tag, "Black"))
1679 return str_to_wchar (translatable_tag_names[5]);
1680 else if (!strcmp (tag, "Result"))
1681 return str_to_wchar (translatable_tag_names[6]);
1683 return str_to_wchar (tag);
1686 void update_tag_window(TAG **t)
1688 int i, l, w;
1689 int namel = 0;
1691 for (i = 0; t[i]; i++) {
1692 wchar_t *namewc = translate_tag_name(t[i]->name);
1694 l = wcslen(namewc);
1695 free (namewc);
1696 if (l > namel)
1697 namel = l;
1700 w = TAG_WIDTH - namel - 4;
1702 for (i = 0; t[i] && i < TAG_HEIGHT - 3; i++) {
1703 wchar_t *namewc = translate_tag_name(t[i]->name);
1704 wchar_t *valuewc = str_etc(t[i]->value, w, 0);
1706 mvwprintw(tagw, (i + 2), 1, "%*ls: %-*ls", namel, namewc, w, valuewc);
1707 free (namewc);
1708 free (valuewc);
1711 for (; i < TAG_HEIGHT - 3; i++)
1712 mvwprintw(tagw, (i + 2), 1, "%*s", namel + w + 2, " ");
1715 void append_enginebuf(GAME g, char *line)
1717 int i = 0;
1718 struct userdata_s *d = g->data;
1720 if (d->engine->enginebuf)
1721 for (i = 0; d->engine->enginebuf[i]; i++);
1723 if (i >= LINES - 3) {
1724 free(d->engine->enginebuf[0]);
1726 for (i = 0; d->engine->enginebuf[i+1]; i++)
1727 d->engine->enginebuf[i] = d->engine->enginebuf[i+1];
1729 d->engine->enginebuf[i] = strdup(line);
1731 else {
1732 d->engine->enginebuf = Realloc(d->engine->enginebuf, (i + 2) * sizeof(char *));
1733 d->engine->enginebuf[i++] = strdup(line);
1734 d->engine->enginebuf[i] = NULL;
1738 void update_engine_window(GAME g)
1740 int i;
1741 struct userdata_s *d = g->data;
1743 if (!d->engine || !d->engine->enginebuf)
1744 return;
1746 wmove(enginew, 0, 0);
1747 wclrtobot(enginew);
1749 if (d->engine->enginebuf) {
1750 for (i = 0; d->engine->enginebuf[i]; i++)
1751 mvwprintw(enginew, i + 2, 1, "%s", d->engine->enginebuf[i]);
1754 window_draw_title(enginew, _("Engine IO Window"), COLS, CP_MESSAGE_TITLE,
1755 CP_MESSAGE_BORDER);
1758 void update_all(GAME g)
1760 struct userdata_s *d = g->data;
1763 * In the middle of a macro. Don't update the screen.
1765 if (macro_match != -1)
1766 return;
1769 * No need to update when the engine window is being shown.
1771 if (enginep && panel_hidden(enginep) == ERR) {
1772 update_panels();
1773 doupdate();
1774 return;
1777 wmove(boardw, ROWTOMATRIX(d->c_row), COLTOMATRIX(d->c_col));
1778 update_board_window(g);
1779 update_status_window(g);
1780 update_history_window(g);
1781 update_tag_window(g->tag);
1782 update_engine_window(g);
1783 update_panels();
1784 doupdate();
1787 static void game_next_prev(GAME g, int n, int count)
1789 if (gtotal < 2)
1790 return;
1792 if (n == 1) {
1793 if (gindex + count > gtotal - 1) {
1794 if (count != 1)
1795 gindex = gtotal - 1;
1796 else
1797 gindex = 0;
1799 else
1800 gindex += count;
1802 else {
1803 if (gindex - count < 0) {
1804 if (count != 1)
1805 gindex = 0;
1806 else
1807 gindex = gtotal - 1;
1809 else
1810 gindex -= count;
1813 gp = game[gindex];
1816 static void delete_game(int which)
1818 GAME *g = NULL;
1819 int gi = 0;
1820 int i;
1821 struct userdata_s *d;
1823 for (i = 0; i < gtotal; i++) {
1824 d = game[i]->data;
1826 if (i == which || TEST_FLAG(d->flags, CF_DELETE)) {
1827 free_userdata_once(game[i]);
1828 pgn_free(game[i]);
1829 continue;
1832 g = Realloc(g, (gi + 1) * sizeof(GAME *));
1833 g[gi] = Calloc(1, sizeof(struct game_s));
1834 memcpy(g[gi], game[i], sizeof(struct game_s));
1835 g[gi]->tag = game[i]->tag;
1836 g[gi]->history = game[i]->history;
1837 g[gi]->hp = game[i]->hp;
1838 gi++;
1841 game = g;
1842 gtotal = gi;
1844 if (which != -1) {
1845 if (which + 1 >= gtotal)
1846 gindex = gtotal - 1;
1847 else
1848 gindex = which;
1850 else
1851 gindex = gtotal - 1;
1853 gp = game[gindex];
1854 gp->hp = gp->history;
1858 * FIXME find across multiple games.
1860 static int find_move_exp(GAME g, regex_t r, int which, int count)
1862 int i;
1863 int ret;
1864 char errbuf[255];
1865 int incr;
1866 int found;
1868 incr = (which == 0) ? -1 : 1;
1870 for (i = g->hindex + incr - 1, found = 0; ; i += incr) {
1871 if (i == g->hindex - 1)
1872 break;
1874 if (i >= pgn_history_total(g->hp))
1875 i = 0;
1876 else if (i < 0)
1877 i = pgn_history_total(g->hp) - 1;
1879 // FIXME RAV
1880 ret = regexec(&r, g->hp[i]->move, 0, 0, 0);
1882 if (ret == 0) {
1883 if (count == ++found) {
1884 return i + 1;
1887 else {
1888 if (ret != REG_NOMATCH) {
1889 regerror(ret, &r, errbuf, sizeof(errbuf));
1890 cmessage(_("Error Matching Regular Expression"), ANY_KEY_STR, "%s", errbuf);
1891 return -1;
1896 return -1;
1899 static int toggle_delete_flag(int n)
1901 int i, x;
1902 struct userdata_s *d = game[n]->data;
1904 TOGGLE_FLAG(d->flags, CF_DELETE);
1905 gindex = n;
1907 for (i = x = 0; i < gtotal; i++) {
1908 d = game[i]->data;
1910 if (TEST_FLAG(d->flags, CF_DELETE))
1911 x++;
1914 if (x == gtotal) {
1915 cmessage(NULL, ANY_KEY_STR, "%s", _("Cannot delete last game."));
1916 d = game[n]->data;
1917 CLEAR_FLAG(d->flags, CF_DELETE);
1918 return 1;
1921 return 0;
1924 static int find_game_exp(char *str, int which, int count)
1926 char *nstr = NULL, *exp = NULL;
1927 regex_t nexp, vexp;
1928 int ret = -1;
1929 int g = 0;
1930 char buf[255] = {0}, *tmp;
1931 char errbuf[255];
1932 int found = 0;
1933 int incr = (which == 0) ? -(1) : 1;
1935 strncpy(buf, str, sizeof(buf)-1);
1936 tmp = buf;
1938 if (strstr(tmp, ":") != NULL) {
1939 nstr = strsep(&tmp, ":");
1941 if ((ret = regcomp(&nexp, nstr,
1942 REG_ICASE|REG_EXTENDED|REG_NOSUB)) != 0) {
1943 regerror(ret, &nexp, errbuf, sizeof(errbuf));
1944 cmessage(_("Error Compiling Regular Expression"), ANY_KEY_STR, "%s", errbuf);
1945 ret = g = -1;
1946 goto cleanup;
1950 exp = tmp;
1952 while (*exp && isspace(*exp))
1953 exp++;
1955 if (exp == NULL)
1956 goto cleanup;
1958 if ((ret = regcomp(&vexp, exp, REG_EXTENDED|REG_NOSUB)) != 0) {
1959 regerror(ret, &vexp, errbuf, sizeof(errbuf));
1960 cmessage(_("Error Compiling Regular Expression"), ANY_KEY_STR, "%s", errbuf);
1961 ret = -1;
1962 goto cleanup;
1965 ret = -1;
1967 for (g = gindex + incr, found = 0; ; g += incr) {
1968 int t;
1970 if (g == gtotal)
1971 g = 0;
1972 else if (g < 0)
1973 g = gtotal - 1;
1975 if (g == gindex)
1976 break;
1978 for (t = 0; game[g]->tag[t]; t++) {
1979 if (nstr) {
1980 if (regexec(&nexp, game[g]->tag[t]->name, 0, 0, 0) == 0) {
1981 if (regexec(&vexp, game[g]->tag[t]->value, 0, 0, 0) == 0) {
1982 if (count == ++found) {
1983 ret = g;
1984 goto cleanup;
1989 else {
1990 if (regexec(&vexp, game[g]->tag[t]->value, 0, 0, 0) == 0) {
1991 if (count == ++found) {
1992 ret = g;
1993 goto cleanup;
1999 ret = -1;
2002 cleanup:
2003 if (nstr)
2004 regfree(&nexp);
2006 if (g != -1)
2007 regfree(&vexp);
2009 return ret;
2013 * Updates the notification line in the status window then refreshes the
2014 * status window.
2016 void update_status_notify(GAME g, char *fmt, ...)
2018 va_list ap;
2019 #ifdef HAVE_VASPRINTF
2020 char *line;
2021 #else
2022 char line[COLS];
2023 #endif
2025 if (!fmt) {
2026 if (status.notify) {
2027 free(status.notify);
2028 status.notify = NULL;
2031 return;
2034 va_start(ap, fmt);
2035 #ifdef HAVE_VASPRINTF
2036 vasprintf(&line, fmt, ap);
2037 #else
2038 vsnprintf(line, sizeof(line), fmt, ap);
2039 #endif
2040 va_end(ap);
2042 if (status.notify)
2043 free(status.notify);
2045 status.notify = str_to_wchar(line);
2047 #ifdef HAVE_VASPRINTF
2048 free(line);
2049 #endif
2052 int rav_next_prev(GAME g, BOARD b, int n)
2054 // Next RAV.
2055 if (n) {
2056 if ((!g->ravlevel && g->hindex && g->hp[g->hindex - 1]->rav == NULL) ||
2057 (!g->ravlevel && !g->hindex && g->hp[g->hindex]->rav == NULL) ||
2058 (g->ravlevel && g->hp[g->hindex]->rav == NULL))
2059 return 1;
2061 g->rav = Realloc(g->rav, (g->ravlevel + 1) * sizeof(RAV));
2062 g->rav[g->ravlevel].hp = g->hp;
2063 g->rav[g->ravlevel].flags = g->flags;
2064 g->rav[g->ravlevel].fen = pgn_game_to_fen(g, b);
2065 g->rav[g->ravlevel].hindex = g->hindex;
2066 g->hp = (!g->ravlevel) ? (g->hindex) ? g->hp[g->hindex - 1]->rav : g->hp[g->hindex]->rav : g->hp[g->hindex]->rav;
2067 g->hindex = 0;
2068 g->ravlevel++;
2069 pgn_board_update(g, b, g->hindex + 1);
2070 return 0;
2073 if (g->ravlevel - 1 < 0)
2074 return 1;
2076 // Previous RAV.
2077 g->ravlevel--;
2078 pgn_board_init_fen(g, b, g->rav[g->ravlevel].fen);
2079 free(g->rav[g->ravlevel].fen);
2080 g->hp = g->rav[g->ravlevel].hp;
2081 g->flags = g->rav[g->ravlevel].flags;
2082 g->hindex = g->rav[g->ravlevel].hindex;
2083 return 0;
2086 static void draw_window_decor()
2088 move_panel(boardp, 0,
2089 (config.boardleft) ? 0 : COLS - BOARD_WIDTH);
2090 move_panel(historyp, LINES - HISTORY_HEIGHT,
2091 (config.boardleft) ? (MEGA_BOARD) ? BOARD_WIDTH : 0 :
2092 (MEGA_BOARD) ? 0 : COLS - HISTORY_WIDTH);
2093 move_panel(statusp, 0,
2094 (config.boardleft) ? BOARD_WIDTH : 0);
2095 move_panel(tagp, STATUS_HEIGHT + 1,
2096 (config.boardleft) ? (MEGA_BOARD) ? BOARD_WIDTH :
2097 HISTORY_WIDTH : 0);
2099 wbkgd(boardw, CP_BOARD_WINDOW);
2100 wbkgd(statusw, CP_STATUS_WINDOW);
2101 window_draw_title(statusw, _("Game Status"), STATUS_WIDTH,
2102 CP_STATUS_TITLE, CP_STATUS_BORDER);
2103 wbkgd(tagw, CP_TAG_WINDOW);
2104 window_draw_title(tagw, _("Roster Tags"), TAG_WIDTH, CP_TAG_TITLE,
2105 CP_TAG_BORDER);
2106 wbkgd(historyw, CP_HISTORY_WINDOW);
2107 window_draw_title(historyw, _("Move History"), HISTORY_WIDTH,
2108 CP_HISTORY_TITLE, CP_HISTORY_BORDER);
2111 static void do_window_resize()
2113 if (LINES < 23 || COLS < 74)
2114 return;
2116 resizeterm(LINES, COLS);
2117 wresize(boardw, BOARD_HEIGHT, BOARD_WIDTH);
2118 wresize(historyw, HISTORY_HEIGHT, HISTORY_WIDTH);
2119 wresize(statusw, STATUS_HEIGHT, STATUS_WIDTH);
2120 wresize(tagw, TAG_HEIGHT, TAG_WIDTH);
2121 wmove(boardw, 0, 0);
2122 wclrtobot(boardw);
2123 wmove(historyw, 0, 0);
2124 wclrtobot(historyw);
2125 wmove(tagw, 0, 0);
2126 wclrtobot(tagw);
2127 wmove(statusw, 0, 0);
2128 wclrtobot(statusw);
2129 draw_window_decor();
2130 update_all(gp);
2133 void stop_clock()
2135 memset(&clock_timer, 0, sizeof(struct itimerval));
2136 setitimer(ITIMER_REAL, &clock_timer, NULL);
2139 void start_clock(GAME g)
2141 struct userdata_s *d = g->data;
2143 if (clock_timer.it_interval.tv_usec)
2144 return;
2146 memset(&d->elapsed, 0, sizeof(struct timeval));
2147 clock_timer.it_value.tv_sec = 0;
2148 clock_timer.it_value.tv_usec = 100000;
2149 clock_timer.it_interval.tv_sec = 0;
2150 clock_timer.it_interval.tv_usec = 100000;
2151 setitimer(ITIMER_REAL, &clock_timer, NULL);
2154 static void update_clocks()
2156 int i;
2157 struct userdata_s *d;
2158 struct itimerval it;
2159 int update = 0;
2161 getitimer(ITIMER_REAL, &it);
2163 for (i = 0; i < gtotal; i++) {
2164 d = game[i]->data;
2166 if (d && d->mode == MODE_PLAY) {
2167 if (d->paused == 1 || TEST_FLAG(d->flags, CF_NEW))
2168 continue;
2169 else if (d->paused == -1) {
2170 if (game[i]->side == game[i]->turn) {
2171 d->paused = 1;
2172 continue;
2176 update_clock(game[i], it);
2178 if (game[i] == gp)
2179 update = 1;
2183 if (update) {
2184 update_status_window(gp);
2185 update_panels();
2186 doupdate();
2190 #define SKIP_SPACE(str) { while (isspace(*str)) str++; }
2192 static int parse_clock_time(char **str)
2194 char *p = *str;
2195 int n = 0, t = 0;
2197 SKIP_SPACE(p);
2199 if (!isdigit(*p))
2200 return -1;
2202 while (*p) {
2203 if (isdigit(*p)) {
2204 t = atoi(p);
2206 while (isdigit(*p))
2207 p++;
2209 continue;
2212 switch (*p) {
2213 case 'H':
2214 case 'h':
2215 n += t * (60 * 60);
2216 t = 0;
2217 break;
2218 case 'M':
2219 case 'm':
2220 n += t * 60;
2221 t = 0;
2222 break;
2223 case 'S':
2224 case 's':
2225 n += t;
2226 t = 0;
2227 break;
2228 case ' ':
2229 p++;
2230 case '/':
2231 case '+':
2232 goto done;
2233 default:
2234 *str = p;
2235 return -1;
2238 p++;
2241 done:
2242 n += t;
2243 *str = p;
2244 return n;
2247 static int parse_clock_input(struct clock_s *clk, char *str, int *incr)
2249 char *p = str;
2250 long n = 0;
2251 int plus = 0;
2252 int m = 0;
2253 int tc = 0;
2255 SKIP_SPACE(p);
2257 if (!*p)
2258 return 0;
2260 if (*p == '+') {
2261 plus = 1;
2262 p++;
2263 SKIP_SPACE(p);
2265 if (*p == '+')
2266 goto move_incr;
2268 else
2269 memset(clk, 0, sizeof(struct clock_s));
2271 again:
2272 /* Sudden death. */
2273 if (strncasecmp(p, "SD", 2) == 0) {
2274 n = 0;
2275 p += 2;
2276 goto tc;
2279 n = parse_clock_time(&p);
2281 if (n == -1)
2282 return 1;
2284 if (!n)
2285 goto done;
2287 /* Time control. */
2289 if (*p == '/') {
2290 if (plus)
2291 return 1;
2293 /* Sudden death without a previous time control. */
2294 if (!n && !tc)
2295 return 1;
2297 m = n;
2298 p++;
2299 n = parse_clock_time(&p);
2301 if (n == -1)
2302 return 1;
2304 if (tc >= MAX_TC) {
2305 message(ERROR_STR, ANY_KEY_STR, "%s (%i)", _("Maximum number of time controls reached"), MAX_TC);
2306 return 1;
2309 clk->tc[tc][0] = m;
2310 clk->tc[tc++][1] = n;
2311 SKIP_SPACE(p);
2313 if (*p == '+')
2314 goto move_incr;
2316 if (*p)
2317 goto again;
2319 goto done;
2322 if (plus)
2323 *incr = n;
2324 else
2325 clk->tc[clk->tcn][1] = (n <= clk->elapsed.tv_sec) ? clk->elapsed.tv_sec + n : n;
2327 move_incr:
2328 if (*p) {
2329 if (*p++ == '+') {
2330 if (!isdigit(*p))
2331 return 1;
2333 n = parse_clock_time(&p);
2335 if (n == -1 || *p)
2336 return 1;
2338 clk->incr = n;
2340 SKIP_SPACE(p);
2342 if (*p)
2343 return 1;
2345 else
2346 return 1;
2349 done:
2350 return 0;
2353 static int parse_which_clock(struct clock_s *clk, char *str)
2355 struct clock_s tmp;
2356 int incr = 0;
2358 memcpy(&tmp, clk, sizeof(struct clock_s));
2360 if (parse_clock_input(&tmp, str, &incr)) {
2361 cmessage(ERROR_STR, ANY_KEY_STR, _("Invalid clock specification"));
2362 return 1;
2365 memcpy(clk, &tmp, sizeof(struct clock_s));
2366 clk->tc[clk->tcn][1] += incr;
2367 return 0;
2370 void do_clock_input_finalize(WIN *win)
2372 struct userdata_s *d = gp->data;
2373 struct input_data_s *in = win->data;
2374 char *p = in->str;
2376 if (!in->str) {
2377 free(in);
2378 return;
2381 SKIP_SPACE(p);
2383 if (tolower(*p) == 'w') {
2384 p++;
2386 if (parse_which_clock(&d->wclock, p))
2387 goto done;
2389 else if (tolower(*p) == 'b') {
2390 p++;
2392 if (parse_which_clock(&d->bclock, p))
2393 goto done;
2395 else {
2396 if (parse_which_clock(&d->wclock, p))
2397 goto done;
2399 if (parse_which_clock(&d->bclock, p))
2400 goto done;
2403 if (!d->wclock.tc[0][1] && !d->bclock.tc[0][1])
2404 CLEAR_FLAG(d->flags, CF_CLOCK);
2405 else
2406 SET_FLAG(d->flags, CF_CLOCK);
2408 done:
2409 free(in->str);
2410 free(in);
2413 void do_engine_command_finalize(WIN *win)
2415 struct userdata_s *d = gp->data;
2416 struct input_data_s *in = win->data;
2417 int x;
2419 if (!in->str) {
2420 free(in);
2421 return;
2424 if (!d->engine)
2425 goto done;
2427 x = d->engine->status;
2428 send_to_engine(gp, -1, "%s\n", in->str);
2429 d->engine->status = x;
2431 done:
2432 free(in->str);
2433 free(in);
2436 void do_board_details()
2438 config.details = (config.details) ? 0 : 1;
2441 void do_toggle_strict_castling()
2443 int n;
2445 pgn_config_get(PGN_STRICT_CASTLING, &n);
2447 if (n == 0)
2448 pgn_config_set(PGN_STRICT_CASTLING, 1);
2449 else
2450 pgn_config_set(PGN_STRICT_CASTLING, 0);
2453 void do_play_set_clock()
2455 struct input_data_s *in;
2457 in = Calloc(1, sizeof(struct input_data_s));
2458 in->efunc = do_clock_input_finalize;
2459 construct_input(_("Set Clock"), NULL, 1, 1,
2460 _ ("Format: [W | B] [+]T[+I] | ++I | M/T [M/T [...] [SD/T]] [+I]\n" \
2461 "T = time (hms), I = increment, M = moves per, SD = sudden death\ne.g., 30m or 4m+12s or 35/90m SD/30m"),
2462 NULL, NULL, 0, in, INPUT_HIST_CLOCK, -1);
2465 void do_play_toggle_human()
2467 struct userdata_s *d = gp->data;
2469 TOGGLE_FLAG(d->flags, CF_HUMAN);
2471 if (!TEST_FLAG(d->flags, CF_HUMAN) && pgn_history_total(gp->hp)) {
2472 if (init_chess_engine(gp))
2473 return;
2476 CLEAR_FLAG(d->flags, CF_ENGINE_LOOP);
2478 if (d->engine)
2479 d->engine->status = ENGINE_READY;
2482 void do_play_toggle_engine()
2484 struct userdata_s *d = gp->data;
2486 TOGGLE_FLAG(d->flags, CF_ENGINE_LOOP);
2487 CLEAR_FLAG(d->flags, CF_HUMAN);
2489 if (d->engine && TEST_FLAG(d->flags, CF_ENGINE_LOOP)) {
2490 char *fen = pgn_game_to_fen (gp, d->b);
2492 pgn_board_update(gp, d->b,
2493 pgn_history_total(gp->hp));
2494 add_engine_command(gp, ENGINE_READY, "setboard %s\n", fen);
2495 free (fen);
2500 * This will send a command to the engine skipping the command queue.
2502 void do_play_send_command()
2504 struct userdata_s *d = gp->data;
2505 struct input_data_s *in;
2507 if (!d->engine || d->engine->status == ENGINE_OFFLINE) {
2508 if (init_chess_engine(gp))
2509 return;
2512 in = Calloc(1, sizeof(struct input_data_s));
2513 in->efunc = do_engine_command_finalize;
2514 construct_input(_("Engine Command"), NULL, 1, 1, NULL, NULL, NULL, 0, in, INPUT_HIST_ENGINE, -1);
2517 void do_play_switch_turn()
2519 struct userdata_s *d = gp->data;
2521 pgn_switch_side(gp);
2522 pgn_switch_turn(gp);
2524 if (!TEST_FLAG(d->flags, CF_HUMAN))
2525 add_engine_command(gp, -1,
2526 (gp->side == WHITE) ? "white\n" : "black\n");
2528 update_status_window(gp);
2531 void do_play_toggle_eh_mode()
2533 struct userdata_s *d = gp->data;
2535 if (!TEST_FLAG(d->flags, CF_HUMAN)) {
2536 if (!gp->hindex){
2537 pgn_switch_side(gp, TRUE);
2538 d->play_mode = (d->play_mode) ? PLAY_HE : PLAY_EH;
2539 if (gp->side == BLACK)
2540 update_status_notify(gp, _("Press 'g' to start the game"));
2542 rotate = (rotate) ? FALSE : TRUE;
2544 else
2545 message(NULL, ANY_KEY_STR,
2546 _("You may only switch sides at the start of the \n"
2547 "game. Press ^K or ^N to begin a new game."));
2551 void do_play_undo()
2553 struct userdata_s *d = gp->data;
2555 if (!pgn_history_total(gp->hp))
2556 return;
2558 if (keycount) {
2559 if (gp->hindex - keycount < 0)
2560 gp->hindex = 0;
2561 else {
2562 if (go_move)
2563 gp->hindex -= (keycount * 2) -1;
2564 else
2565 gp->hindex -= keycount * 2;
2568 else {
2569 if (gp->hindex - 2 < 0)
2570 gp->hindex = 0;
2571 else {
2572 if (go_move)
2573 gp->hindex -= 1;
2574 else
2575 gp->hindex -= 2;
2579 pgn_history_free(gp->hp, gp->hindex);
2580 gp->hindex = pgn_history_total(gp->hp);
2581 pgn_board_update(gp, d->b, gp->hindex);
2583 if (d->engine && d->engine->status == ENGINE_READY) {
2584 char *fen = pgn_game_to_fen(gp, d->b);
2586 add_engine_command(gp, ENGINE_READY, "setboard %s\n", fen);
2587 free (fen);
2588 d->engine->status = ENGINE_READY;
2591 update_history_window(gp);
2593 if (go_move) {
2594 pgn_switch_side(gp, FALSE);
2595 go_move--;
2599 void do_play_toggle_pause()
2601 struct userdata_s *d = gp->data;
2603 if (!TEST_FLAG(d->flags, CF_HUMAN) && gp->turn !=
2604 gp->side) {
2605 d->paused = -1;
2606 return;
2609 d->paused = (d->paused) ? 0 : 1;
2612 void do_play_go()
2614 struct userdata_s *d = gp->data;
2616 if (TEST_FLAG(d->flags, CF_HUMAN))
2617 return;
2619 if (fm_loaded_file && gp->side != gp->turn) {
2620 pgn_switch_side(gp, FALSE);
2621 add_engine_command(gp, ENGINE_THINKING, "black\n");
2624 add_engine_command(gp, ENGINE_THINKING, "go\n");
2626 // Completa la función para que permita seguir jugando al usarla.
2627 // Complete the function to allow continue playing when using.
2628 if (gp->side == gp->turn)
2629 pgn_switch_side(gp, FALSE);
2631 go_move++;
2634 void do_play_config_command()
2636 int x, w;
2638 if (config.keys) {
2639 for (x = 0; config.keys[x]; x++) {
2640 if (config.keys[x]->c == input_c) {
2641 switch (config.keys[x]->type) {
2642 case KEY_DEFAULT:
2643 add_engine_command(gp, -1, "%s\n",
2644 config.keys[x]->str);
2645 break;
2646 case KEY_SET:
2647 if (!keycount)
2648 break;
2650 add_engine_command(gp, -1,
2651 "%s %i\n", config.keys[x]->str, keycount);
2652 keycount = 0;
2653 break;
2654 case KEY_REPEAT:
2655 if (!keycount)
2656 break;
2658 for (w = 0; w < keycount; w++)
2659 add_engine_command(gp, -1,
2660 "%s\n", config.keys[x]->str);
2661 keycount = 0;
2662 break;
2668 update_status_notify(gp, NULL);
2671 void do_play_cancel_selected()
2673 struct userdata_s *d = gp->data;
2675 d->sp.icon = d->sp.srow = d->sp.scol = 0;
2676 keycount = 0;
2677 pgn_reset_valid_moves(d->b);
2678 update_status_notify(gp, NULL);
2681 void do_play_commit()
2683 struct userdata_s *d = gp->data;
2685 pushkey = keycount = 0;
2686 update_status_notify(gp, NULL);
2688 if (!TEST_FLAG(d->flags, CF_HUMAN) &&
2689 (!d->engine || d->engine->status == ENGINE_THINKING))
2690 return;
2692 if (!d->sp.icon)
2693 return;
2695 d->sp.row = d->c_row;
2696 d->sp.col = d->c_col;
2698 if (rotate) {
2699 rotate_position(SP_POSITION);
2700 rotate_position(SPS_POSITION);
2703 move_to_engine(gp);
2705 // Completa la función para que permita seguir jugando cuando se carga un
2706 // archivo pgn (con juego no terminado) que inicie con turno del lado
2707 // negro.
2708 // Complete the function to allow continue playing when loading a file
2709 // pgn (with unfinished game) you start to turn black side.
2710 if (gp->side != gp->turn)
2711 pgn_switch_side(gp, FALSE);
2713 if (rotate && d->sp.icon)
2714 rotate_position(SPS_POSITION);
2716 // Envia comando 'go' a Polyglot en el primer movimiento debido a que
2717 // polyglot no envia el movimiento y cboard se queda esperando.
2718 // Send command 'go' to the first movement Polyglot because cboard
2719 // waits to send polyglot movement and this does not make.
2720 if (config.fmpolyglot &&
2721 ((gp->side == WHITE && !gp->hindex) || fm_loaded_file))
2722 add_engine_command(gp, ENGINE_THINKING, "go\n");
2724 go_move = 0;
2725 fm_loaded_file = FALSE;
2728 void do_play_select()
2730 struct userdata_s *d = gp->data;
2732 if (!TEST_FLAG(d->flags, CF_HUMAN) && (!d->engine ||
2733 d->engine->status == ENGINE_OFFLINE)) {
2734 if (init_chess_engine(gp))
2735 return;
2738 if (d->engine && d->engine->status == ENGINE_THINKING)
2739 return;
2741 if (d->sp.icon)
2742 do_play_cancel_selected ();
2744 if (rotate)
2745 rotate_position(CURSOR_POSITION);
2747 d->sp.icon = d->b[RANKTOBOARD(d->c_row)][FILETOBOARD(d->c_col)].icon;
2749 if (pgn_piece_to_int(d->sp.icon) == OPEN_SQUARE) {
2750 d->sp.icon = 0;
2751 return;
2754 if (((islower(d->sp.icon) && gp->turn != BLACK)
2755 || (isupper(d->sp.icon) && gp->turn != WHITE))) {
2756 struct key_s **k;
2757 char *str = Malloc (512);
2759 for (k = play_keys; *k; k++) {
2760 if ((*k)->f == do_play_toggle_eh_mode)
2761 break;
2764 snprintf (str, 512, _("It is not your turn to move. You may switch playing sides by pressing \"%lc\"."),
2765 *k ? (*k)->c : '?');
2766 message(NULL, ANY_KEY_STR, "%s", str);
2767 free (str);
2768 d->sp.icon = 0;
2769 return;
2770 #if 0
2771 if (pgn_history_total(gp->hp)) {
2772 message(NULL, ANY_KEY_STR, "%s", _("It is not your turn to move. You can switch sides "));
2773 d->sp.icon = 0;
2774 return;
2776 else {
2777 if (pgn_tag_find(gp->tag, "FEN") != E_PGN_ERR)
2778 return;
2780 add_engine_command(gp, ENGINE_READY, "black\n");
2781 pgn_switch_turn(gp);
2783 if (gp->side != BLACK)
2784 pgn_switch_side(gp);
2786 #endif
2789 d->sp.srow = d->c_row;
2790 d->sp.scol = d->c_col;
2792 if (config.validmoves)
2793 pgn_find_valid_moves(gp, d->b, d->sp.scol, d->sp.srow);
2795 if (rotate) {
2796 rotate_position(CURSOR_POSITION);
2797 rotate_position(SPS_POSITION);
2800 CLEAR_FLAG(d->flags, CF_NEW);
2801 start_clock(gp);
2804 /* FIXME: keys with the same function should comma deliminated. */
2805 static wchar_t *build_help(struct key_s **keys)
2807 int i, nlen = 1, len, t, n;
2808 wchar_t *buf = NULL, *wc = NULL;
2809 wchar_t *p;
2811 if (!keys)
2812 return NULL;
2814 for (i = len = t = 0; keys[i]; i++) {
2815 if (!keys[i]->d)
2816 continue;
2818 if (keys[i]->key) {
2819 if (wcslen(keys[i]->key) > nlen) {
2820 nlen = wcslen(keys[i]->key);
2821 t += nlen;
2823 else
2824 t++;
2827 if (keys[i]->d) {
2828 if (wcslen(keys[i]->d) > len)
2829 len = wcslen(keys[i]->d);
2832 t += len;
2833 t += keys[i]->r;
2836 t += 4 + i;
2837 buf = Malloc(t*sizeof(wchar_t));
2838 p = buf;
2840 for (i = 0; keys[i]; i++) {
2841 if (!keys[i]->d)
2842 continue;
2844 if (keys[i]->key)
2845 n = wcslen(keys[i]->key);
2846 else
2847 n = 1;
2849 while (n++ <= nlen)
2850 *p++ = ' ';
2852 *p = 0;
2854 if (keys[i]->key) {
2855 wcscat(buf, keys[i]->key);
2856 p = buf + wcslen(buf);
2858 else
2859 *p++ = keys[i]->c;
2861 *p++ = ' ';
2862 *p++ = '-';
2863 *p++ = ' ';
2864 *p = 0;
2866 if (keys[i]->d)
2867 wcscat(buf, keys[i]->d);
2869 if (keys[i]->r) {
2870 wc = str_to_wchar ("*");
2871 wcscat(buf, wc);
2872 free (wc);
2875 wc = str_to_wchar ("\n");
2876 wcscat(buf, wc);
2877 free (wc);
2878 p = buf + wcslen(buf);
2881 return buf;
2884 void do_more_help(WIN *);
2885 void do_main_help(WIN *win)
2887 wchar_t *buf;
2889 switch (win->c) {
2890 case 'p':
2891 buf = build_help(play_keys);
2892 construct_message(_("Play Mode Keys (* = can take a repeat count)"), ANY_KEY_STR, 0, 0,
2893 NULL, NULL, buf, do_more_help, 0, 1, "%ls", buf);
2894 break;
2895 case 'h':
2896 buf = build_help(history_keys);
2897 construct_message(_("History Mode Keys (* = can take a repeat count)"), ANY_KEY_STR, 0, 0,
2898 NULL, NULL, buf, do_more_help, 0, 1, "%ls", buf);
2899 break;
2900 case 'e':
2901 buf = build_help(edit_keys);
2902 construct_message(_("Edit Mode Keys (* = can take a repeat count)"), ANY_KEY_STR, 0, 0,
2903 NULL, NULL, buf, do_more_help, 0, 1, "%ls", buf);
2904 break;
2905 case 'g':
2906 buf = build_help(global_keys);
2907 construct_message(_("Global Game Keys (* = can take a repeat count)"), ANY_KEY_STR, 0, 0,
2908 NULL, NULL, buf, do_more_help, 0, 1, "%ls", buf);
2909 break;
2910 default:
2911 break;
2915 void do_more_help(WIN *win)
2917 if (win->c == KEY_F(1) || win->c == CTRL_KEY('g'))
2918 construct_message(_("Command Key Index"),
2919 _ ("p/h/e/g or any other key to quit"), 0, 0,
2920 NULL, NULL, NULL, do_main_help, 0, 0, "%s",
2922 "p - play mode keys\n"
2923 "h - history mode keys\n"
2924 "e - board edit mode keys\n"
2925 "g - global game keys"
2929 void do_play_help()
2931 wchar_t *buf = build_help(play_keys);
2933 construct_message(_("Play Mode Keys (* = can take a repeat count)"),
2934 ANY_KEY_STR, 0, 0, NULL, NULL,
2935 buf, do_more_help, 0, 1, "%ls", buf);
2938 void do_play_history_mode()
2940 struct userdata_s *d = gp->data;
2942 if (!pgn_history_total(gp->hp) ||
2943 (d->engine && d->engine->status == ENGINE_THINKING))
2944 return;
2946 d->mode = MODE_HISTORY;
2947 pgn_board_update(gp, d->b, pgn_history_total(gp->hp));
2950 void do_play_edit_mode()
2952 struct userdata_s *d = gp->data;
2954 if (pgn_history_total(gp->hp))
2955 return;
2957 pgn_board_init_fen(gp, d->b, NULL);
2958 config.details++;
2959 d->mode = MODE_EDIT;
2962 void do_edit_insert_finalize(WIN *win)
2964 struct userdata_s *d = win->data;
2966 if (pgn_piece_to_int(win->c) == -1)
2967 return;
2969 d->b[RANKTOBOARD(d->c_row)][FILETOBOARD(d->c_col)].icon = win->c;
2972 void do_edit_select()
2974 struct userdata_s *d = gp->data;
2976 if (d->sp.icon)
2977 return;
2979 d->sp.icon = d->b[RANKTOBOARD(d->c_row)][FILETOBOARD(d->c_col)].icon;
2981 if (pgn_piece_to_int(d->sp.icon) == OPEN_SQUARE) {
2982 d->sp.icon = 0;
2983 return;
2986 d->sp.srow = d->c_row;
2987 d->sp.scol = d->c_col;
2990 void do_edit_commit()
2992 int p;
2993 struct userdata_s *d = gp->data;
2995 pushkey = keycount = 0;
2996 update_status_notify(gp, NULL);
2998 if (!d->sp.icon)
2999 return;
3001 d->sp.row = d->c_row;
3002 d->sp.col = d->c_col;
3003 p = d->b[RANKTOBOARD(d->sp.srow)][FILETOBOARD(d->sp.scol)].icon;
3004 d->b[RANKTOBOARD(d->sp.row)][FILETOBOARD(d->sp.col)].icon = p;
3005 d->b[RANKTOBOARD(d->sp.srow)][FILETOBOARD(d->sp.scol)].icon =
3006 pgn_int_to_piece(gp->turn, OPEN_SQUARE);
3007 d->sp.icon = d->sp.srow = d->sp.scol = 0;
3010 void do_edit_delete()
3012 struct userdata_s *d = gp->data;
3014 if (d->sp.icon)
3015 d->b[RANKTOBOARD(d->sp.srow)][FILETOBOARD(d->sp.scol)].icon =
3016 pgn_int_to_piece(gp->turn, OPEN_SQUARE);
3017 else
3018 d->b[RANKTOBOARD(d->c_row)][FILETOBOARD(d->c_col)].icon =
3019 pgn_int_to_piece(gp->turn, OPEN_SQUARE);
3021 d->sp.icon = d->sp.srow = d->sp.scol = 0;
3024 void do_edit_cancel_selected()
3026 struct userdata_s *d = gp->data;
3028 d->sp.icon = d->sp.srow = d->sp.scol = 0;
3029 keycount = 0;
3030 update_status_notify(gp, NULL);
3033 void do_edit_switch_turn()
3035 pgn_switch_turn(gp);
3038 void do_edit_toggle_castle()
3040 struct userdata_s *d = gp->data;
3042 castling_state(gp, d->b, RANKTOBOARD(d->c_row),
3043 FILETOBOARD(d->c_col),
3044 d->b[RANKTOBOARD(d->c_row)][FILETOBOARD(d->c_col)].icon, 1);
3047 void do_edit_insert()
3049 struct userdata_s *d = gp->data;
3051 construct_message(_("Insert Piece"), _("P=pawn, R=rook, N=knight, B=bishop, "), 0, 0, NULL, NULL,
3052 d->b, do_edit_insert_finalize, 0, 0, "%s", _("Type the piece letter to insert. Lowercase "));
3055 void do_edit_enpassant()
3057 struct userdata_s *d = gp->data;
3059 if (d->c_row == 6 || d->c_row == 3) {
3060 pgn_reset_enpassant(d->b);
3061 d->b[RANKTOBOARD(d->c_row)][FILETOBOARD(d->c_col)].enpassant = 1;
3065 void do_edit_help()
3067 wchar_t *buf = build_help(edit_keys);
3069 construct_message(_("Edit Mode Keys (* = can take a repeat count)"),
3070 ANY_KEY_STR, 0, 0, NULL, NULL,
3071 buf, do_more_help, 0, 1, "%ls", buf);
3074 void do_edit_exit()
3076 struct userdata_s *d = gp->data;
3077 char *fen = pgn_game_to_fen(gp, d->b);
3079 config.details--;
3080 pgn_tag_add(&gp->tag, "FEN", fen);
3081 free (fen);
3082 pgn_tag_add(&gp->tag, "SetUp", "1");
3083 pgn_tag_sort(gp->tag);
3084 pgn_board_update(gp, d->b, gp->hindex);
3085 d->mode = MODE_PLAY;
3088 void really_do_annotate_finalize(struct input_data_s *in,
3089 struct userdata_s *d)
3091 HISTORY *h = in->data;
3092 int len;
3094 if (!in->str) {
3095 if (h->comment) {
3096 free(h->comment);
3097 h->comment = NULL;
3100 else {
3101 len = strlen(in->str);
3102 h->comment = Realloc(h->comment, len+1);
3103 strncpy(h->comment, in->str, len);
3104 h->comment[len] = 0;
3107 free(in->str);
3108 free(in);
3109 SET_FLAG(d->flags, CF_MODIFIED);
3112 void do_annotate_finalize(WIN *win)
3114 struct userdata_s *d = gp->data;
3115 struct input_data_s *in = win->data;
3117 really_do_annotate_finalize(in, d);
3120 void do_find_move_exp_finalize(int init, int which)
3122 int n;
3123 struct userdata_s *d = gp->data;
3124 static int firstrun;
3125 static regex_t r;
3126 int ret;
3127 char errbuf[255];
3129 if (init || !firstrun) {
3130 if (!firstrun)
3131 regfree(&r);
3133 if ((ret = regcomp(&r, moveexp, REG_EXTENDED|REG_NOSUB)) != 0) {
3134 regerror(ret, &r, errbuf, sizeof(errbuf));
3135 cmessage(_("Error Compiling Regular Expression"), ANY_KEY_STR, "%s", errbuf);
3136 return;
3139 firstrun = 1;
3142 if ((n = find_move_exp(gp, r,
3143 (which == -1) ? 0 : 1, (keycount) ? keycount : 1)) == -1)
3144 return;
3146 gp->hindex = n;
3147 pgn_board_update(gp, d->b, gp->hindex);
3150 void do_find_move_exp(WIN *win)
3152 struct input_data_s *in = win->data;
3153 int *n = in->data;
3154 int which = *n;
3156 if (in->str) {
3157 strncpy(moveexp, in->str, sizeof(moveexp)-1);
3158 moveexp[sizeof(moveexp)-1] = 0;
3159 do_find_move_exp_finalize(1, which);
3160 free(in->str);
3163 free(in->data);
3164 free(in);
3167 void do_move_jump_finalize(int n)
3169 struct userdata_s *d = gp->data;
3171 if (n < 0 || n > (pgn_history_total(gp->hp) / 2))
3172 return;
3174 keycount = 0;
3175 update_status_notify(gp, NULL);
3176 gp->hindex = (n) ? n * 2 - 1 : n * 2;
3177 pgn_board_update(gp, d->b, gp->hindex);
3180 void do_move_jump(WIN *win)
3182 struct input_data_s *in = win->data;
3184 if (!in->str || !isinteger(in->str)) {
3185 if (in->str)
3186 free(in->str);
3188 free(in);
3189 return;
3192 do_move_jump_finalize(atoi(in->str));
3193 free(in->str);
3194 free(in);
3197 struct history_menu_s {
3198 char *line;
3199 int hindex;
3200 int ravlevel;
3201 int move;
3202 int indent;
3205 void free_history_menu_data(struct history_menu_s **h)
3207 int i;
3209 if (!h)
3210 return;
3212 for (i = 0; h[i]; i++) {
3213 free(h[i]->line);
3214 free(h[i]);
3217 free(h);
3220 void get_history_data(HISTORY **hp, struct history_menu_s ***menu, int m,
3221 int turn)
3223 int i, n = 0;
3224 int t = pgn_history_total(hp);
3225 char buf[MAX_SAN_MOVE_LEN + 4];
3226 static int depth;
3227 struct history_menu_s **hmenu = *menu;
3229 if (hmenu)
3230 for (n = 0; hmenu[n]; n++);
3231 else
3232 depth = 0;
3234 for (i = 0; i < t; i++) {
3235 hmenu = Realloc(hmenu, (n + 2) * sizeof(struct history_menu_s *));
3236 hmenu[n] = Malloc(sizeof(struct history_menu_s));
3237 snprintf(buf, sizeof(buf), "%c%s%s", (turn == WHITE) ? 'W' : 'B',
3238 hp[i]->move, (hp[i]->comment || hp[i]->nag[0]) ? " !" : "");
3239 hmenu[n]->line = strdup(buf);
3240 hmenu[n]->hindex = i;
3241 hmenu[n]->indent = 0;
3242 hmenu[n]->ravlevel = depth;
3243 hmenu[n]->move = (n && depth > hmenu[n-1]->ravlevel) ? m++ : m;
3244 n++;
3245 hmenu[n] = NULL;
3247 #if 0
3248 if (hp[i]->rav) {
3249 depth++;
3250 get_history_data(hp[i]->rav, &hmenu, m, turn);
3251 for (n = 0; hmenu[n]; n++);
3252 depth--;
3254 if (depth)
3255 m--;
3257 #endif
3259 turn = (turn == WHITE) ? BLACK : WHITE;
3262 *menu = hmenu;
3265 void history_draw_update(struct menu_input_s *m)
3267 GAME g = m->data;
3268 struct userdata_s *d = g->data;
3270 g->hindex = m->selected + 1;
3271 update_cursor(g, m->selected);
3272 pgn_board_update(g, d->b, m->selected + 1);
3275 struct menu_item_s **get_history_items(WIN *win)
3277 struct menu_input_s *m = win->data;
3278 GAME g = m->data;
3279 struct userdata_s *d = g->data;
3280 struct history_menu_s **hm = d->data;
3281 struct menu_item_s **items = m->items;
3282 int i;
3284 if (!hm) {
3285 get_history_data(g->history, &hm, 0,
3286 TEST_FLAG(g->flags, GF_BLACK_OPENING));
3287 m->selected = g->hindex - 1;
3289 if (m->selected < 0)
3290 m->selected = 0;
3292 m->draw_exit_func = history_draw_update;
3295 d->data = hm;
3297 if (items) {
3298 for (i = 0; items[i]; i++)
3299 free(items[i]);
3301 free(items);
3302 items = NULL;
3305 for (i = 0; hm[i]; i++) {
3306 items = Realloc(items, (i+2) * sizeof(struct menu_item_s *));
3307 items[i] = Malloc(sizeof(struct menu_item_s));
3308 items[i]->name = hm[i]->line;
3309 items[i]->value = NULL;
3310 items[i]->selected = 0;
3313 if (items)
3314 items[i] = NULL;
3316 m->nofree = 1;
3317 m->items = items;
3318 return items;
3321 void history_menu_quit(struct menu_input_s *m)
3323 pushkey = -1;
3326 void history_menu_exit(WIN *win)
3328 GAME g = win->data;
3329 struct userdata_s *d = g->data;
3330 struct history_menu_s **hm = d->data;
3331 int i;
3333 if (!hm)
3334 return;
3336 for (i = 0; hm[i]; i++) {
3337 free(hm[i]->line);
3338 free(hm[i]);
3341 free(hm);
3342 d->data = NULL;
3345 // FIXME RAV
3346 void history_menu_next(struct menu_input_s *m)
3348 GAME g = m->data;
3349 struct userdata_s *d = g->data;
3350 struct history_menu_s **hm = d->data;
3351 int n, t;
3353 for (t = 0; hm[t]; t++);
3355 if (m->selected + 1 == t)
3356 n = 0;
3357 else
3358 n = hm[m->selected + 1]->hindex;
3360 n++;
3361 g->hindex = n;
3364 // FIXME RAV
3365 void history_menu_prev(struct menu_input_s *m)
3367 GAME g = m->data;
3368 struct userdata_s *d = g->data;
3369 struct history_menu_s **hm = d->data;
3370 int n, t;
3372 for (t = 0; hm[t]; t++);
3374 if (m->selected - 1 < 0)
3375 n = t - 1;
3376 else
3377 n = hm[m->selected - 1]->hindex;
3379 n++;
3380 g->hindex = n;
3383 void history_menu_help(struct menu_input_s *m)
3385 message("History Menu Help", ANY_KEY_STR, "%s",
3387 " UP/DOWN - previous/next menu item\n"
3388 " HOME/END - first/last menu item\n"
3389 " PGDN/PGUP - next/previous page\n"
3390 " a-zA-Z0-9 - jump to item\n"
3391 " CTRL-a - annotate the selected move\n"
3392 " ENTER - view annotation\n"
3393 " CTRL-d - toggle board details\n"
3394 " ESCAPE/M - return to move history"
3398 void do_annotate_move(HISTORY *hp)
3400 char buf[COLS - 4];
3401 struct input_data_s *in;
3403 snprintf(buf, sizeof(buf), "%s \"%s\"", _("Editing Annotation for"), hp->move);
3404 in = Calloc(1, sizeof(struct input_data_s));
3405 in->data = hp;
3406 in->efunc = do_annotate_finalize;
3407 construct_input(buf, hp->comment, MAX_PGN_LINE_LEN / INPUT_WIDTH, 0,
3408 _("Type CTRL-t to edit NAG"), edit_nag, NULL, CTRL_KEY('T'), in, -1, -1);
3411 void history_menu_view_annotation(struct menu_input_s *m)
3413 GAME g = m->data;
3415 // FIXME RAV
3416 view_annotation(g->history[m->selected]);
3419 void history_menu_annotate_finalize(WIN *win)
3421 struct input_data_s *in = win->data;
3422 GAME g = in->moredata;
3423 struct userdata_s *d = g->data;
3424 struct history_menu_s **hm = d->data;
3426 really_do_annotate_finalize(in, d);
3427 free_history_menu_data(hm);
3428 hm = NULL;
3429 get_history_data(g->history, &hm, 0, TEST_FLAG(g->flags, GF_BLACK_OPENING));
3430 d->data = hm;
3431 pushkey = REFRESH_MENU;
3434 void history_menu_annotate(struct menu_input_s *m)
3436 GAME g = m->data;
3437 char buf[COLS - 4];
3438 struct input_data_s *in;
3439 HISTORY *hp = g->history[m->selected]; // FIXME RAV
3441 snprintf(buf, sizeof(buf), "%s \"%s\"", _("Editing Annotation for"), hp->move);
3442 in = Calloc(1, sizeof(struct input_data_s));
3443 in->data = hp;
3444 in->moredata = m->data;
3445 in->efunc = history_menu_annotate_finalize;
3446 construct_input(buf, hp->comment, MAX_PGN_LINE_LEN / INPUT_WIDTH, 0,
3447 _("Type CTRL-t to edit NAG"), edit_nag, NULL, CTRL_KEY('T'), in, -1, -1);
3450 void history_menu_details(struct menu_input_s *m)
3452 do_board_details();
3455 // FIXME RAV
3456 void history_menu_print(WIN *win)
3458 struct menu_input_s *m = win->data;
3459 GAME g = m->data;
3460 struct userdata_s *d = g->data;
3461 struct history_menu_s **hm = d->data;
3462 struct history_menu_s *h = hm[m->top];
3463 int i;
3464 char *p = m->item->name;
3465 int line = m->print_line - 2;
3467 * Solaris 5.9 doesn't have wattr_get() or any function that requires an
3468 * attr_t data type.
3470 #ifdef HAVE_ATTR_T
3471 attr_t attrs;
3472 short pair;
3473 #endif
3474 int total;
3476 for (total = 0; hm[total]; total++);
3477 #ifdef HAVE_ATTR_T
3478 wattr_get(win->w, &attrs, &pair, NULL);
3479 wattroff(win->w, COLOR_PAIR(pair));
3480 #endif
3481 mvwaddch(win->w, m->print_line, 1,
3482 *p == 'W' ? *p | mix_cp(CP_BOARD_WHITE, CP_HISTORY_WINDOW, ATTRS(CP_BOARD_WHITE), A_FG_B_BG) : *p | mix_cp(CP_BOARD_BLACK, CP_HISTORY_WINDOW, ATTRS(CP_BOARD_BLACK), A_FG_B_BG));
3483 p++;
3485 if (h->hindex == 0 && line == 0)
3486 waddch(win->w, ACS_ULCORNER | CP_HISTORY_MENU_LG);
3487 else if ((!hm[h->hindex + (win->rows - 5) + 1] && line == win->rows - 5) ||
3488 (m->top + line == total - 1))
3489 waddch(win->w, ACS_LLCORNER | CP_HISTORY_MENU_LG);
3490 else if (hm[m->top + 1]->ravlevel != h->ravlevel || !h->ravlevel)
3491 waddch(win->w, ACS_LTEE | CP_HISTORY_MENU_LG);
3492 else
3493 waddch(win->w, ACS_VLINE | CP_HISTORY_MENU_LG);
3495 #ifdef HAVE_ATTR_T
3496 wattron(win->w, COLOR_PAIR(pair) | attrs);
3497 #endif
3499 for (i = 2; *p; p++, i++)
3500 waddch(win->w, (*p == '!') ? *p | A_BOLD : *p);
3502 while (i++ < win->cols - 2)
3503 waddch(win->w, ' ');
3506 void history_menu(GAME g)
3508 struct menu_key_s **keys = NULL;
3510 add_menu_key(&keys, KEY_ESCAPE, history_menu_quit);
3511 add_menu_key(&keys, 'M', history_menu_quit);
3512 add_menu_key(&keys, KEY_UP, history_menu_prev);
3513 add_menu_key(&keys, KEY_DOWN, history_menu_next);
3514 add_menu_key(&keys, KEY_F(1), history_menu_help);
3515 add_menu_key(&keys, CTRL_KEY('a'), history_menu_annotate);
3516 add_menu_key(&keys, CTRL_KEY('d'), history_menu_details);
3517 add_menu_key(&keys, '\n', history_menu_view_annotation);
3518 construct_menu(LINES, TAG_WIDTH, 0, config.boardleft ? BOARD_WIDTH : 0,
3519 _("Move History Tree"), 1, get_history_items, keys, g,
3520 history_menu_print, history_menu_exit);
3523 void do_history_menu()
3525 history_menu(gp);
3528 void do_history_half_move_toggle()
3530 movestep = (movestep == 1) ? 2 : 1;
3531 update_history_window(gp);
3534 void do_history_rotate_board()
3536 rotate = (rotate) ? FALSE : TRUE;
3539 void do_history_jump_next()
3541 struct userdata_s *d = gp->data;
3543 pgn_history_next(gp, d->b, (keycount > 0) ?
3544 config.jumpcount * keycount * movestep :
3545 config.jumpcount * movestep);
3548 void do_history_jump_prev()
3550 struct userdata_s *d = gp->data;
3552 pgn_history_prev(gp, d->b, (keycount) ?
3553 config.jumpcount * keycount * movestep :
3554 config.jumpcount * movestep);
3557 void do_history_prev()
3559 struct userdata_s *d = gp->data;
3561 pgn_history_prev(gp, d->b,
3562 (keycount) ? keycount * movestep : movestep);
3565 void do_history_next()
3567 struct userdata_s *d = gp->data;
3569 pgn_history_next(gp, d->b, (keycount) ?
3570 keycount * movestep : movestep);
3573 void do_history_mode_finalize(struct userdata_s *d)
3575 pushkey = 0;
3576 d->mode = MODE_PLAY;
3579 void do_history_mode_confirm(WIN *win)
3581 struct userdata_s *d = gp->data;
3582 wchar_t str[] = { win->c, 0 };
3584 if (!wcscmp (str, resume_wchar)) {
3585 pgn_history_free(gp->hp, gp->hindex);
3586 pgn_board_update(gp, d->b, pgn_history_total(gp->hp));
3588 #if 0
3589 case 'C':
3590 case 'c':
3591 if (pgn_history_rav_new(gp, d->b,
3592 gp->hindex) != E_PGN_OK)
3593 return;
3595 break;
3596 #endif
3597 else
3598 return;
3600 if (!TEST_FLAG(d->flags, CF_HUMAN)) {
3601 char *fen = pgn_game_to_fen(gp, d->b);
3603 add_engine_command(gp, ENGINE_READY, "setboard %s\n", fen);
3604 free (fen);
3607 do_history_mode_finalize(d);
3610 void do_history_toggle()
3612 struct userdata_s *d = gp->data;
3614 // FIXME Resuming from previous history could append to a RAV.
3615 if (gp->hindex != pgn_history_total(gp->hp)) {
3616 if (!pushkey)
3617 construct_message(NULL, _ ("What would you like to do?"), 0, 1,
3618 NULL, NULL, NULL, do_history_mode_confirm, 0, 0,
3619 _("The current move is not the final move of this round. Press \"%ls\" to resume a game from the current move and discard future moves or any other key to cancel."),
3620 resume_wchar);
3621 return;
3623 else {
3624 if (TEST_FLAG(gp->flags, GF_GAMEOVER))
3625 return;
3628 if (gp->side != gp->turn) {
3629 d->play_mode = PLAY_EH;
3631 else {
3632 d->play_mode = PLAY_HE;
3633 rotate = FALSE;
3636 do_history_mode_finalize(d);
3639 void do_history_annotate()
3641 int n = gp->hindex;
3643 if (n && gp->hp[n - 1]->move)
3644 n--;
3645 else
3646 return;
3648 do_annotate_move(gp->hp[n]);
3651 void do_history_help()
3653 wchar_t *buf = build_help(history_keys);
3655 construct_message(_("History Mode Keys (* = can take a repeat count)"),
3656 ANY_KEY_STR, 0, 0, NULL, NULL,
3657 buf, do_more_help, 0, 1, "%ls", buf);
3660 void do_history_find(int which)
3662 struct input_data_s *in;
3663 int *p;
3665 if (pgn_history_total(gp->hp) < 2)
3666 return;
3668 in = Calloc(1, sizeof(struct input_data_s));
3669 p = Malloc(sizeof(int));
3670 *p = which;
3671 in->data = p;
3672 in->efunc = do_find_move_exp;
3674 if (!*moveexp || which == 0) {
3675 construct_input(_("Find Move Text Expression"), NULL, 1, 0, NULL, NULL, NULL,
3676 0, in, INPUT_HIST_MOVE_EXP, -1);
3677 return;
3680 do_find_move_exp_finalize(0, which);
3683 void do_history_find_new()
3685 do_history_find(0);
3688 void do_history_find_prev()
3690 do_history_find(-1);
3693 void do_history_find_next()
3695 do_history_find(1);
3698 void do_history_rav(int which)
3700 struct userdata_s *d = gp->data;
3702 rav_next_prev(gp, d->b, which);
3705 void do_history_rav_next()
3707 do_history_rav(1);
3710 void do_history_rav_prev()
3712 do_history_rav(0);
3715 void do_history_jump()
3717 struct input_data_s *in;
3719 if (pgn_history_total(gp->hp) < 2)
3720 return;
3722 if (!keycount) {
3723 in = Calloc(1, sizeof(struct input_data_s));
3724 in->efunc = do_move_jump;
3726 construct_input(_("Jump to Move Number"), NULL, 1, 1, NULL,
3727 NULL, NULL, 0, in, -1, 0);
3728 return;
3731 do_move_jump_finalize(keycount);
3734 static void free_userdata_once(GAME g)
3736 struct userdata_s *d = g->data;
3738 if (!d)
3739 return;
3741 if (d->engine) {
3742 stop_engine(g);
3744 if (d->engine->enginebuf) {
3745 int n;
3747 for (n = 0; d->engine->enginebuf[n]; n++)
3748 free(d->engine->enginebuf[n]);
3750 free(d->engine->enginebuf);
3753 if (d->engine->queue) {
3754 struct queue_s **q;
3756 for (q = d->engine->queue; *q; q++)
3757 free(*q);
3759 free(d->engine->queue);
3762 free(d->engine);
3765 #ifdef WITH_LIBPERL
3766 if (d->perlfen)
3767 free(d->perlfen);
3769 if (d->oldfen)
3770 free(d->oldfen);
3771 #endif
3773 free(d);
3774 g->data = NULL;
3777 static void free_userdata()
3779 int i;
3781 for (i = 0; i < gtotal; i++) {
3782 free_userdata_once(game[i]);
3783 game[i]->data = NULL;
3787 void update_loading_window(int n)
3789 char buf[16];
3791 if (!loadingw) {
3792 loadingw = newwin(3, COLS / 2, CALCPOSY(3), CALCPOSX(COLS / 2));
3793 loadingp = new_panel(loadingw);
3794 wbkgd(loadingw, CP_MESSAGE_WINDOW);
3797 wmove(loadingw, 0, 0);
3798 wclrtobot(loadingw);
3799 wattron(loadingw, CP_MESSAGE_BORDER);
3800 box(loadingw, ACS_VLINE, ACS_HLINE);
3801 wattroff(loadingw, CP_MESSAGE_BORDER);
3802 mvwprintw(loadingw, 1, CENTER_INT((COLS / 2), 11 +
3803 strlen(itoa(gtotal, buf))),
3804 _("Loading... %i%% (%i games)"), n, gtotal);
3805 update_panels();
3806 doupdate();
3809 static void init_userdata_once(GAME g, int n)
3811 struct userdata_s *d = NULL;
3813 d = Calloc(1, sizeof(struct userdata_s));
3814 d->n = n;
3815 d->c_row = 2, d->c_col = 5;
3816 SET_FLAG(d->flags, CF_NEW);
3817 g->data = d;
3819 if (pgn_board_init_fen(g, d->b, NULL) != E_PGN_OK)
3820 pgn_board_init(d->b);
3823 void init_userdata()
3825 int i;
3827 for (i = 0; i < gtotal; i++)
3828 init_userdata_once(game[i], i);
3831 void fix_marks(int *start, int *end)
3833 int i;
3835 *start = (*start < 0) ? 0 : *start;
3836 *end = (*end < 0) ? 0 : *end;
3838 if (*start > *end) {
3839 i = *start;
3840 *start = *end;
3841 *end = i + 1;
3844 *end = (*end > gtotal) ? gtotal : *end;
3847 void do_new_game_finalize(GAME g)
3849 struct userdata_s *d = g->data;
3851 d->mode = MODE_PLAY;
3852 update_status_notify(g, NULL);
3855 void do_new_game_from_scratch(WIN *win)
3857 wchar_t str[] = { win->c, 0 };
3859 if (wcscmp (str, yes_wchar))
3860 return;
3862 stop_clock();
3863 free_userdata();
3864 pgn_parse(NULL);
3865 gp = game[gindex];
3866 add_custom_tags(&gp->tag);
3867 init_userdata();
3868 loadfile[0] = 0;
3869 do_new_game_finalize(gp);
3870 rotate = FALSE;
3873 void do_new_game()
3875 pgn_new_game();
3876 gp = game[gindex];
3877 add_custom_tags(&gp->tag);
3878 init_userdata_once(gp, gindex);
3879 do_new_game_finalize(gp);
3880 rotate = FALSE;
3883 void do_game_delete_finalize(int n)
3885 struct userdata_s *d;
3887 delete_game((!n) ? gindex : -1);
3888 d = gp->data;
3889 pgn_board_update(gp, d->b, pgn_history_total(gp->hp));
3892 void do_game_delete_confirm(WIN *win)
3894 int *n;
3895 wchar_t str[] = { win->c, 0 };
3897 if (wcscmp (str, yes_wchar)) {
3898 free(win->data);
3899 return;
3902 n = (int *)win->data;
3903 do_game_delete_finalize(*n);
3904 free(win->data);
3907 void do_game_delete()
3909 char *tmp = NULL;
3910 int i, n;
3911 struct userdata_s *d;
3912 int *p;
3914 if (gtotal < 2) {
3915 cmessage(NULL, ANY_KEY_STR, "%s", _("Cannot delete last game."));
3916 return;
3919 tmp = NULL;
3921 for (i = n = 0; i < gtotal; i++) {
3922 d = game[i]->data;
3924 if (TEST_FLAG(d->flags, CF_DELETE))
3925 n++;
3928 if (!n)
3929 tmp = _("Delete the current game?");
3930 else {
3931 if (n == gtotal) {
3932 cmessage(NULL, ANY_KEY_STR, "%s", _("Cannot delete last game."));
3933 return;
3936 tmp = _("Delete all games marked for deletion?");
3939 if (config.deleteprompt) {
3940 p = Malloc(sizeof(int));
3941 *p = n;
3942 construct_message(NULL, _("[ Yes or No ]"), 1, 1, NULL, NULL, p,
3943 do_game_delete_confirm, 0, 0, tmp);
3944 return;
3947 do_game_delete_finalize(n);
3950 void do_find_game_exp_finalize(int which)
3952 struct userdata_s *d = gp->data;
3953 int n;
3955 if ((n = find_game_exp(gameexp, (which == -1) ? 0 : 1,
3956 (keycount) ? keycount : 1)) == -1) {
3957 update_status_notify(gp, "%s", _("No matches found"));
3958 return;
3961 gindex = n;
3962 d = gp->data;
3964 if (pgn_history_total(gp->hp))
3965 d->mode = MODE_HISTORY;
3967 pgn_board_update(gp, d->b, pgn_history_total(gp->hp));
3970 void do_find_game_exp(WIN *win)
3972 struct input_data_s *in = win->data;
3973 int *n = in->data;
3974 int c = *n;
3976 if (in->str) {
3977 strncpy(gameexp, in->str, sizeof(gameexp));
3978 gameexp[sizeof(gameexp)-1] = 0;
3980 if (c == '?')
3981 c = '}';
3983 do_find_game_exp_finalize(c);
3984 free(in->str);
3987 free(in->data);
3988 free(in);
3991 void do_game_jump_finalize(int n)
3993 struct userdata_s *d;
3995 if (--n > gtotal - 1 || n < 0)
3996 return;
3998 gindex = n;
3999 gp = game[gindex];
4000 d = gp->data;
4001 pgn_board_update(gp, d->b, pgn_history_total(gp->hp));
4002 update_status_notify(gp, NULL);
4005 void do_game_jump(WIN *win)
4007 struct input_data_s *in = win->data;
4009 if (!in->str || !isinteger(in->str)) {
4010 if (in->str)
4011 free(in->str);
4013 free(in);
4014 return;
4017 do_game_jump_finalize(atoi(in->str));
4018 free(in->str);
4019 free(in);
4022 void do_load_file(WIN *win)
4024 struct input_data_s *in = win->data;
4025 char *tmp = in->str;
4026 struct userdata_s *d;
4027 PGN_FILE *pgn = NULL;
4028 int n;
4030 if (!in->str) {
4031 free(in);
4032 return;
4035 if ((tmp = pathfix(tmp)) == NULL)
4036 goto done;
4038 n = pgn_open(tmp, "r", &pgn);
4040 if (n == E_PGN_ERR) {
4041 cmessage(ERROR_STR, ANY_KEY_STR, "%s\n%s", tmp, strerror(errno));
4042 goto done;
4044 else if (n == E_PGN_INVALID) {
4045 cmessage(ERROR_STR, ANY_KEY_STR, "%s\n%s", tmp, _("Not a regular file"));
4046 goto done;
4049 free_userdata();
4051 if (pgn_parse(pgn) == E_PGN_ERR) {
4052 del_panel(loadingp);
4053 delwin(loadingw);
4054 loadingw = NULL;
4055 loadingp = NULL;
4056 init_userdata();
4057 goto done;
4060 del_panel(loadingp);
4061 delwin(loadingw);
4062 loadingw = NULL;
4063 loadingp = NULL;
4064 init_userdata();
4065 strncpy(loadfile, tmp, sizeof(loadfile));
4066 loadfile[sizeof(loadfile)-1] = 0;
4067 gp = game[gindex];
4068 d = gp->data;
4070 if (pgn_history_total(gp->hp))
4071 d->mode = MODE_HISTORY;
4073 pgn_board_update(gp, d->b, pgn_history_total(gp->hp));
4075 fm_loaded_file = TRUE;
4077 done:
4078 pgn_close(pgn);
4080 if (in->str)
4081 free(in->str);
4083 free(in);
4086 void do_game_save(WIN *win)
4088 struct input_data_s *in = win->data;
4089 int *x = in->data;
4090 int n = *x;
4091 char *tmp = in->str;
4092 char tfile[FILENAME_MAX];
4093 char *p;
4094 int i;
4095 struct userdata_s *d;
4097 if (!tmp || (tmp = pathfix(tmp)) == NULL)
4098 goto done;
4100 if (pgn_is_compressed(tmp) == E_PGN_ERR) {
4101 p = tmp + strlen(tmp) - 1;
4103 if (*p != 'n' || *(p-1) != 'g' || *(p-2) != 'p' ||
4104 *(p-3) != '.') {
4105 snprintf(tfile, sizeof(tfile), "%s.pgn", tmp);
4106 tmp = tfile;
4111 * When in edit mode, update the FEN tag.
4113 if (n == -1) {
4114 for (i = 0; i < gtotal; i++) {
4115 d = game[i]->data;
4117 if (d->mode == MODE_EDIT) {
4118 char *fen = pgn_game_to_fen(game[i], d->b);
4120 pgn_tag_add(&game[i]->tag, "FEN", fen);
4121 free (fen);
4125 else {
4126 d = game[n]->data;
4128 if (d->mode == MODE_EDIT) {
4129 char *fen = pgn_game_to_fen(game[n], d->b);
4131 pgn_tag_add(&game[n]->tag, "FEN", fen);
4132 free (fen);
4136 save_pgn(tmp, n);
4138 done:
4139 if (in->str)
4140 free(in->str);
4142 free(in->data);
4143 free(in);
4146 void do_get_game_save_input(int n)
4148 struct input_data_s *in = Calloc(1, sizeof(struct input_data_s));
4149 int *p = Malloc(sizeof(int));
4151 in->efunc = do_game_save;
4152 *p = n;
4153 in->data = p;
4155 construct_input(_("Save Game Filename"), loadfile, 1, 1, _("Type TAB for file browser"),
4156 file_browser, NULL, '\t', in, INPUT_HIST_FILE, -1);
4159 void do_game_save_multi_confirm(WIN *win)
4161 int i;
4162 wchar_t str[] = { win->c, 0 };
4164 if (!wcscmp (str, current_wchar))
4165 i = gindex;
4166 else if (!wcscmp (str, all_wchar))
4167 i = -1;
4168 else {
4169 update_status_notify(gp, "%s", _("Save game aborted."));
4170 return;
4173 do_get_game_save_input(i);
4176 void do_global_about()
4178 cmessage("ABOUT", ANY_KEY_STR, "%s\nUsing %s with %i colors "
4179 "and %i color pairs\n%s",
4180 PACKAGE_STRING, curses_version(), COLORS, COLOR_PAIRS,
4181 COPYRIGHT);
4184 void global_game_next_prev(int which)
4186 struct userdata_s *d;
4188 game_next_prev(gp, (which == 1) ? 1 : 0,
4189 (keycount) ? keycount : 1);
4190 d = gp->data;
4192 if (delete_count) {
4193 if (which == 1) {
4194 markend = markstart + delete_count;
4195 delete_count = 0;
4197 else {
4198 markend = markstart - delete_count + 1;
4199 delete_count = -1; // to fix gindex in the other direction
4202 fix_marks(&markstart, &markend);
4203 do_global_toggle_delete();
4206 if (d->mode == MODE_HISTORY)
4207 pgn_board_update(gp, d->b, gp->hindex);
4208 else if (d->mode == MODE_PLAY)
4209 pgn_board_update(gp, d->b, pgn_history_total(gp->hp));
4212 void do_global_next_game()
4214 global_game_next_prev(1);
4217 void do_global_prev_game()
4219 global_game_next_prev(0);
4222 void global_find(int which)
4224 struct input_data_s *in;
4225 int *p;
4227 if (gtotal < 2)
4228 return;
4230 in = Calloc(1, sizeof(struct input_data_s));
4231 p = Malloc(sizeof(int));
4232 *p = which;
4233 in->data = p;
4234 in->efunc = do_find_game_exp;
4236 if (!*gameexp || which == 0) {
4237 construct_input(_("Find Game by Tag Expression"), NULL, 1, 0,
4238 _("[name expression:]value expression"), NULL, NULL, 0, in,
4239 INPUT_HIST_GAME_EXP, -1);
4240 return;
4243 do_find_game_exp_finalize(which);
4246 void do_global_find_new()
4248 global_find(0);
4251 void do_global_find_next()
4253 global_find(1);
4256 void do_global_find_prev()
4258 global_find(-1);
4261 void do_global_game_jump()
4263 if (gtotal < 2)
4264 return;
4266 if (!keycount) {
4267 struct input_data_s *in;
4269 in = Calloc(1, sizeof(struct input_data_s));
4270 in->efunc = do_game_jump;
4271 construct_input(_("Jump to Game Number"), NULL, 1, 1, NULL, NULL, NULL, 0, in,
4272 -1, 0);
4273 return;
4276 do_game_jump_finalize(keycount);
4279 void do_global_toggle_delete()
4281 int i;
4283 pushkey = 0;
4285 if (gtotal < 2)
4286 return;
4288 if (keycount && delete_count == 0) {
4289 markstart = gindex;
4290 delete_count = keycount;
4291 update_status_notify(gp, "%s (delete)", status.notify);
4292 return;
4295 if (markstart >= 0 && markend >= 0) {
4296 for (i = markstart; i < markend; i++) {
4297 if (toggle_delete_flag(i)) {
4298 return;
4302 gindex = (delete_count < 0) ? markstart : i - 1;
4304 else {
4305 if (toggle_delete_flag(gindex))
4306 return;
4309 markstart = markend = -1;
4310 delete_count = 0;
4311 update_status_window(gp);
4314 void do_global_delete_game()
4316 do_game_delete();
4319 void do_global_tag_edit()
4321 struct userdata_s *d = gp->data;
4323 edit_tags(gp, d->b, 1);
4326 void do_global_tag_view()
4328 struct userdata_s *d = gp->data;
4330 edit_tags(gp, d->b, 0);
4333 void do_global_resume_game()
4335 struct input_data_s *in;
4337 in = Calloc(1, sizeof(struct input_data_s));
4338 in->efunc = do_load_file;
4339 construct_input(_("Load Filename"), NULL, 1, 1, _("Type TAB for file browser"), file_browser,
4340 NULL, '\t', in, INPUT_HIST_FILE, -1);
4343 void do_global_save_game()
4345 if (gtotal > 1) {
4346 construct_message(NULL, _("What would you like to do?"), 0, 1,
4347 NULL, NULL, NULL, do_game_save_multi_confirm, 0, 0,
4348 _("There is more than one game loaded. Press \"%ls\" to save the current game, \"%ls\" to save all games or any other key to cancel."),
4349 current_wchar, all_wchar);
4350 return;
4353 do_get_game_save_input(-1);
4356 void do_global_new_game()
4358 do_new_game();
4361 void do_global_copy_game()
4363 int g = gindex;
4364 int i, n;
4365 struct userdata_s *d;
4367 do_global_new_game();
4368 d = gp->data;
4369 n = pgn_tag_total(game[g]->tag);
4371 for (i = 0; i < n; i++)
4372 pgn_tag_add(&gp->tag, game[g]->tag[i]->name,
4373 game[g]->tag[i]->value);
4375 pgn_board_init_fen (gp, d->b, NULL);
4376 n = pgn_history_total(game[g]->history);
4378 // FIXME RAV
4379 for (i = 0; i < n; i++) {
4380 char *frfr = NULL;
4381 char move[MAX_SAN_MOVE_LEN+1] = {0}, *m = move;
4383 strcpy (move, game[g]->history[i]->move);
4384 if (pgn_parse_move(gp, d->b, &m, &frfr) != E_PGN_OK) {
4385 SET_FLAG(gp->flags, GF_PERROR);
4386 return;
4389 pgn_history_add(gp, d->b, move);
4390 free(frfr);
4391 pgn_switch_turn(gp);
4394 pgn_board_update(gp, d->b, pgn_history_total(gp->hp));
4397 void do_global_new_all()
4399 construct_message(NULL, _("[ Yes or No ]"), 1, 1, NULL, NULL, NULL,
4400 do_new_game_from_scratch, 0, 0, "%s", _("Really start a new game from scratch?"));
4403 void do_quit(WIN *win)
4405 wchar_t str[] = { win->c, 0 };
4407 if (wcscmp (str, yes_wchar))
4408 return;
4410 quit = 1;
4413 void do_global_quit()
4415 if (config.exitdialogbox)
4416 construct_message(NULL, _("[ Yes or No ]"), 1, 1, NULL, NULL, NULL,
4417 do_quit, 0, 0, _("Want to Quit?"));
4418 else
4419 quit = 1;
4422 void do_global_toggle_engine_window()
4424 if (!enginew) {
4425 enginew = newwin(LINES, COLS, 0, 0);
4426 enginep = new_panel(enginew);
4427 window_draw_title(enginew, _("Engine IO Window"), COLS, CP_MESSAGE_TITLE,
4428 CP_MESSAGE_BORDER);
4429 hide_panel(enginep);
4432 if (panel_hidden(enginep)) {
4433 update_engine_window(gp);
4434 top_panel(enginep);
4436 else {
4437 hide_panel(enginep);
4441 void do_global_toggle_board_details()
4443 do_board_details();
4446 void do_global_toggle_strict_castling()
4448 do_toggle_strict_castling();
4451 // Global and other keys.
4452 static int globalkeys()
4454 struct userdata_s *d = gp->data;
4455 int i;
4458 * These cannot be modified and other game mode keys cannot conflict with
4459 * these.
4461 switch (input_c) {
4462 case CTRL_KEY('L'):
4463 endwin();
4464 keypad(boardw, TRUE);
4465 wmove(stdscr, 0, 0);
4466 wclrtobot(stdscr);
4467 return 1;
4468 case KEY_ESCAPE:
4469 d->sp.icon = d->sp.srow = d->sp.scol = 0;
4470 markend = markstart = 0;
4472 if (keycount) {
4473 keycount = 0;
4474 update_status_notify(gp, NULL);
4477 if (config.validmoves)
4478 pgn_reset_valid_moves(d->b);
4480 return 1;
4481 case '0' ... '9':
4482 i = input_c - '0';
4484 if (keycount)
4485 keycount = keycount * 10 + i;
4486 else
4487 keycount = i;
4489 update_status_notify(gp, _("Repeat %i"), keycount);
4490 return -1;
4491 case KEY_UP:
4492 if (d->mode == MODE_HISTORY)
4493 return 0;
4495 if (keycount)
4496 d->c_row += keycount;
4497 else
4498 d->c_row++;
4500 if (d->c_row > 8)
4501 d->c_row = 1;
4503 return 1;
4504 case KEY_DOWN:
4505 if (d->mode == MODE_HISTORY)
4506 return 0;
4508 if (keycount) {
4509 d->c_row -= keycount;
4510 update_status_notify(gp, NULL);
4512 else
4513 d->c_row--;
4515 if (d->c_row < 1)
4516 d->c_row = 8;
4518 return 1;
4519 case KEY_LEFT:
4520 if (d->mode == MODE_HISTORY)
4521 return 0;
4523 if (keycount)
4524 d->c_col -= keycount;
4525 else
4526 d->c_col--;
4528 if (d->c_col < 1)
4529 d->c_col = 8;
4531 return 1;
4532 case KEY_RIGHT:
4533 if (d->mode == MODE_HISTORY)
4534 return 0;
4536 if (keycount)
4537 d->c_col += keycount;
4538 else
4539 d->c_col++;
4541 if (d->c_col > 8)
4542 d->c_col = 1;
4544 return 1;
4545 case KEY_RESIZE:
4546 return 1;
4547 case 0:
4548 default:
4549 for (i = 0; global_keys[i]; i++) {
4550 if (input_c == global_keys[i]->c) {
4551 (*global_keys[i]->f)();
4552 return 1;
4555 break;
4558 return 0;
4561 #ifdef WITH_LIBPERL
4562 static void perl_error(const char *fmt, ...)
4564 va_list ap;
4565 char *buf;
4567 va_start(ap, fmt);
4568 vasprintf(&buf, fmt, ap);
4569 va_end(ap);
4571 message(ERROR_STR, ANY_KEY_STR, "%s", buf);
4572 free(buf);
4575 static void do_perl_finalize(WIN *win)
4577 struct input_data_s *in = win->data;
4578 GAME g = in->data;
4579 struct userdata_s *d = g->data;
4580 char *filename;
4581 char *result = NULL;
4582 char *arg = NULL;
4583 int n;
4585 asprintf(&filename, "%s/perl.pl", config.datadir);
4587 if (!in->str)
4588 goto done;
4590 if (perl_init_file(filename, perl_error))
4591 goto done;
4593 arg = pgn_game_to_fen(g, d->b);
4595 if (perl_call_sub(trim(in->str), arg, &result))
4596 goto done;
4598 d->perlfen = pgn_game_to_fen(g, d->b);
4599 d->perlflags = g->flags;
4601 if (pgn_board_init_fen(g, d->b, result) != E_PGN_OK) {
4602 message(ERROR_STR, ANY_KEY_STR, "%s", _("FEN parse error."));
4603 pgn_board_init_fen(g, d->b, d->perlfen);
4604 g->flags = d->perlflags;
4605 free(d->perlfen);
4606 d->perlfen = NULL;
4607 goto done;
4610 SET_FLAG(d->flags, CF_PERL);
4611 n = pgn_tag_find(g->tag, "FEN");
4613 if (n != E_PGN_ERR)
4614 d->oldfen = strdup(g->tag[n]->value);
4616 pgn_tag_add(&g->tag, "FEN", result);
4617 update_status_notify(g, "%s", ANY_KEY_STR);
4618 update_all(g);
4620 done:
4621 free(result);
4622 free(arg);
4623 free(in->str);
4624 free(in);
4625 free(filename);
4628 void do_global_perl()
4630 struct input_data_s *in;
4632 in = Calloc(1, sizeof(struct input_data_s));
4633 in->data = gp;
4634 in->efunc = do_perl_finalize;
4635 construct_input(_("PERL Subroutine Filter"), NULL, 1, 0, NULL, NULL, NULL, 0, in, INPUT_HIST_PERL, -1);
4637 #endif
4640 * A macro may contain a key that belongs to another macro so macro_match will
4641 * need to be updated to the new index of the matching macro.
4643 static void find_macro(struct userdata_s *d)
4645 int i;
4648 * Macros can't contain macros when in a window.
4650 if (wins)
4651 return;
4653 again:
4654 for (i = 0; macros[i]; i++) {
4655 if ((macros[i]->mode == -1 || macros[i]->mode == d->mode) &&
4656 input_c == macros[i]->c) {
4657 input_c = macros[i]->keys[macros[i]->n++];
4659 if (!macro_depth_n && macro_match > -1) {
4660 macro_depth = realloc(macro_depth, (macro_depth_n + 1) * sizeof(int));
4661 macro_depth[macro_depth_n++] = macro_match;
4664 macro_depth = realloc(macro_depth, (macro_depth_n + 1) * sizeof(int));
4665 macro_depth[macro_depth_n++] = i;
4666 macro_match = i;
4667 goto again;
4673 * Resets the position in each macro to the first key.
4675 static void reset_macros()
4677 int i;
4678 struct userdata_s *d = gp->data;
4680 again:
4681 if (macro_depth_n > 0) {
4682 macro_depth_n--;
4683 macro_match = macro_depth[macro_depth_n];
4685 if (macros[macro_match]->n >= macros[macro_match]->total)
4686 goto again;
4688 input_c = macros[macro_match]->keys[macros[macro_match]->n++];
4689 find_macro(d);
4690 return;
4693 for (i = 0; macros[i]; i++)
4694 macros[i]->n = 0;
4696 free(macro_depth);
4697 macro_depth = NULL;
4698 macro_depth_n = 0;
4699 macro_match = -1;
4702 void game_loop()
4704 struct userdata_s *d;
4706 macro_match = -1;
4707 gindex = gtotal - 1;
4708 gp = game[gindex];
4709 d = gp->data;
4711 if (pgn_history_total(gp->hp))
4712 d->mode = MODE_HISTORY;
4713 else {
4714 d->mode = MODE_PLAY;
4715 d->play_mode = PLAY_HE;
4718 if (d->mode == MODE_HISTORY)
4719 pgn_board_update(gp, d->b, pgn_history_total(gp->hp));
4721 update_status_notify(gp, "%s", _("Type F1 for help"));
4722 movestep = 2;
4723 flushinp();
4724 update_all(gp);
4725 wtimeout(boardw, WINDOW_TIMEOUT);
4727 while (!quit) {
4728 int n = 0, i;
4729 char fdbuf[8192] = {0};
4730 int len;
4731 struct timeval tv = {0, 0};
4732 fd_set rfds, wfds;
4733 WIN *win = NULL;
4734 WINDOW *wp = NULL;
4736 FD_ZERO(&rfds);
4737 FD_ZERO(&wfds);
4739 for (i = 0; i < gtotal; i++) {
4740 d = game[i]->data;
4742 if (d->engine && d->engine->pid != -1) {
4743 if (d->engine->fd[ENGINE_IN_FD] > 2) {
4744 if (d->engine->fd[ENGINE_IN_FD] > n)
4745 n = d->engine->fd[ENGINE_IN_FD];
4747 FD_SET(d->engine->fd[ENGINE_IN_FD], &rfds);
4750 if (d->engine->fd[ENGINE_OUT_FD] > 2) {
4751 if (d->engine->fd[ENGINE_OUT_FD] > n)
4752 n = d->engine->fd[ENGINE_OUT_FD];
4754 FD_SET(d->engine->fd[ENGINE_OUT_FD], &wfds);
4759 if (n) {
4760 if ((n = select(n + 1, &rfds, &wfds, NULL, &tv)) > 0) {
4761 for (i = 0; i < gtotal; i++) {
4762 d = game[i]->data;
4764 if (d->engine && d->engine->pid != -1) {
4765 if (FD_ISSET(d->engine->fd[ENGINE_IN_FD], &rfds)) {
4766 len = read(d->engine->fd[ENGINE_IN_FD], fdbuf,
4767 sizeof(fdbuf));
4769 if (len > 0) {
4770 if (d->engine->iobuf)
4771 d->engine->iobuf = Realloc(d->engine->iobuf, d->engine->len + len + 1);
4772 else
4773 d->engine->iobuf = Calloc(1, len + 1);
4775 memcpy(&(d->engine->iobuf[d->engine->len]), &fdbuf, len);
4776 d->engine->len += len;
4777 d->engine->iobuf[d->engine->len] = 0;
4780 * The fdbuf is full or no newline
4781 * was found. So we'll append the next
4782 * read() to this games buffer.
4784 if (d->engine->iobuf[d->engine->len - 1] != '\n')
4785 continue;
4787 parse_engine_output(game[i], d->engine->iobuf);
4788 free(d->engine->iobuf);
4789 d->engine->iobuf = NULL;
4790 d->engine->len = 0;
4792 else if (len == -1) {
4793 if (errno != EAGAIN) {
4794 cmessage(ERROR_STR, ANY_KEY_STR, "Engine read(): %s",
4795 strerror(errno));
4796 waitpid(d->engine->pid, &n, 0);
4797 free(d->engine);
4798 d->engine = NULL;
4799 break;
4804 if (FD_ISSET(d->engine->fd[ENGINE_OUT_FD], &wfds)) {
4805 if (d->engine->queue)
4806 send_engine_command(game[i]);
4811 else {
4812 if (n == -1)
4813 cmessage(ERROR_STR, ANY_KEY_STR, "select(): %s", strerror(errno));
4814 /* timeout */
4818 gp = game[gindex];
4819 d = gp->data;
4822 * This is needed to detect terminal resizing.
4824 doupdate();
4825 if (LINES != LINES_OLD || COLS != COLS_OLD) {
4826 COLS_OLD = COLS;
4827 LINES_OLD = LINES;
4828 do_window_resize();
4832 * Finds the top level window in the window stack so we know what
4833 * window the wget_wch()'ed key belongs to.
4835 if (wins) {
4836 for (i = 0; wins[i]; i++);
4837 win = wins[i-1];
4838 wp = win->w;
4839 wtimeout(wp, WINDOW_TIMEOUT);
4841 else
4842 wp = boardw;
4844 if (!i && pushkey)
4845 input_c = pushkey;
4846 else {
4847 if (!pushkey) {
4848 if (macros && macro_match >= 0) {
4849 if (macros[macro_match]->n >= macros[macro_match]->total)
4850 reset_macros();
4851 else {
4852 input_c = macros[macro_match]->keys[macros[macro_match]->n++];
4853 find_macro(d);
4856 else {
4857 if (wget_wch(wp, &input_c) == ERR || input_c == KEY_RESIZE)
4858 continue;
4861 else
4862 input_c = pushkey;
4864 if (win) {
4865 switch (input_c) {
4866 case CTRL_KEY('L'):
4867 endwin();
4868 keypad(boardw, TRUE);
4869 wmove(stdscr, 0, 0);
4870 wclrtobot(stdscr);
4871 goto refresh;
4874 win->c = input_c;
4877 * Run the function associated with the window. When the
4878 * function returns 0 win->efunc is ran (if not NULL) with
4879 * win as the one and only parameter. Then the window is
4880 * destroyed.
4882 * The exit function may create another window which will
4883 * mess up the window stack when window_destroy() is called.
4884 * So don't destory the window until the top window is
4885 * destroyable. See window_destroy().
4887 if ((*win->func)(win) == 0) {
4888 if (win->efunc)
4889 (*win->efunc)(win);
4891 win->keep = 1;
4892 window_destroy(win);
4893 update_all(gp);
4896 continue;
4900 if (!keycount && status.notify)
4901 update_status_notify(gp, NULL);
4903 #ifdef WITH_LIBPERL
4904 if (TEST_FLAG(d->flags, CF_PERL)) {
4905 CLEAR_FLAG(d->flags, CF_PERL);
4906 pgn_board_init_fen(gp, d->b, d->perlfen);
4907 gp->flags = d->perlflags;
4908 free(d->perlfen);
4909 pgn_tag_add(&gp->tag, "FEN", d->oldfen);
4910 free(d->oldfen);
4911 d->perlfen = d->oldfen = NULL;
4912 update_all(gp);
4913 continue;
4915 #endif
4917 if (macros && macro_match < 0)
4918 find_macro(d);
4920 if ((n = globalkeys()) == 1) {
4921 if (macro_match == -1)
4922 keycount = 0;
4924 goto refresh;
4926 else if (n == -1)
4927 goto refresh;
4929 switch (d->mode) {
4930 case MODE_EDIT:
4931 for (i = 0; edit_keys[i]; i++) {
4932 if (input_c == edit_keys[i]->c) {
4933 (*edit_keys[i]->f)();
4934 break;
4937 break;
4938 case MODE_PLAY:
4939 for (i = 0; play_keys[i]; i++) {
4940 if (input_c == play_keys[i]->c) {
4941 (*play_keys[i]->f)();
4942 goto done;
4946 do_play_config_command();
4947 break;
4948 case MODE_HISTORY:
4949 for (i = 0; history_keys[i]; i++) {
4950 if (input_c == history_keys[i]->c) {
4951 (*history_keys[i]->f)();
4952 break;
4955 break;
4956 default:
4957 break;
4960 done:
4961 if (keycount)
4962 update_status_notify(gp, NULL);
4964 keycount = 0;
4966 refresh:
4967 update_all(gp);
4971 void usage(const char *pn, int ret)
4973 fprintf((ret) ? stderr : stdout, "%s", _(
4974 #ifdef DEBUG
4975 "Usage: cboard [-hvCD] [-u [N]] [-p [-VtRSE] <file>]\n"
4976 " -D Dump libchess debugging info to \"libchess.debug\" (stderr)\n"
4977 #else
4978 "Usage: cboard [-hvC] [-u [N]] [-p [-VtRSE] <file>]\n"
4979 #endif
4980 " -p Load PGN file.\n"
4981 " -V Validate a game file.\n"
4982 " -S Validate and output a PGN formatted game.\n"
4983 " -R Like -S but write a reduced PGN formatted game.\n"
4984 " -t Also write custom PGN tags from config file.\n"
4985 " -E Stop processing on file parsing error (overrides config).\n"
4986 " -C Enable strict castling (overrides config).\n"
4987 " -u Enable/disable UTF-8 pieces (1=enable, 0=disable, moverrides config).\n"
4988 " -v Version information.\n"
4989 " -h This help text.\n"));
4991 exit(ret);
4994 void cleanup_all()
4996 int i;
4998 stop_clock();
4999 free_userdata();
5000 pgn_free_all();
5001 free(config.engine_cmd);
5002 free(config.pattern);
5003 free(config.ccfile);
5004 free(config.nagfile);
5005 free(config.configfile);
5007 if (config.keys) {
5008 for (i = 0; config.keys[i]; i++) {
5009 free(config.keys[i]->str);
5010 free(config.keys[i]);
5013 free(config.keys);
5016 if (config.einit) {
5017 for (i = 0; config.einit[i]; i++)
5018 free(config.einit[i]);
5020 free(config.einit);
5023 if (config.tag)
5024 pgn_tag_free(config.tag);
5026 free(config.datadir);
5028 if (curses_initialized) {
5029 del_panel(boardp);
5030 del_panel(historyp);
5031 del_panel(statusp);
5032 del_panel(tagp);
5033 delwin(boardw);
5034 delwin(historyw);
5035 delwin(statusw);
5036 delwin(tagw);
5038 if (enginew) {
5039 del_panel(enginep);
5040 delwin(enginew);
5043 endwin();
5046 #ifdef WITH_LIBPERL
5047 perl_cleanup();
5048 #endif
5051 static void signal_save_pgn(int sig)
5053 char *buf;
5054 time_t now;
5055 char *p = config.savedirectory ? config.savedirectory : config.datadir;
5057 time(&now);
5058 asprintf(&buf, "%s/signal-%i-%li.pgn", p, sig, now);
5060 if (do_game_write(buf, "w", 0, gtotal)) {
5061 cmessage(ERROR_STR, ANY_KEY_STR, "%s: %s", p, strerror(errno));
5062 update_status_notify(gp, "%s", _("Save game failed."));
5065 free(buf);
5066 quit = 1;
5069 void catch_signal(int which)
5071 switch (which) {
5072 case SIGALRM:
5073 update_clocks();
5074 break;
5075 case SIGPIPE:
5076 if (which == SIGPIPE && quit)
5077 break;
5079 if (which == SIGPIPE)
5080 cmessage(NULL, ANY_KEY_STR, "%s", _("Broken pipe. Quitting."));
5082 cleanup_all();
5083 exit(EXIT_FAILURE);
5084 break;
5085 case SIGSTOP:
5086 savetty();
5087 break;
5088 case SIGCONT:
5089 resetty();
5090 keypad(boardw, TRUE);
5091 curs_set(0);
5092 cbreak();
5093 noecho();
5094 break;
5095 case SIGINT:
5096 quit = 1;
5097 break;
5098 case SIGTERM:
5099 signal_save_pgn(which);
5100 break;
5101 default:
5102 break;
5106 void loading_progress(long total, long offset)
5108 int n = (100 * (offset / 100) / (total / 100));
5110 if (curses_initialized)
5111 update_loading_window(n);
5112 else {
5113 fprintf(stderr, _("Loading... %i%% (%i games)%c"), n, gtotal, '\r');
5114 fflush(stderr);
5118 static void set_defaults()
5120 set_config_defaults();
5121 set_default_keys();
5122 filetype = FILE_NONE;
5123 pgn_config_set(PGN_PROGRESS, 1024);
5124 pgn_config_set(PGN_PROGRESS_FUNC, loading_progress);
5127 int main(int argc, char *argv[])
5129 int opt;
5130 struct stat st;
5131 char buf[FILENAME_MAX];
5132 char datadir[FILENAME_MAX];
5133 int ret = EXIT_SUCCESS;
5134 int validate_only = 0, validate_and_write = 0;
5135 int write_custom_tags = 0;
5136 int i = 0;
5137 PGN_FILE *pgn;
5138 int utf8_pieces = -1;
5140 setlocale (LC_ALL, "");
5141 bindtextdomain ("cboard", LOCALE_DIR);
5142 textdomain ("cboard");
5144 /* Solaris 5.9 */
5145 #ifndef HAVE_PROGNAME
5146 __progname = argv[0];
5147 #endif
5149 if ((config.pwd = getpwuid(getuid())) == NULL)
5150 err(EXIT_FAILURE, "getpwuid()");
5152 snprintf(datadir, sizeof(datadir), "%s/.cboard", config.pwd->pw_dir);
5153 config.datadir = strdup(datadir);
5154 snprintf(buf, sizeof(buf), "%s/cc.data", datadir);
5155 config.ccfile = strdup(buf);
5156 snprintf(buf, sizeof(buf), "%s/nag.data", datadir);
5157 config.nagfile = strdup(buf);
5158 snprintf(buf, sizeof(buf), "%s/config", datadir);
5159 config.configfile = strdup(buf);
5161 if (stat(datadir, &st) == -1) {
5162 if (errno == ENOENT) {
5163 if (mkdir(datadir, 0755) == -1)
5164 err(EXIT_FAILURE, "%s", datadir);
5166 else
5167 err(EXIT_FAILURE, "%s", datadir);
5169 stat(datadir, &st);
5172 if (!S_ISDIR(st.st_mode))
5173 errx(EXIT_FAILURE, "%s: %s", datadir, _("Not a directory."));
5175 set_defaults();
5177 #ifdef DEBUG
5178 while ((opt = getopt(argc, argv, "DCEVtSRhp:vu::")) != -1) {
5179 #else
5180 while ((opt = getopt(argc, argv, "ECVtSRhp:vu::")) != -1) {
5181 #endif
5182 switch (opt) {
5183 #ifdef DEBUG
5184 case 'D':
5185 unlink("libchess.debug");
5186 pgn_config_set(PGN_DEBUG, 1);
5187 break;
5188 #endif
5189 case 'C':
5190 pgn_config_set(PGN_STRICT_CASTLING, 1);
5191 break;
5192 case 't':
5193 write_custom_tags = 1;
5194 break;
5195 case 'E':
5196 i = 1;
5197 break;
5198 case 'R':
5199 pgn_config_set(PGN_REDUCED, 1);
5200 case 'S':
5201 validate_and_write = 1;
5202 case 'V':
5203 validate_only = 1;
5204 break;
5205 case 'v':
5206 printf("%s (%s)\n%s\n", PACKAGE_STRING, curses_version(),
5207 COPYRIGHT);
5208 exit(EXIT_SUCCESS);
5209 case 'p':
5210 filetype = FILE_PGN;
5211 strncpy(loadfile, optarg, sizeof(loadfile));
5212 loadfile[sizeof(loadfile)-1] = 0;
5213 break;
5214 case 'u':
5215 utf8_pieces = optarg ? atoi (optarg): 1;
5216 break;
5217 case 'h':
5218 default:
5219 usage(argv[0], EXIT_SUCCESS);
5223 if ((validate_only || validate_and_write) && !*loadfile)
5224 usage(argv[0], EXIT_FAILURE);
5226 if (access(config.configfile, R_OK) == 0)
5227 parse_rcfile(config.configfile);
5229 if (i)
5230 pgn_config_set(PGN_STOP_ON_ERROR, 1);
5232 signal(SIGPIPE, catch_signal);
5233 signal(SIGCONT, catch_signal);
5234 signal(SIGSTOP, catch_signal);
5235 signal(SIGINT, catch_signal);
5236 signal(SIGALRM, catch_signal);
5237 signal(SIGTERM, catch_signal);
5239 srandom(getpid());
5241 switch (filetype) {
5242 case FILE_PGN:
5243 if (pgn_open(loadfile, "r", &pgn) != E_PGN_OK)
5244 err(EXIT_FAILURE, "%s", loadfile);
5246 ret = pgn_parse(pgn);
5247 pgn_close(pgn);
5248 break;
5249 case FILE_FEN:
5250 //ret = parse_fen_file(loadfile);
5251 break;
5252 case FILE_EPD: // Not implemented.
5253 case FILE_NONE:
5254 default:
5255 // No file specified. Empty game.
5256 ret = pgn_parse(NULL);
5257 gp = game[gindex];
5258 add_custom_tags(&gp->tag);
5259 break;
5262 if (validate_only || validate_and_write) {
5263 if (validate_and_write) {
5264 if (pgn_open("-", "r", &pgn) != E_PGN_OK)
5265 err(EXIT_FAILURE, "pgn_open()");
5267 for (i = 0; i < gtotal; i++) {
5268 if (write_custom_tags)
5269 add_custom_tags(&game[i]->tag);
5271 pgn_write(pgn, game[i]);
5274 pgn_close(pgn);
5276 fm_loaded_file = TRUE;
5279 cleanup_all();
5280 exit(ret);
5282 else if (ret == E_PGN_ERR)
5283 exit(ret);
5285 if (utf8_pieces != -1)
5286 config.utf8_pieces = utf8_pieces;
5288 init_wchar_pieces ();
5289 yes_wchar = str_to_wchar (_("y"));
5290 all_wchar = str_to_wchar (_("a"));
5291 overwrite_wchar = str_to_wchar (_("o"));
5292 resume_wchar = str_to_wchar (_("r"));
5293 current_wchar = str_to_wchar (_("c"));
5294 append_wchar = str_to_wchar (_("a"));
5295 translatable_tag_names[0] = _("Event");
5296 translatable_tag_names[1] = _("Site");
5297 translatable_tag_names[2] = _("Date");
5298 translatable_tag_names[3] = _("Round");
5299 translatable_tag_names[4] = _("White");
5300 translatable_tag_names[5] = _("Black");
5301 translatable_tag_names[6] = _("Result");
5302 init_userdata();
5305 * This fixes window resizing in an xterm.
5307 if (getenv("DISPLAY") != NULL) {
5308 putenv("LINES=");
5309 putenv("COLUMNS=");
5312 if (initscr() == NULL)
5313 errx(EXIT_FAILURE, "%s", _("Could not initialize curses."));
5314 else
5315 curses_initialized = 1;
5317 if (LINES < 23 || COLS < 74) {
5318 endwin();
5319 errx(EXIT_FAILURE, _("Need at least an 74x23 terminal."));
5322 COLS_OLD = COLS;
5323 LINES_OLD = LINES;
5325 if (has_colors() == TRUE && start_color() == OK)
5326 init_color_pairs();
5328 boardw = newwin(BOARD_HEIGHT, BOARD_WIDTH, 0, COLS - BOARD_WIDTH);
5329 boardp = new_panel(boardw);
5330 historyw = newwin(HISTORY_HEIGHT, HISTORY_WIDTH, LINES - HISTORY_HEIGHT,
5331 COLS - HISTORY_WIDTH);
5332 historyp = new_panel(historyw);
5333 statusw = newwin(STATUS_HEIGHT, STATUS_WIDTH, 0, 0);
5334 statusp = new_panel(statusw);
5335 tagw = newwin(TAG_HEIGHT, TAG_WIDTH, STATUS_HEIGHT + 1, 0);
5336 tagp = new_panel(tagw);
5337 keypad(boardw, TRUE);
5338 // leaveok(boardw, TRUE);
5339 leaveok(tagw, TRUE);
5340 leaveok(statusw, TRUE);
5341 leaveok(historyw, TRUE);
5342 curs_set(0);
5343 cbreak();
5344 noecho();
5345 draw_window_decor();
5346 game_loop();
5347 cleanup_all();
5348 free (w_pawn_wchar);
5349 free (w_rook_wchar);
5350 free (w_bishop_wchar);
5351 free (w_knight_wchar);
5352 free (w_queen_wchar);
5353 free (w_king_wchar);
5354 free (b_pawn_wchar);
5355 free (b_rook_wchar);
5356 free (b_bishop_wchar);
5357 free (b_knight_wchar);
5358 free (b_queen_wchar);
5359 free (b_king_wchar);
5360 free (empty_wchar);
5361 free (enpassant_wchar);
5362 free (yes_wchar);
5363 free (all_wchar);
5364 free (overwrite_wchar);
5365 free (resume_wchar);
5366 free (current_wchar);
5367 free (append_wchar);
5368 exit(EXIT_SUCCESS);