File: dialogs.c

package info (click to toggle)
shogivar 1.55b-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, trixie
  • size: 6,268 kB
  • sloc: ansic: 10,375; sh: 4,109; makefile: 613
file content (1155 lines) | stat: -rw-r--r-- 31,530 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
/*
 * dialogs.c -- platform-independent code for dialogs of XBoard
 *
 * Copyright 2000, 2009, 2010, 2011, 2012, 2013, 2014 Free Software Foundation, Inc.
 * ------------------------------------------------------------------------
 *
 * GNU XBoard is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or (at
 * your option) any later version.
 *
 * GNU XBoard is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses/.  *
 *
 *------------------------------------------------------------------------
 ** See the file ChangeLog for a revision history.  */

// [HGM] this file is the counterpart of woptions.c, containing xboard popup menus
// similar to those of WinBoard, to set the most common options interactively.

#include "config.h"

#include <stdio.h>
#include <ctype.h>
#include <errno.h>
#include <sys/types.h>

#if STDC_HEADERS
# include <stdlib.h>
# include <string.h>
#else /* not STDC_HEADERS */
extern char *getenv();
# if HAVE_STRING_H
#  include <string.h>
# else /* not HAVE_STRING_H */
#  include <strings.h>
# endif /* not HAVE_STRING_H */
#endif /* not STDC_HEADERS */

#if HAVE_UNISTD_H
# include <unistd.h>
#endif
#include <stdint.h>

#include "common.h"
#include "backend.h"
#include "frontend.h"
#include "menus.h"
#include "dialogs.h"
#include "draw.h"
#include "gettext.h"

#ifdef ENABLE_NLS
# define  _(s) gettext (s)
# define N_(s) gettext_noop (s)
#else
# define  _(s) (s)
# define N_(s)  s
#endif

#define FALSE 0
#define TRUE 1
#define TOPLEVEL 1 /* preference item; 1 = make popup windows toplevel */

int values[MAX_OPTIONS];
int *currentCps;

// FIXME: dummies to prevent compile errors
int lineGap, squareSize;

//----------------------------Generic dialog --------------------------------------------

// cloned from Engine Settings dialog (and later merged with it)

char *marked[NrOfDialogs];
Boolean shellUp[NrOfDialogs];

void
MarkMenu (char *item, int dlgNr)
{
    MarkMenuItem(marked[dlgNr] = item, True);
}

void
AddLine (Option *opt, char *s)
{
    AppendText(opt, s);
    AppendText(opt, "\n");
}

//---------------------------------------------- Update dialog controls ------------------------------------

int
SetCurrentComboSelection (Option *opt)
{
    int j;
    if(!opt->textValue) opt->value = *(int*)opt->target; /* numeric */else {
	for(j=0; opt->choice[j]; j++) // look up actual value in list of possible values, to get selection nr
	    if(*(char**)opt->target && !strcmp(*(char**)opt->target, ((char**)opt->textValue)[j])) break;
	opt->value = j + (opt->choice[j] == NULL);
    }
    return opt->value;
}

void
GenericUpdate (Option *opts, int selected)
{
    int i;
    char buf[MSG_SIZ];

    for(i=0; ; i++)
      {
	if(selected >= 0) { if(i < selected) continue; else if(i > selected) break; }
	switch(opts[i].type)
	  {
	  case TextBox:
	  case FileName:
	  case PathName:
	    SetWidgetText(&opts[i],  *(char**) opts[i].target, -1);
	    break;
	  case Spin:
	    sprintf(buf, "%d", *(int*) opts[i].target);
	    SetWidgetText(&opts[i], buf, -1);
	    break;
	  case Fractional:
	    sprintf(buf, "%4.2f", *(float*) opts[i].target);
	    SetWidgetText(&opts[i], buf, -1);
	    break;
	  case CheckBox:
	    SetWidgetState(&opts[i],  *(Boolean*) opts[i].target);
	    break;
	  case ComboBox:
	    if(opts[i].min & COMBO_CALLBACK) break;
	    SetCurrentComboSelection(opts+i);
	    // TODO: actually display this (but it is never used that way...)
	    break;
	  case EndMark:
	    return;
	  default:
	    printf("GenericUpdate: unexpected case in switch.\n");
	  case ListBox:
	  case Button:
	  case SaveButton:
	  case Label:
	  case Graph:
	  case Skip:
	  case Icon:
	  case Break:
	    break;
	  }
      }
}

//------------------------------------------- Read out dialog controls ------------------------------------

int
GenericReadout (Option *opts, int selected)
{
    int i, j, res=1;
    char *val;
    char **dest;
    float x;
	for(i=0; ; i++) { // send all options that had to be OK-ed to engine
	    if(selected >= 0) { if(i < selected) continue; else if(i > selected) break; }
	    switch(opts[i].type) {
		case TextBox:
		case FileName:
		case PathName:
		    GetWidgetText(&opts[i], &val);
		    dest = currentCps ? &(opts[i].textValue) : (char**) opts[i].target;
		    if(*dest == NULL || strcmp(*dest, val)) {
			if(*dest) free(*dest);
			*dest = malloc(strlen(val)+1);
			strncpy(*dest, val, MSG_SIZ - (*dest - opts[i].name) - 1); // copy text there
		    }
		    break;
		case Spin:
		case Fractional:
		    GetWidgetText(&opts[i], &val);
		    x = 0.0; // Initialise because sscanf() will fail if non-numeric text is entered
		    sscanf(val, "%f", &x);
		    if(x > opts[i].max) x = opts[i].max;
		    if(x < opts[i].min) x = opts[i].min;
		    if(opts[i].type == Fractional)
			*(float*) opts[i].target = x;
		    else {
			*(int*) opts[i].target = x;
			opts[i].value = x;
		    }
		    break;
		case CheckBox:
		    j = 0;
		    GetWidgetState(&opts[i], &j);
		    if(opts[i].value != j) {
			opts[i].value = j;
		    }
		    break;
		case ComboBox:
		    if(opts[i].min & COMBO_CALLBACK) break;
		    if(!opts[i].textValue) { *(int*)opts[i].target = values[i]; break; } // numeric
		    val = ((char**)opts[i].textValue)[values[i]];
		    if(val && (*(char**) opts[i].target == NULL || strcmp(*(char**) opts[i].target, val))) {
		      if(*(char**) opts[i].target) free(*(char**) opts[i].target);
		      *(char**) opts[i].target = strdup(val);
		    }
		    break;
		case EndMark:
		    if(opts[i].target && selected != -2) // callback for implementing necessary actions on OK (like redraw)
			res = ((OKCallback*) opts[i].target)(i);
		    break;
	    default:
		printf("GenericReadout: unexpected case in switch.\n");
		case ListBox:
		case Button:
		case SaveButton:
		case Label:
		case Break:
		case Skip:
		case Graph:
		case Icon:
	      break;
	    }
	    if(opts[i].type == EndMark) break;
	}
	return res;
}

//------------------------------------------------------ Edit Tags ----------------------------------

static char *tagsText, **resPtr, *general;

static int TagsClick(Option *opt, int n, int x, int y, char *val, int index);
static Option *ExpTags(int n, int x, int y);

static int
NewTagsCallback (int n)
{
    if(resPtr) { ASSIGN(*resPtr, tagsText); }
    return 1;
}

static void
TagButton (int n)
{
    PopDown(TagsDlg);
    if(n == 4) LoadPieceHelp();
}

static Option tagsOptions[] = {
{  59,         FIX_H, 59, NULL, (void*) &ExpTags, NULL, NULL, Graph,  "" },
{  33,SAME_ROW|FIX_H,266, NULL, (void*) &ExpTags, NULL, NULL, Graph,  "" },
{  59,SAME_ROW|FIX_H, 59, NULL, (void*) &ExpTags, NULL, NULL, Graph,  "" },
{ 400, T_VSCRL | T_FILL | T_WRAP | T_TOP, 595, NULL, (void*) &tagsText, "", (char **) &TagsClick, TextBox, "" },
{   1,   0,   100, NULL, (void*) &TagButton, NULL, NULL, Button, N_("Piece Help") },
{ 2,SAME_ROW, 100, NULL, (void*) &TagButton, NULL, NULL, Button, N_("Print") },
{ 3,SAME_ROW, 100, NULL, (void*) &TagButton, NULL, NULL, Button, N_("Exit") },
{ 0,  NO_OK,   40, NULL, (void*) &NewTagsCallback, "", (char**) "#008080", EndMark , "" }
};

static Option *
ExpTags (int n, int x, int y)
{
    char buf[MSG_SIZ];
    if(n == 10) {
	snprintf(buf, MSG_SIZ, DATADIR "/titles/%sTit.png", general ? general : Choice);
	DrawLogo(&tagsOptions[1], buf);
	snprintf(buf, MSG_SIZ, DATADIR "/titles/Piece.png");
	DrawLogo(&tagsOptions[2], buf);
	DrawLogo(&tagsOptions[0], buf);
    }
    return NULL;
}

static int TagsClick (Option *opt, int n, int x, int y, char *val, int index)
{
//    PlayBookMove(val, index);
    return TRUE;
}

void
NewTagsPopup (char *text, char *msg)
{
    char *title = "Rules Help";
    if(DialogExists(TagsDlg)) { // if already exists, alter title and content
	SetWidgetText(&tagsOptions[3], text, TagsDlg);
//	SetDialogTitle(TagsDlg, title);
    }
    if(tagsText) free(tagsText); tagsText = strdup(text);
//    MarkMenu("View.Tags", TagsDlg);
    GenericPopUp(tagsOptions, title, TagsDlg, BoardDlg, NONMODAL, TOPLEVEL);
    ExpTags(10, 0, 0);
}

void
TagsPopUp (char *tags, char *msg)
{
    general = msg;
    NewTagsPopup(tags, NULL);
}

void
EditTagsPopUp (char *tags, char **dest)
{   // wrapper to preserve old name used in back-end
    resPtr = dest; 
    NewTagsPopup(tags, NULL);
}

void
UnloadRulesHelp()
{
    PopDown(TagsDlg);
}

//----------------------------- Error popup in various uses -----------------------------

/*
 * [HGM] Note:
 * XBoard has always had some pathologic behavior with multiple simultaneous error popups,
 * (which can occur even for modal popups when asynchrounous events, e.g. caused by engine, request a popup),
 * and this new implementation reproduces that as well:
 * Only the shell of the last instance is remembered in shells[ErrorDlg] (which replaces errorShell),
 * so that PopDowns ordered from the code always refer to that instance, and once that is down,
 * have no clue as to how to reach the others. For the Delete Window button calling PopDown this
 * has now been repaired, as the action routine assigned to it gets the shell passed as argument.
 */

int errorUp = False;

void
ErrorPopDown ()
{
    if (!errorUp) return;
    dialogError = errorUp = False;
    PopDown(ErrorDlg); PopDown(FatalDlg); // on explicit request we pop down any error dialog
//    if (errorExitStatus != -1) ExitEvent(errorExitStatus);
}

static int
ErrorOK (int n)
{
    dialogError = errorUp = False;
    PopDown(n == 1 ? FatalDlg : ErrorDlg); // kludge: non-modal dialogs have one less (dummy) option
//    if (errorExitStatus != -1) ExitEvent(errorExitStatus);
    return FALSE; // prevent second Popdown !
}

static Option errorOptions[] = {
{   0,  0,    0, NULL, NULL, NULL, NULL, Label,  NULL }, // dummy option: will never be displayed
{   0,  0,    0, NULL, NULL, NULL, NULL, Label,  NULL }, // textValue field will be set before popup
{ 0,NO_CANCEL,0, NULL, (void*) &ErrorOK, "", NULL, EndMark , "" }
};

void
ErrorPopUp (char *title, char *label, int modal)
{
    errorUp = True;
    errorOptions[1].name = label;
    if(dialogError = shellUp[TransientDlg])
	GenericPopUp(errorOptions+1, title, FatalDlg, TransientDlg, MODAL, 0); // pop up as daughter of the transient dialog
    else
	GenericPopUp(errorOptions+modal, title, modal ? FatalDlg: ErrorDlg, BoardDlg, modal, 0); // kludge: option start address indicates modality
}

void
DisplayError (char *message, int error)
{
    ErrorPopUp(_("Error"), message, FALSE);
}



void
DisplayFatalError (char *message, int error, int status)
{
    if(mainOptions[W_BOARD].handle) {
	    ErrorPopUp(status ? _("Fatal Error") : _("Exiting"), message, TRUE);
    }
}

void
DisplayInformation (char *message)
{
    ErrorPopDown();
    ErrorPopUp(_("Information"), message, TRUE);
}

void
DisplayNote (char *message)
{
    ErrorPopDown();
    ErrorPopUp(_("Note"), message, FALSE);
}

//-------------------------------- About Box --------------------------------------

static Option *ExpAbout(int n, int x, int y);

static Option aboutOptions[] = {
{ 201, L2L|T2T, 321,NULL, (char*) &ExpAbout, NULL, NULL, Graph, "logo" }, // image
{ 0,  NO_OK, 0, NULL, NULL, "", NULL, EndMark , "" }
};

static Option *
ExpAbout (int n, int x, int y)
{
    if(n == 10) {
	DrawLogo(&aboutOptions[0], DATADIR "/titles/About.png");
    }
    return NULL;
}

void
AboutProc()
{
    GenericPopUp(aboutOptions, "About", TransientDlg, BoardDlg, MODAL, 0);
    ExpAbout(10, 0, 0);
}

//------------------------------- Piece Help dialog --------------------------------

static int helpNr;
static char helpFile[MSG_SIZ];

static Option *ExpHelp(int n, int x, int y);
static void MoreClick(int n);

void
ExitClick (int n)
{
    PopDown(PieceDlg);
}

void
RulesClick (int n)
{
    PopDown(PieceDlg);
    SetRules();
}

static Option pieceOptions[] = {
{ 480, L2L|T2T, 640,NULL, (char*) &ExpHelp, NULL, NULL, Graph, "logo" }, // image
{ 0, SAME_ROW, 0, NULL, NULL, NULL, NULL, Break, "" },
{ 1,    0,    60, NULL, (void*) &MoreClick, NULL, NULL, Button, N_("More") },
{ 2,    0,    60, NULL, (void*) &RulesClick, NULL, NULL, Button, N_("Rules") },
{ 3,    0,    60, NULL, (void*) &ExitClick, NULL, NULL, Button, N_("Exit") },
{ 0,  NO_OK, 0, NULL, NULL, "", NULL, EndMark , "" }
};

static void
MoreClick (int n)
{
    FILE *f;
    snprintf(helpFile, MSG_SIZ, DATADIR "/help/%sHelp%d.png", Choice, 3 - helpNr);
    if((f = fopen(helpFile, "r"))) {
	fclose(f);
        helpNr = 3 - helpNr; // toggle between 1 and 2
	DrawLogo(&pieceOptions[0], helpFile);
    }
}

static Option *
ExpHelp (int n, int x, int y)
{
    if(n == 10) {
	snprintf(helpFile, MSG_SIZ, DATADIR "/help/%sHelp%d.png", Choice, helpNr);
	DrawLogo(&pieceOptions[0], helpFile);
    }
    return NULL;
}

void
LoadPieceHelp ()
{
    helpNr = 1;
    GenericPopUp(pieceOptions, "Piece Help", PieceDlg, BoardDlg, NONMODAL, 0);
    ExpHelp(10, 0, 0);
}

void
UnloadPieceHelp ()
{
    PopDown(PieceDlg);
}

//-------------------------------- AddPieces dialog --------------------------------

static char *pieceList[NPIECES];

static void AddClick(int n);
static void AddExit(void);
static Option *ExpAdd(int n, int x, int y);

static void
CancelClick (int n)
{
    AddExit();
    PopDown(HistoryDlg);
    UpdateCaptions();
}

static Option addOptions[] = {
{  50,  FIX_H, 283, NULL, (void*) &ExpAdd, NULL, NULL, Graph,  "" },
{ 400,  LR,      0, NULL, (void*) pieceList, (char*) &AddClick, NULL, ListBox, "" }, // list of pieces
{ 1,    0,     100, NULL, (void*) &AddClick, NULL, NULL, Button, N_("Add Piece") },
{ 2, SAME_ROW, 100, NULL, (void*) &CancelClick, NULL, NULL, Button, N_("Cancel") },
{ 0,  NO_OK, 0, NULL, NULL, "", NULL, EndMark , "" }
};

static Option *
ExpAdd (int n, int x, int y)
{
    if(n == 10) {
	DrawLogo(&addOptions[0], DATADIR "/titles/AddBanner.png");
    }
    return NULL;
}

static void
AddClick (int n)
{
    Selection = SelectedListBoxItem(&addOptions[1]) + 1;
    if(Selection > 0) AddSomePieces();
    UpdateCaptions();
    DrawBoard();
}

static void
AddExit ()
{
    I = SelectedListBoxItem(&addOptions[1]);
    if(Drop == 1) ResetHand();
    Selection = 0; Reduce = 0; MovePiece = 0;
    if(!Board.Timer1.Enabled) StartClockTimer(1000);
    Board.Timer1.Enabled = True;
    MoveCount = 0; TurnCount = 0; strcpy(ExtraPiece, "");
    if(!strcmp(Turn, "White") ) MoveCount = 1;
    strcpy(Board.LastMove.Caption, "");
    UpdateCaptions();
}

void
LoadAddPieces ()
{
    STRING ASTR, Newt;
    INT L;
    for(L = 1; L <= PieceNum / 2; L++) {
	sprintf(ASTR, "%s %s", ExtraPiece, Pieces[L].Name);
	sprintf(Newt, "%-30s %-5s %6d", ASTR, Pieces[L].sname, Pieces[L].number);
	ASSIGN(pieceList[L-1], Newt);
    }
    pieceList[L] = NULL;
//    if(NewPiece.ListIndex == -1 ) AddPiece.Enabled = False; FIXME
//    AddPieces.Visible = True;
    GenericPopUp(addOptions, "Add Pieces", HistoryDlg, BoardDlg, NONMODAL, 1);
    LoadListBox(&addOptions[1], _("No Pieces"), -1, -1);
    ExpAdd(10, 0, 0);
}

void
UnloadAddPieces()
{
//    AddExit();
    PopDown(HistoryDlg);
}

//----------------------------------- Startup dialog -------------------------------------

static Option *ExpLogo(int n, int x, int y);
static Option *ExpSamurai(int n, int x, int y);

char *choice;

static char *variantList[] = {
	N_("-------- Modern Games --------"),
	N_("Micro Shogi (4x5)"),
	N_("Mini Shogi (5x5)"),
	N_("Judkins Shogi (6x6)"),
	N_("Whale Shogi (6x6)"),
	N_("Yari Shogi (7x9)"),
	N_("Modern Shogi (9x9)"),
	N_("-------- 1200-1800 AD --------"),
	N_("Tori Shogi (7x7)"),
	N_("Sho Shogi (9x9)"),
	N_("Wa Shogi (11x11)"),
	N_("Chu Shogi (12x12)"),
	N_("Dai Shogi (15x15)"),
	N_("Tenjiku Shogi (16x16)"),
	N_("Dai Dai Shogi (17x17)"),
	N_("Maka Dai Dai Shogi (19x19)"),
	N_("Tai Shogi (25x25)"),
	N_("--------- 800-1200 AD --------"),
	N_("Heian Shogi (9x8)"),
	N_("Heian Dai Shogi (13x13)"),
	NULL
};

static char *variantNames[] = { // sound files corresponding to above names
	"",
	"Micro",
	"Mini",
	"Judkin",
	"Whale",
	"Yari",
	"Shogi",
	"",
	"Tori",
	"Sho",
	"Wa",
	"Chu",
	"Dai",
	"Tenjiku",
	"DaiDai",
	"Maka",
	"Tai",
	"",
	"HShogi",
	"Heian",
	NULL
};

typedef struct { int x, y; } Point;
static Point windowSize[] = {
	{ 0, 0 },
	{ 640, 469 },
	{ 640, 469 },
	{ 640, 469 },
	{ 640, 469 },
	{ 640, 469 },
	{ 640, 469 },
	{ 0, 0 },
	{ 640, 469 },
	{ 640, 469 },
	{ 639, 469 },
	{ 640, 470 },
	{ 640, 470 },
	{ 640, 470 },
	{ 639, 469 },
	{ 639, 469 },
	{ 799, 600 },
	{ 0, 0 },
	{ 640, 470 },
	{ 640, 469 }
};

void
Go (int n);

void
Change (int n)
{
    ASSIGN(choice, variantNames[values[n]]);
    Go(3); // simulate 'Play' press
}

static Option startOptions[] = {
{ 6, COMBO_CALLBACK, 0, NULL, (void*) &Change, (char*) variantNames, variantList, ComboBox, N_("Select Variant:") },
{ 103, L2L|T2T, 319,NULL, (char*) &ExpLogo, NULL, NULL, Graph, "logo" }, // board
{ 7,     LR,     0, NULL, NULL, NULL, NULL, Label, N_("Linux / GTK+ / C port by H.G.Muller (2014)") }, // black clock
{ 1,    0,     100, NULL, (void*) &Go, NULL, NULL, Button, N_("Play") },
{ 2, SAME_ROW, 100, NULL, (void*) &Go, NULL, NULL, Button, N_("Load Game") },
{ 3, SAME_ROW, 100, NULL, (void*) &Go, NULL, NULL, Button, N_("Quit") },
{ 0, SAME_ROW,   0, NULL, NULL, NULL, NULL, Break, "" },
{ 179, LR|TB,  125, NULL, (char*) &ExpSamurai, NULL, NULL, Graph, "samurai" }, // board
{ 0,  NO_OK, 0, NULL, NULL, "", NULL, EndMark , "" }
};

void
Go (int n)
{
    static int used;
    n = startOptions[n].value;
    switch(n) {
	case 1: GenericReadout(startOptions, -1);
		if(!choice) { ASSIGN(choice, "Shogi"); }
		if(!*choice) return; // prevent selecting separator
		strcpy(Choice, choice);
		StartUp();
		UpdateCaptions();
		used = 1;
		break; // Play
	case 2: *Choice = '\0'; LoadGameProc(); break; // FIXME: this uses LoadGame instead of LoadGame2
	case 3: if(used) QuitProc(); else exit(0); break; // Quit
    }
    InitMenuMarkers();
    PopDown(RootWindow);
}

static Option *
ExpLogo(int n, int x, int y)
{
    if(n == 10) DrawLogo(&startOptions[1], DATADIR "/titles/logo.png");
    return NULL;
}

static Option *
ExpSamurai(int n, int x, int y)
{
    if(n == 10) DrawLogo(&startOptions[7], DATADIR "/titles/armour.png");
    return NULL;
}

void
UnloadStart()
{
    PopDown(RootWindow);
}

void
LoadStart()
{
    GenericPopUp(startOptions, "ShogiVar", RootWindow, RootWindow, MODAL, 0);
    ExpSamurai(10, 0, 0); ExpLogo(10, 0, 0);
    SetColoredLabel(&startOptions[2], startOptions[2].name, "blue", "#F0F0F0", "Sans Bold 9");
}

// [HGM] experimental code to pop up window just like the main window, using GenercicPopUp

static int boardWidth, boardHeight;
void *dotLarge, *dotSmall;

void
Dot(int x, int y)
{
    int w = 6, h = 7, d = 4;
    void *dot = dotSmall;
    if(Pixels > 50) dot = dotLarge, w = 10, h = 9, d = 5;
    if(BoardSizeY >= 12 && BoardSizeY <= 16) d--;
    CopyRectangle(dot, 0, 0, w, h, XStart + x*Pixels - d, 11 + y*Pixels - d);
}

void
Render (OBJECT *p)
{
    if(!p->Visible) return;
    CopyRectangle(p->Picture, 0, 0, p->width, p->height, p->x, p->y);
}

void
DrawBoard ()
{
    int i, dotX, dotY = PromDotY, Pixels = Board.Pix[1].width;
    CopyRectangle(Board.Picture, 0, 0, boardWidth, boardHeight, 0, 0);
    for(i=0; i<NPIECES; i++) Render(&Board.showpic[i]);
    for(i=0; i<NTYPES; i++) Render(&Board.HandPic[i]);
    for(i=0; i<NTYPES; i++) if(Board.HandPic[i].Visible) {
	int off = Pixels/2 + 5, mid = Board.HandPic[i].x + Pixels/2 - 4, h = mid;
	if(mid > 320) off = - off, h = 640 - h;
	if(h > Pixels) off = -off;
	DrawSeekText(Board.Held[i].Caption,
		     mid - off + (off < 0 & Pixels), // odd mid was rounded down
		     Board.HandPic[i].y + Pixels/2 - 5);
    }
    dotX = (2*BoardSizeY)/3 + 1 >> 1; // divide as equal as possible
    if(BoardSizeY > 16) dotY = 6 + (BoardSizeY > 20); // force dots in DaiDai+
    if(dotY) { // repair board dots overwritten by pieces
	if(BoardSizeX - 2*dotX <= 1 || BoardSizeY == 11) dotX--;
	Dot(dotX, dotY);
	Dot(BoardSizeX - dotX, dotY);
	Dot(dotX, BoardSizeY - dotY);
	Dot(BoardSizeX - dotX, BoardSizeY - dotY);
    }
    GraphExpose(&mainOptions[W_BOARD], 0, 0, boardWidth, boardHeight);
    DrawWidgetIcon(&mainOptions[W_BICON], 3 + Reverse);
    DrawWidgetIcon(&mainOptions[W_WICON], 2 - Reverse);
    if(Notate) NotSet();
}

static Option *Exp(int n, int x, int y);
void MenuCallback(int n);

static void
CCB (int n)
{
    shiftKey = (ShiftKeys() & 3) != 0;
    if(n < 0) { // button != 1
	n = -n;
	if(shiftKey) {
//	    AdjustClock(n == W_BLACK, 1);
	}
    } else
;//    ClockClick(n == W_BLACK);
}

Option mainOptions[] = { // description of main window in terms of generic dialog creator
{ 0, 0xCA, 0, NULL, NULL, "", NULL, BarBegin, "" }, // menu bar
  { 0, COMBO_CALLBACK, 0, NULL, (void*)&MenuCallback, NULL, NULL, DropDown, N_("Game") },
  { 0, COMBO_CALLBACK, 0, NULL, (void*)&MenuCallback, NULL, NULL, DropDown, N_("Moves") },
  { 0, COMBO_CALLBACK, 0, NULL, (void*)&MenuCallback, NULL, NULL, DropDown, N_("Preferences") },
  { 0, COMBO_CALLBACK, 0, NULL, (void*)&MenuCallback, NULL, NULL, DropDown, N_("Set-Up") },
  { 0, COMBO_CALLBACK, 0, NULL, (void*)&MenuCallback, NULL, NULL, DropDown, N_("Help") },
{ 0, 0, 0, NULL, NULL, "", NULL, BarEnd, "" },
{ 401, LR|TB,  401, NULL, (char*) &Exp, NULL, NULL, Graph, "shadow board" }, // board
{ 7,     L2L,          70, NULL, (void*) &CCB, NULL, NULL, Label, "Black" }, // black clock
{  0,       SAME_ROW,  18, NULL, NULL, NULL, NULL, Icon, " " },
{ 0, BORDER|SAME_ROW, 260, NULL, NULL, "", NULL, Label, "" }, // PieceID field
{ 0, BORDER|SAME_ROW,  90, NULL, NULL, "", NULL, Label, "" }, // LastMove field
{ 0, BORDER|SAME_ROW, 110, NULL, NULL, "", NULL, Label, "" }, // NextMove field
{  0,       SAME_ROW,  18, NULL, NULL, NULL, NULL, Icon, " " },
{ 10,   R2R|SAME_ROW,  70, NULL, (void*) &CCB, NULL, NULL, Label, "White" }, // white clock
{ 0, COMBO_CALLBACK, 0, NULL, (void*)&MenuCallback, NULL, NULL, PopUp, "Bindings" }, // BEWARE! Must be 15th!
{ 0,  NO_OK, 0, NULL, NULL, "", NULL, EndMark , "" }
};

void
MenuCallback (int n)
{
    MenuProc *proc = (MenuProc *) (((MenuItem*)(mainOptions[n].choice))[values[n]].proc);

    if(proc) (proc)();
    if( !(n == 1 && values[n] == 3) )
	UpdateCaptions();
}

static int grabbed; // encodes dragged item

static int Dispatch(int button, int x, int y);

static int
ShowpicsClick(int index, int button, int x, int y)
{
    if(button == 9) { // DragDrop
	NewIndex = index; PicDrop();
	return 0;
    }
    NewButton = abs(button); I = index;
    if(button > 0) { // press
	grabbed = index + 1; // remember what we drag
	CCC = 1; ClickPiece = 1;
	EndTilde();
	if(button == 1) PicDown(); else ShowProm();
	if(button == 1 && Board.showpic[index].dragged) NewCursor(&mainOptions[W_BOARD], "");
    } else { // release
	int n = Board.showpic[index].dragged;
	if(n) Dispatch(9, x, y); // generate DragDrop event
	DropPiece();
	if(button == -1 && n) NewCursor(&mainOptions[W_BOARD], NULL);
    }
    return 0;
}

static int
HandpicsClick(int index, int button, int x, int y)
{
    if(button == 9) { // DragDrop
	ClearLegal();
    } else if(button > 0) { // press
	grabbed = -1 - index; // remember what we drag
	CCC = 1; NewButton = abs(button); I = index;
	EndTilde();
	if(button == 1) HeldDown(); else HeldProm();
	if(button == 1 && Board.HandPic[index].dragged) NewCursor(&mainOptions[W_BOARD], "");
    } else { // release
	int n = Board.HandPic[index].dragged;
	if(n) Dispatch(9, x, y); // generate DragDrop event
	NewButton = abs(button); I = index;
	DropPiece2();
	if(button == -1 && n) NewCursor(&mainOptions[W_BOARD], NULL);
    }
    return 0;
}

static int
FormClick(int button, int x, int y)
{
    if(button == 9) { // DragDrop
	NewX = x; NewY = y; FormDrop();
    } else if(button > 0) { // press
	CCC = 1; ClickPiece = 0; NewX = x, NewY = y;
	EndTilde();
	if(button == 1) FillSquare(); else ShowProm();
    } else { // release
	if(LegalMoves == 0) ClearLegal();
    }
    return 0;
}

static int
Dispatch (int button, int x, int y)
{   // figure out in which screen element the click takes place
    int i;
    for(i=0; i<NSQUARES; i++) {
        OBJECT *p = &Board.showpic[i];
	if(p->Visible &&
	   p->x <= x && x < p->x + p->width &&
	   p->y <= y && y < p->y + p->height  )
	    return ShowpicsClick(i, button, x, y);
    }
    for(i=0; i<NTYPES; i++) {
        OBJECT *p = &Board.HandPic[i];
	if(p->Visible &&
	   p->x <= x && x < p->x + p->width &&
	   p->y <= y && y < p->y + p->height  )
	    return HandpicsClick(i, button, x, y);
    }
    return FormClick(button, x, y);
}

int
MouseClick (int button, int x, int y)
{   // Primary mouse handler
    static int lastX, lastY;
    int j = grabbed, i = 0;
    if(button < 0) {
	if(j) { // up-click to same object as down-click
	    if(j > 0) i = ShowpicsClick( j-1, -1, x, y); else
	    if(j < 0) i = HandpicsClick(-j-1, -1, x, y);
        } else i = FormClick(button, x, y);
	grabbed = 0;
    } else { // down-click to clicked object
	i = Dispatch(button, x, y);
	lastX = x; lastY = y;
    }
    UpdateCaptions();
    return i;
}

static Option *
Exp (int n, int x, int y)
{
    static int but1, but3, oldW, oldH;
    int menuNr = -3, sizing;
    TimeMark now;

    if(n == 0) { // motion
//	if((but1 || dragging == 2) && !PromoScroll(x, y)) DragPieceMove(x, y);
//	if(but3) MovePV(x, y, oldH);
	return NULL;
    }
//    if(n != 10 && PopDown(PromoDlg)) fromX = fromY = -1; else // user starts fiddling with board when promotion dialog is up
    GetTimeMark(&now);
    shiftKey = ShiftKeys();
    controlKey = (shiftKey & 0xC) != 0;
    shiftKey = (shiftKey & 3) != 0;
    switch(n) {
	case  1: MouseClick(n, x, y); but1 = 1; break;
	case -1: MouseClick(n, x, y); but1 = 0; break;
	case  2: shiftKey = !shiftKey;
	case  3: MouseClick(n, x, y); but3 = 1; break;
	case -2: shiftKey = !shiftKey;
	case -3: MouseClick(n, x, y); but3 = 0; break;
	case 10:
	    sizing = (oldW != x || oldH != y);
	    oldW = x; oldH = y;
	    InitDrawingHandle(mainOptions + W_BOARD);
//	    if(sizing && SubtractTimeMarks(&now, &programStartTime) > 10000) return NULL; // don't redraw while sizing (except at startup)
	    DrawBoard();
	default:
	    return NULL;
    }

    switch(menuNr) {
      case 2:
      case -1: ErrorPopDown();
      case -2:
      default: break; // -3, so no clicks caught
    }
    return NULL;
}

Option *
BoardPopUp (int squareSize, int lineGap, void *clockFontThingy)
{
    int i;
//    mainOptions[W_WHITE].choice = (char**) clockFontThingy;
//    mainOptions[W_BLACK].choice = (char**) clockFontThingy;
    for(i=0; strcmp(Choice, variantNames[i]); i++);
    boardWidth = windowSize[i].x; boardHeight = windowSize[i].y;
    mainOptions[W_BOARD].value = boardHeight;
    mainOptions[W_BOARD].max = boardWidth; // board size
//    mainOptions[W_PIECE].max = mainOptions[W_LAST].max = mainOptions[W_NEXT].max = 
//    mainOptions[W_BLACK].max = mainOptions[W_WHITE].max = (boardWidth-36)/5-3; // clock width
    mainOptions[W_MENU].max = boardWidth-40; // menu bar
    for(i=0; i<5; i++) mainOptions[i+1].choice = (char**) menuBar[i].mi;
    mainOptions[W_BIND].choice = (char**) menuBar[5].mi; // BEWARE! Must correspond to order!
    GenericPopUp(mainOptions, "GUI", BoardDlg, RootWindow, MODAL, 1);
    return mainOptions;
}

void
BoardPopDown()
{
    Board.Timer1.Enabled = False; // make sure clock stops updating labels
    PopDown(BoardDlg);
}

void
UnloadBoard()
{
    int t = GetTime();
    BoardPopDown();
    while(GetTime() - t < 500) { DoEvents(); usleep(10000); }
    UnloadImages();
    Destroy(BoardDlg);
}


//---------------------------------------------

char lastMsg[MSG_SIZ];

void
DisplayMessage (char *message, char *extMessage)
{
  /* display a message in the message widget */

  char buf[MSG_SIZ];

  if (extMessage)
    {
      if (*message)
	{
	  snprintf(buf, sizeof(buf), "%s  %s", message, extMessage);
	  message = buf;
	}
      else
	{
	  message = extMessage;
	};
    };

    strncpy(lastMsg, message, MSG_SIZ); // [HGM] make available

  /* need to test if messageWidget already exists, since this function
     can also be called during the startup, if for example a Xresource
     is not set up correctly */
//  if(mainOptions[W_MESSG].handle)
//    SetWidgetLabel(&mainOptions[W_MESSG], message);

  return;
}

int
StartTime ()
{
    return programStartTime.ms;
}

int
GetTime ()
{
    TimeMark now;
    GetTimeMark(&now);
    return now.ms;
}

static char *openName;
FileProc fileProc;
char *fileOpenMode;
FILE *openFP;

void
DelayedLoad ()
{
  (void) (*fileProc)(openFP, 0, openName);
}

char *
Cleanse (char *s)
{
    static char buf[MSG_SIZ];
    char *p = buf;
    while(*p++ = *s++) if(p[-1] < ' ' || p[-1] > 126) p[-1] = '?';
    return buf;
}

void
UpdateMsg (Option *opt, char *s, char *old, char *fg, char *bg, char *font)
{
    s = Cleanse(s);
    if(strcmp(s, old)) {
	strcpy(old, s);
	SetColoredLabel(opt, s, fg, bg, font);
    }
}

void
UpdateCaptions ()
{
    static STRING white, black, pieceID, lastMove, nextMove, title;
    char textColor[MSG_SIZ];
    int fg = Board.PieceID.ForeColor;
    snprintf(textColor, MSG_SIZ, "#%02x%02x%02x", fg&255, fg>>8&255, fg>>16&255); // Yegh! RB-swap
    UpdateMsg(&mainOptions[W_WHITE], &Board.WhiteClock.Caption[0], &white[0], "white", "grey", "Sans Bold 9");
    UpdateMsg(&mainOptions[W_BLACK], &Board.BlackClock.Caption[0], &black[0], "black", "grey", "Sans Bold 9");
    UpdateMsg(&mainOptions[W_PIECE], &Board.PieceID.Caption[0],  &pieceID[0], textColor, "#F0F0F0", "Sans Bold 9");
    UpdateMsg(&mainOptions[W_LAST],  &Board.LastMove.Caption[0], &lastMove[0], "black", "#F0F0F0", "Sans 9");
    UpdateMsg(&mainOptions[W_NEXT],  &Board.NextMove.Caption[0], &nextMove[0], "red", "#F0F0F0", "Sans Bold 9");
    if(strcmp(Board.Caption, title)) {
	strcpy(title, Board.Caption);
	SetWindowTitle(BoardDlg, title, "");
    }
}

void
MoveObject (int draw, OBJECT *obj, int x, int y /*, int w, int h*/)
{
    obj->x = x; obj->y = y; // obj->width = 2; obj->height = h;
    if(draw) DrawBoard();
}

void
Refresh ()
{
    DrawBoard();
}

void
DrawText (char *s)
{
    DrawSeekText(s, Board.CurrentX, Board.CurrentY);
}

static void
DrawLineWrapper (int x1, int y1, int x2, int y2, int c, char *options)
{
//printf("line (%d,%d)-(%d,%d) %dx%d %06x\n",x1,y1,x2,y2,x2-x1,y2-y1,Board.ForeColor);
    DrawLine(x1, y1, x2, y2, Board.ForeColor, options);
}

void
DrawCircleWrapper (int x, int y, int r)
{
    DrawCircle(x, y, r, Board.ForeColor, Board.FillColor, !Board.FillStyle);
}

void
InitBoard (char *name)
{
    int i;
    Board.Refresh = &Refresh;
    Board.Show = &Refresh;  // FIXME
    Board.Hide = &Refresh;  // FIXME
    Board.Print = &DrawText;
    Board.Line = &DrawLineWrapper;
    Board.Circle = &DrawCircleWrapper;

    Board.Timer1.Enabled = True;
    StartClockTimer(1000);

    for(i=0; i<NTYPES; i++) Board.HandPic[i].Visible = False;
    for(i=0; i<NSQUARES; i++) {
	Board.showpic[i].Visible = False;
	Board.showpic[i].Picture = NULL;
    }
    ReadIcon(DATADIR "/WhiteUp.png", 1);
    ReadIcon(DATADIR "/WhiteDn.png", 2);
    ReadIcon(DATADIR "/BlackUp.png", 3);
    ReadIcon(DATADIR "/BlackDn.png", 4);
    LoadPieces(name);
}