summaryrefslogtreecommitdiff
path: root/plugins/!NotAdopted/Chess4Net/ManagerUnit.pas
blob: a20cb4c1bc80af3ff02944a285faf149b5bd39c7 (plain)
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
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
////////////////////////////////////////////////////////////////////////////////
// All code below is exclusively owned by author of Chess4Net - Pavel Perminov
// (packpaul@mail.ru, packpaul1@gmail.com).
// Any changes, modifications, borrowing and adaptation are a subject for
// explicit permition from the owner.

unit ManagerUnit;

{$DEFINE GAME_LOG}

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
  Menus, TntMenus, ActnList, TntActnList, ExtCtrls,
{$IFDEF TRILLIAN}
  plugin,
{$ENDIF}
  // Chess4Net Units
  ChessBoardHeaderUnit, ChessRulesEngine, ChessBoardUnit,
  GameChessBoardUnit, ConnectorUnit, ConnectingUnit, GameOptionsUnit,
  ModalForm, DialogUnit, ContinueUnit, LocalizerUnit, URLVersionQueryUnit;

type
  TManager = class(TForm, ILocalizable)
    ActionList: TTntActionList;
    LookFeelOptionsAction: TTntAction;
    AboutAction: TTntAction;

    ConnectedPopupMenu: TTntPopupMenu;
    LookFeelOptionsConnected: TTntMenuItem;
    StartStandartGameConnected: TTntMenuItem;
    StartPPRandomGameConnected: TTntMenuItem;
    GameOptionsConnected: TTntMenuItem;
    ChangeColorConnected: TTntMenuItem;
    GamePopupMenu: TTntPopupMenu;
    AbortGame: TTntMenuItem;
    DrawGame: TTntMenuItem;
    ResignGame: TTntMenuItem;
    N4: TTntMenuItem;
    LookFeelOptionsGame: TTntMenuItem;
    TakebackGame: TTntMenuItem;
    GamePause: TTntMenuItem;
    N1: TTntMenuItem;
    AboutConnected: TTntMenuItem;
    N2: TTntMenuItem;
    AboutGame: TTntMenuItem;
    StartAdjournedGameConnected: TTntMenuItem;
    AdjournGame: TTntMenuItem;
    N5: TTntMenuItem;
    N6: TTntMenuItem;

    BroadcastAction: TTntAction;
    N3: TTntMenuItem;
    BroadcastConnected: TTntMenuItem;
    N7: TTntMenuItem;
    Broadcast: TTntMenuItem;
    
    ConnectorTimer: TTimer;

    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure ActionListUpdate(Action: TBasicAction;
      var Handled: Boolean);
    procedure LookFeelOptionsActionExecute(Sender: TObject);
    procedure AbortGameClick(Sender: TObject);
    procedure DrawGameClick(Sender: TObject);
    procedure ResignGameClick(Sender: TObject);
    procedure ChangeColorConnectedClick(Sender: TObject);
    procedure GameOptionsConnectedClick(Sender: TObject);
    procedure StartStandartGameConnectedClick(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure ConnectorTimerTimer(Sender: TObject);
    procedure StartPPRandomGameConnectedClick(Sender: TObject);
    procedure TakebackGameClick(Sender: TObject);
    procedure GamePauseClick(Sender: TObject);
    procedure AboutActionExecute(Sender: TObject);
    procedure StartAdjournedGameConnectedClick(Sender: TObject);
    procedure AdjournGameClick(Sender: TObject);
    procedure GamePopupMenuPopup(Sender: TObject);
    procedure BroadcastActionExecute(Sender: TObject);

  private
    m_ConnectingForm: TConnectingForm;
    m_ContinueForm: TContinueForm;
    m_Connector: TConnector;
    m_ChessBoard: TGameChessBoard;
    m_Dialogs: TDialogs;

    m_ExtBaseList: TStringList;
    m_strExtBaseName: string;
{$IFDEF QIP}
    iProtoDllHandle: integer;
    wAccName: WideString;
    QIPConnectionError: boolean;
{$ENDIF}
{$IFDEF TRILLIAN}
    contactlistEntry: TTtkContactListEntry;
{$ENDIF}
{$IFDEF SKYPE}
    m_bDontShowCredits: boolean;
{$ENDIF}
    m_lwOpponentClientVersion: LongWord;
    // It's for ChessBoard
    you_unlimited, opponent_unlimited: boolean;
    you_time, opponent_time,
    you_inc, opponent_inc: word;
    you_takebacks, opponent_takebacks: boolean;
    can_pause_game, can_adjourn_game, move_done: boolean;

    m_strPlayerNick: string;
    m_strPlayerNickId: string;

    m_strOpponentNick: string;
    m_strOpponentId: string;
    m_strOverridedOpponentNickId: string;

    extra_exit: boolean;
    m_bConnectionOccured: boolean;

    m_bTransmittable: boolean;

    m_iDontShowLastVersion: integer;
    m_iQueriedDontShowLastVersion: integer;

{$IFDEF GAME_LOG}
    // for game log
    gameLog: string;
    procedure FInitGameLog;
    procedure FWriteToGameLog(const s: string);
    procedure FlushGameLog;
{$ENDIF}
    procedure ChessBoardHandler(e: TGameChessBoardEvent;
      d1: pointer = nil; d2: pointer = nil);
    procedure SetClock; overload;
    procedure SetClock(var sr: string); overload;

    procedure FPopulateExtBaseList;

    function FReadCommonSettings(setToOpponent: boolean): boolean;
    procedure FWritePrivateSettings;
    procedure FWriteCommonSettings;

    function ClockToStr: string;
    procedure ChangeColor;
    procedure PauseGame;
    procedure ContinueGame;
    procedure FAdjournGame;
    procedure FExitGameMode;

    procedure FBuildAdjournedStr;
    procedure FStartAdjournedGame;

    function FGetAdjournedStr: string;
    procedure FSetAdjournedStr(const strValue: string);

    function FGetPlayerColor: TFigureColor;
    procedure FSetPlayerColor(Value: TFigureColor);

    function FGetOpponentNickId: string;
{$IFDEF SKYPE}
    procedure FShowCredits;
{$ENDIF}

    procedure FSetTransmittable(bValue: boolean);

    procedure FOnURLQueryReady(Sender: TURLVersionQuery);

    property AdjournedStr: string read FGetAdjournedStr write FSetAdjournedStr;
    property _PlayerColor: TFigureColor read FGetPlayerColor write FSetPlayerColor;

  protected
    constructor RCreate;

    procedure ROnCreate; virtual; abstract;
    procedure ROnDestroy; virtual;

    procedure ConnectorHandler(e: TConnectorEvent;
      d1: pointer = nil; d2: pointer = nil); virtual;
    procedure RCreateChessBoardAndDialogs;
    procedure RCreateAndPopulateExtBaseList;
    procedure RSetChessBoardToView;

    procedure RReadPrivateSettings;
    procedure RShowConnectingForm;

    procedure ILocalizable.Localize = RLocalize;
    procedure RLocalize;

    class procedure RSplitStr(s: string; var strLeft: string; var strRight: string);
    procedure RHandleConnectorDataCommand(sl: string); virtual;
    procedure RSetOpponentClientVersion(lwVersion: LongWord); virtual;

    procedure RSendData(const cmd: string = ''); virtual; abstract;

    procedure RSetConnectionOccured; virtual;
    function RGetGameName: string; virtual;

    function RGetGameContextStr: string;
    procedure RSetGameContext(const strValue: string);

    procedure RReleaseWithConnectorGracefully;

    procedure RRetransmit(const strCmd: string); virtual;
    procedure RBroadcast; virtual;

    procedure RUpdateChessBoardCaption;

    procedure DialogFormHandler(modSender: TModalForm; msgDlgID: TModalFormID); virtual;

    property Connector: TConnector read m_Connector write m_Connector;
    property ChessBoard: TGameChessBoard read m_ChessBoard write m_ChessBoard;

    property PlayerNick: string read m_strPlayerNick write m_strPlayerNick;
    property PlayerNickId: string read m_strPlayerNickId write m_strPlayerNickId;
    property OpponentNick: string read m_strOpponentNick write m_strOpponentNick;
    property OpponentId: string read m_strOpponentId write m_strOpponentId;
    property OpponentNickId: string read FGetOpponentNickId write m_strOverridedOpponentNickId;

    property Transmittable: boolean read m_bTransmittable write FSetTransmittable;

    property pDialogs: TDialogs read m_Dialogs;

  public
{$IFDEF AND_RQ}
    class function Create: TManager; reintroduce;
{$ENDIF}
{$IFDEF QIP}
    class function Create(const accName: WideString; const protoDllHandle: integer): TManager; reintroduce;
{$ENDIF}
{$IFDEF TRILLIAN}
    class function Create(const vContactlistEntry: TTtkContactListEntry): TManager; reintroduce;
{$ENDIF}
  end;

const
  CMD_DELIMITER = '&&'; // CMD_DELIMITER has to be present in arguments

  CMD_VERSION = 'ver';
  CMD_WELCOME = 'wlcm'; // Accept of connection
  CMD_GOODBYE = 'gdb'; // Refusion of connection
  CMD_TRANSMITTING = 'trnsm';
  CMD_NICK_ID = 'nkid';
  CMD_CONTINUE_GAME = 'cont';
  CMD_GAME_CONTEXT = 'gmctxt';

implementation

{$R *.dfm}
{$J+}

uses
  // Chess4Net
  DateUtils, Math, StrUtils, Dialogs,
  //
  LookFeelOptionsUnit, GlobalsUnit, GlobalsLocalUnit, InfoUnit, ChessClockUnit,
  DontShowMessageDlgUnit, IniSettingsUnit, PosBaseChessBoardLayerUnit
{$IFDEF AND_RQ}
  , CallExec
{$ENDIF}
{$IFDEF QIP}
  , ControlUnit
{$ENDIF}
{$IFDEF SKYPE}
  , CreditsFormUnit
{$ENDIF}
  ;

const
  USR_BASE_NAME = 'Chess4Net';

  NO_CLOCK_TIME ='u u';

  HOUR_TIME_FORMAT = 'h:nn:ss';

  // Command shorthands for Connector
  CMD_ECHO = 'echo';
  CMD_START_GAME = 'strt';
  CMD_GAME_OPTIONS = 'gmopt'; // Doesn't exist from 2007.5
  CMD_CHANGE_COLOR = 'chclr';
//  CMD_NICK_ID = 'nkid';
  CMD_RESIGN = 'res';
  CMD_ABORT = 'abrt';
  CMD_ABORT_ACCEPTED = 'abrtacc';
  CMD_ABORT_DECLINED = 'abrtdec';
  CMD_DRAW = 'draw';
  CMD_DRAW_ACCEPTED = 'drawacc';
  CMD_DRAW_DECLINED = 'drawdec';
  CMD_FLAG = 'flg';
  CMD_FLAG_YES = 'flgyes';
  CMD_FLAG_NO = 'flgno';
  CMD_TAKEBACK = 'tkbk';
  CMD_TAKEBACK_YES = 'tkbkyes';
  CMD_TAKEBACK_NO = 'tkbkno';
  CMD_SWITCH_CLOCK = 'swclck';
  CMD_REPEAT_COMMAND = 'rptcmd';
  CMD_POSITION = 'pos';
//  CMD_VERSION = 'ver';
//  CMD_WELCOME = 'wlcm'; // Accept of connection
//  CMD_GOODBYE = 'gdb'; // Refusion of connection
  // ñóùåñòâóåò ñ 2007.5
  CMD_NO_SETTINGS = 'noset'; // If global settings are absent then request from partner's client
  CMD_ALLOW_TAKEBACKS = 'alwtkb';
  CMD_SET_CLOCK = 'clck'; // Change of timing  
  CMD_SET_TRAINING = 'trnng'; // Setting training mode
  // Ñóùåñòâóåò ñ 2007.6
  CMD_CAN_PAUSE_GAME = 'canpaus';
  CMD_PAUSE_GAME = 'paus';
  CMD_PAUSE_GAME_YES = 'pausyes';
  CMD_PAUSE_GAME_NO = 'pausno';
//  CMD_CONTINUE_GAME = 'cont';
  // Ñóùåñòâóåò ñ 2008.1
  CMD_CAN_ADJOURN_GAME = 'canadj';
  CMD_SET_ADJOURNED = 'setadj'; // Setting of adj. position and timing
  CMD_ADJOURN_GAME = 'adj';
  CMD_ADJOURN_GAME_YES = 'adjyes';
  CMD_ADJOURN_GAME_NO = 'adjno';
  CMD_START_ADJOURNED_GAME = 'strtadj';

  // CMD_DELIMITER = '&&'; // CMD_DELIMITER has to be present in arguments
  // CMD_CLOSE = 'ext' - IS RESERVED

type
  TManagerDefault = class(TManager) // TODO: TRILLIAN, AND_RQ, QIP-> own classes
  protected
    procedure ROnCreate; override;
    procedure ROnDestroy; override;
    procedure RSendData(const cmd: string = ''); override;
  public
{$IFDEF AND_RQ}
    constructor Create; reintroduce;
{$ENDIF}
{$IFDEF QIP}
    constructor Create(const accName: WideString; const protoDllHandle: integer); reintroduce;
{$ENDIF}
{$IFDEF TRILLIAN}
    constructor Create(const vContactlistEntry: TTtkContactListEntry); reintroduce;
{$ENDIF}
  end;

////////////////////////////////////////////////////////////////////////////////
// TManager

procedure TManager.RCreateChessBoardAndDialogs;
begin
//  m_ChessBoard := TGameChessBoard.Create(self, ChessBoardHandler, Chess4NetPath + USR_BASE_NAME);
  m_ChessBoard := TGameChessBoard.Create(nil, ChessBoardHandler, Chess4NetGamesLogPath + USR_BASE_NAME);
  m_Dialogs := TDialogs.Create(ChessBoard, DialogFormHandler);
end;


procedure TManager.FormCreate(Sender: TObject);
begin
{$IFNDEF SKYPE}
  BroadcastAction.Visible := TRUE;
{$ENDIF}
  ROnCreate;
end;


procedure TManager.RShowConnectingForm;
begin
  m_ConnectingForm := (m_Dialogs.CreateDialog(TConnectingForm) as TConnectingForm);
  m_ConnectingForm.Show;
end;


procedure TManager.ChessBoardHandler(e: TGameChessBoardEvent;
                            d1: pointer = nil; d2: pointer = nil);
var
  s: string;
  wstrMsg1, wstrMsg2: WideString;
  strSwitchClockCmd: string;
begin
  case e of
    cbeKeyPressed:
      if extra_exit and (Word(d1) = VK_ESCAPE) then
        begin
{$IFDEF GAME_LOG}
          if (ChessBoard.Mode = mGame) then
          begin
            FWriteToGameLog('*');
            FlushGameLog;
          end;
{$ENDIF}
          Release;
        end;

    cbeExit:
      Close;

    cbeMenu:
      if (not m_Dialogs.Showing) then
      begin
        if ((ChessBoard.Mode = mView) or Transmittable) then
        begin
          if (Connector.connected) then
            ConnectedPopupMenu.Popup(Mouse.CursorPos.X, Mouse.CursorPos.Y);
        end
        else if (ChessBoard.Mode = mGame) then
        begin
          GamePopupMenu.Popup(Mouse.CursorPos.X, Mouse.CursorPos.Y);
        end;
      end;

    cbeMoved:
      begin
        if (not Transmittable) then
        begin
          RSendData(PString(d1)^);
          RRetransmit(PString(d1)^);
        end;
{$IFDEF GAME_LOG}
        if (ChessBoard.PositionColor = fcBlack) or (not move_done) then
        begin
          FWriteToGameLog(' ' + IntToStr(ChessBoard.NMoveDone) + '.');
          if (ChessBoard.PositionColor = fcWhite) then
            FWriteToGameLog(' ...');
        end;
        FWriteToGameLog(' ' + PString(d1)^);
{$ENDIF}
        move_done := TRUE;
        TakebackGame.Enabled := TRUE;
      end;

    cbeMate:
      with ChessBoard do
      begin
        FExitGameMode;
{$IFDEF GAME_LOG}
        FWriteToGameLog('#');
        if (PositionColor = fcWhite) then
          FWriteToGameLog(sLineBreak + '0 - 1')
        else
          FWriteToGameLog(sLineBreak + '1 - 0');
        FlushGameLog;
{$ENDIF}
        with TLocalizer.Instance do
        begin
          if (Transmittable) then
          begin
            if (PositionColor = fcWhite) then
              wstrMsg1 := GetMessage(36) // White is checkmated.
            else
              wstrMsg1 := GetMessage(37); // Black is checkmated.
            wstrMsg2 := wstrMsg1;
          end
          else // not Transmittable
          begin
            if (PositionColor = fcWhite) then
            begin
              wstrMsg1 := GetMessage(0); // White is checkmated. You win.
              wstrMsg2 := GetMessage(1); // White is checkmated. You loose.
            end
            else
            begin
              wstrMsg1 := GetMessage(2); // Black is checkmated. You win.
              wstrMsg2 := GetMessage(3); // Black is checkmated. You loose.
            end;
          end;
        end; // with

        if ((_PlayerColor <> fcWhite) and (PositionColor = fcWhite)) or
           ((_PlayerColor <> fcBlack) and (PositionColor = fcBlack)) then
        begin
          m_Dialogs.MessageDlg(wstrMsg1, mtCustom, [mbOK], mfNone);
          ChessBoard.WriteGameToBase(grWin);
        end
        else
        begin
          m_Dialogs.MessageDlg(wstrMsg2, mtCustom, [mbOK], mfNone);
          ChessBoard.WriteGameToBase(grLost);
        end;
      end;

    cbeStaleMate:
    begin
      FExitGameMode;
{$IFDEF GAME_LOG}
      FWriteToGameLog('=' + sLineBreak + '1/2 - 1/2');
      FlushGameLog;
{$ENDIF}
      if (Transmittable) then
        wstrMsg1 := TLocalizer.Instance.GetMessage(35) // Stalemate.
      else
        wstrMsg1 := TLocalizer.Instance.GetMessage(4); // It's stalemate. No one wins.
      m_Dialogs.MessageDlg(wstrMsg1, mtCustom, [mbOK], mfNone);
      ChessBoard.WriteGameToBase(grDraw);
    end;

    cbeClockSwitched:
    begin
      if (Transmittable) then
        exit;
      with ChessBoard do
      begin
        if (move_done and (ClockColor = PositionColor)) then
        begin
          if (ClockColor <> _PlayerColor) then
          begin
            Time[_PlayerColor] := IncSecond(Time[_PlayerColor], you_inc);
            s := TChessClock.ConvertToFullStr(Time[_PlayerColor]);

            if ((not Unlimited[_PlayerColor]) or (m_lwOpponentClientVersion < 200706)) then
            begin
              strSwitchClockCmd := CMD_SWITCH_CLOCK + ' ' + s;
              RSendData(strSwitchClockCmd);
              RRetransmit(strSwitchClockCmd);
            end;
          end
          else
          begin
            if (_PlayerColor = fcWhite) then
              Time[fcBlack] := IncSecond(Time[fcBlack], opponent_inc)
            else
              Time[fcWhite] := IncSecond(Time[fcWhite], opponent_inc);
          end;
        end;
      end; { with }
    end;

    cbeTimeOut:
    begin
      if (not Transmittable) then
        RSendData(CMD_FLAG);
    end;

    cbeActivate:
    begin
      m_Dialogs.BringToFront;
    end;

    cbeFormMoving:
    begin
      m_Dialogs.MoveForms(integer(d1), integer(d2));
    end;
  end;
end;


class procedure TManager.RSplitStr(s: string; var strLeft: string; var strRight: string);
var
  x: integer;
begin
  x := pos(' ', s);
  strLeft := copy(s, 1, sign(x) * (x - 1) + (1 - sign(x)) * length(s));
  strRight := copy(s, length(strLeft) + 2, length(s));
end;


procedure TManager.SetClock(var sr: string);
var
  sl: string;


  procedure NSetOpponentTime;
  begin
    RSplitStr(sr, sl, sr);
    if (sl = 'u') then
      opponent_unlimited := TRUE
    else
    begin
      opponent_unlimited:= FALSE;
      opponent_time:= StrToInt(sl);
      RSplitStr(sr, sl, sr);
      opponent_inc := StrToInt(sl);
    end;
  end;

  procedure NSetYouTime;
  begin
    RSplitStr(sr, sl, sr);
    if (sl = 'u') then
      you_unlimited:= TRUE
    else
    begin
      you_unlimited := FALSE;
      you_time := StrToInt(sl);
      RSplitStr(sr, sl, sr);
      you_inc := StrToInt(sl);
    end;
  end;

begin // TManager.SetClock
  if (Transmittable) then
  begin
    NSetYouTime;
    NSetOpponentTime;
  end
  else
  begin
    NSetOpponentTime;
    NSetYouTime;
  end;

  SetClock;
end;


procedure TManager.ConnectorHandler(e: TConnectorEvent; d1: pointer = nil; d2: pointer = nil);
var
  strCmd: string;
  strLeft: string;
begin
  case e of
    ceConnected:
    begin
      if (Assigned(m_ConnectingForm)) then
        m_ConnectingForm.Shut;
      RSendData(CMD_VERSION + ' ' + IntToStr(CHESS4NET_VERSION));
    end;

    ceDisconnected:
    begin
      if (not Connector.connected) then
        exit;

      if (Transmittable) then
      begin
        m_Dialogs.CloseNoneDialogs;
        m_Dialogs.MessageDlg(TLocalizer.Instance.GetMessage(34), mtCustom,
          [mbOK], mfMsgLeave); // Broadcaster leaves. Transmition will be closed.
      end;

      case ChessBoard.Mode of
        mView:
        begin
          m_Dialogs.MessageDlg(TLocalizer.Instance.GetMessage(5), mtCustom, [mbOK],
            mfMsgLeave); // 'Your opponent leaves.'
        end;
        mGame:
        begin
{$IFDEF GAME_LOG}
          FWriteToGameLog('*');
          FlushGameLog;
{$ENDIF}
          m_Dialogs.MessageDlg(TLocalizer.Instance.GetMessage(6), mtWarning,
                             [mbOK], mfMsgLeave); // Your opponent leaves. The game is aborted.
        end;
      end;
    end; { ceDisconnected }

    ceError:
    begin
{$IFDEF GAME_LOG}
      if ChessBoard.Mode = mGame then
      begin
        FWriteToGameLog('*');
        FlushGameLog;
      end;
{$ENDIF}
      m_Dialogs.MessageDlg(TLocalizer.Instance.GetMessage(7), mtWarning,
                         [mbOk], mfMsgLeave); // An error during connection occured.
    end;
{$IFDEF QIP}
    ceQIPError:
    begin
      QIPConnectionError := TRUE;
      // TODO: Localize
      m_Dialogs.MessageDlg('Special message channel is not responding.' + sLineBreak +
                         'This can happen due to the following reasons:' + sLineBreak +
                         '  1) Your partner is using an IM other than QIP Infium. OR' + sLineBreak +
                         '  2) Your partner is offline. OR' + sLineBreak +
                         '  3) Protocol doesn''t support multiple channels. OR' + sLineBreak +
                         '  4) Other reasons.' + sLineBreak +
                         'Chess4Net won''t start.', mtWarning, [mbOk], mfMsgLeave);
    end;
{$ENDIF}

    ceData:
    begin
      strCmd := PString(d1)^;
      repeat
        strLeft := LeftStr(strCmd, pos(CMD_DELIMITER, strCmd) - 1);
        strCmd := RightStr(strCmd, length(strCmd) - length(strLeft) - length(CMD_DELIMITER));

        RHandleConnectorDataCommand(strLeft);
      until (strCmd = '');

    end; {  ceData }

  end; { case ChessBoard.Mode }
end;


procedure TManager.RSetOpponentClientVersion(lwVersion: LongWord);
begin
  m_lwOpponentClientVersion := lwVersion;
end;


procedure TManager.RSetConnectionOccured;
begin
  m_bConnectionOccured := TRUE;
{$IFNDEF TESTING}
  with TURLVersionQuery.Create do
  begin
    OnQueryReady := FOnURLQueryReady;
  {$IFDEF SKYPE}
    Query(aidSkype, CHESS4NET_VERSION, osidWindows);
  {$ELSE}
    Free; // TODO: URL query for other clients
  {$ENDIF}
  end;
{$ENDIF}
end;


procedure TManager.FOnURLQueryReady(Sender: TURLVersionQuery);
begin
  if (not Assigned(Sender)) then
    exit;

  try
    if ((Sender.LastVersion <= m_iDontShowLastVersion)) then
      exit;

    if (Sender.Info <> '') then
    begin
      with TDontShowMessageDlg.Create(m_Dialogs, Sender.Info) do
      begin
        m_iQueriedDontShowLastVersion := Sender.LastVersion;
        Show;
      end;
    end;

  finally
    Sender.Free;
  end;

end;


procedure TManager.RUpdateChessBoardCaption;
begin
  if (m_bConnectionOccured and Assigned(ChessBoard)) then
    ChessBoard.Caption := RGetGameName;
end;


procedure TManager.RHandleConnectorDataCommand(sl: string);
var
  AMode: TMode;
  sr: string;
  strSavedCmd: string;
  wstrMsg: WideString;
begin
  strSavedCmd := sl;

  RSplitStr(sl, sl, sr);

  if (Assigned(ChessBoard)) then
    AMode := ChessBoard.Mode
  else
    AMode := mView;

  case AMode of
  mView:
    if (sl = CMD_VERSION) then
    begin
      RSplitStr(sr, sl, sr);
      RSetOpponentClientVersion(StrToIntDef(sl, CHESS4NET_VERSION));
      RSendData(CMD_WELCOME);
      if (m_lwOpponentClientVersion < CHESS4NET_VERSION) then
      begin
        m_Dialogs.MessageDlg(TLocalizer.Instance.GetMessage(8), mtWarning,
          [mbOK], mfNone); // Your opponent is using an older version of Chess4Net. ...
      end;
      // 2007.4 is the first client with a backward compatibility
      // For incompatible versions:
      // else RSendData(CMD_GOODBYE);
    end
    else if (sl = CMD_WELCOME) then
    begin
      RSendData(CMD_NICK_ID + ' ' + OpponentNickId);
      if (Assigned(ChessBoard)) then
        ChessBoard.InitPosition;
      SetClock;
      RSetConnectionOccured;
    end
    else if (sl = CMD_GOODBYE) then // For the future versions
    begin
      m_Dialogs.MessageDlg(TLocalizer.Instance.GetMessage(9) , mtWarning, [mbOK], mfIncompatible); // The current version of Chess4Net is incompatible ...
    end
    else if (sl = CMD_START_GAME) then
    begin
      with ChessBoard do
      begin
        if (Transmittable) then
          m_Dialogs.CloseNoneDialogs;
        // Starting from 2007.6 only white can start the game
        if ((m_lwOpponentClientVersion >= 200706) and (_PlayerColor = fcWhite) and
            (not Transmittable)) then
        begin
          ChangeColor;
        end;
        SetClock;
        ResetMoveList;
        move_done:= FALSE;
        TakebackGame.Enabled := FALSE;
        Mode := mGame;
        SwitchClock(PositionColor);
{$IFDEF GAME_LOG}
        FInitGameLog;
{$ENDIF}
      end;
      RRetransmit(strSavedCmd);
    end
    else if (sl = CMD_START_ADJOURNED_GAME) then
    begin
      FStartAdjournedGame;
      RRetransmit(CMD_GAME_CONTEXT + ' ' + RGetGameContextStr);
      RRetransmit(CMD_CONTINUE_GAME);
    end
    else if (sl = CMD_CONTINUE_GAME) then
    begin
      if (Transmittable) then
      begin
        m_Dialogs.CloseNoneDialogs;
        ChessBoard.Mode := mGame;
        ContinueGame;
      end;
    end
    else if (sl = CMD_ALLOW_TAKEBACKS) then
    begin
      RSplitStr(sr, sl, sr);
      opponent_takebacks := (sl = '1');
      TakebackGame.Visible := (opponent_takebacks or ChessBoard.pTrainingMode);
    end
    else if (sl = CMD_CAN_PAUSE_GAME) then
    begin
      RSplitStr(sr, sl, sr);
      can_pause_game := (sl = '1');
      GamePause.Visible := can_pause_game;
    end
    else if (sl = CMD_CAN_ADJOURN_GAME) then
    begin
      RSplitStr(sr, sl, sr);
      can_adjourn_game := (sl = '1');
    end
    else if (sl = CMD_SET_CLOCK) then
    begin
      SetClock(sr);
      RRetransmit(CMD_SET_CLOCK + ' ' + ClockToStr);
    end
    else if (sl = CMD_SET_TRAINING) then
    begin
      RSplitStr(sr, sl, sr);
      ChessBoard.pTrainingMode := (sl = '1');
      TakebackGame.Visible := (opponent_takebacks or ChessBoard.pTrainingMode);
    end
    else if (sl = CMD_GAME_OPTIONS) then // 2007.4
    begin
      SetClock(sr);
      RSplitStr(sr, sl, sr);
      opponent_takebacks := (sl = '1');
      RSplitStr(sr, sl, sr);
      ChessBoard.pTrainingMode := (sl = '1');
      TakebackGame.Visible := (opponent_takebacks or ChessBoard.pTrainingMode);
    end
    else if (sl = CMD_SET_ADJOURNED) then // 2008.1
    begin
      if ((AdjournedStr = '') or (CompareStr(PlayerNickId, OpponentNickId) > 0)) then
      begin
        if (pos('&w&', sr) > 0) then
          sr := StringReplace(sr, '&w&', '&b&', []) // White -> Black
        else
          sr := StringReplace(sr, '&b&', '&w&', []); // Black -> White
        AdjournedStr := sr;
      end;
    end
    else if (sl = CMD_CHANGE_COLOR) then
    begin
      ChangeColor;
      RRetransmit(strSavedCmd);
    end
    else if (sl = CMD_NICK_ID) then
    begin
      m_strPlayerNickId := sr;
      if (CompareStr(PlayerNickId, OpponentNickId) < 0) then
      begin
        StartStandartGameConnected.Enabled := TRUE;
        StartPPRandomGameConnected.Enabled := TRUE;
        _PlayerColor := fcWhite;
        if (not FReadCommonSettings(TRUE)) then
          RSendData(CMD_NO_SETTINGS);
      end
      else
      begin
        StartStandartGameConnected.Enabled := FALSE;
        StartPPRandomGameConnected.Enabled := FALSE;
        _PlayerColor := fcBlack;
        FReadCommonSettings(FALSE);
      end; // if CompareStr

      RUpdateChessBoardCaption;
    end
    else if (sl = CMD_POSITION) then
    begin
      if (Assigned(ChessBoard)) then
        ChessBoard.SetPosition(sr);
      RRetransmit(strSavedCmd);
    end
    else if (sl = CMD_NO_SETTINGS) then
    begin
      FReadCommonSettings(TRUE);
    end
    else if (sl = CMD_TRANSMITTING) then
    begin
      m_Dialogs.MessageDlg(TLocalizer.Instance.GetMessage(33),
        mtCustom, [mbOK], mfMsgLeave); // Game transmition is not supported by this client!
    end;

  mGame:
    if (sl = CMD_DRAW) then
    begin
      m_Dialogs.MessageDlg(TLocalizer.Instance.GetMessage(10), mtConfirmation,
        [mbYes, mbNo], mfMsgDraw) // Draw?
    end
    else if (sl = CMD_ABORT) then
    begin
      m_Dialogs.MessageDlg(TLocalizer.Instance.GetMessage(11), mtConfirmation,
        [mbYes, mbNo], mfMsgAbort); // Can we abort the game?
    end
    else if (sl = CMD_RESIGN) then
    begin
      FExitGameMode;
{$IFDEF GAME_LOG}
      if (_PlayerColor = fcWhite) then
        FWriteToGameLog(sLineBreak + 'Black resigns' + sLineBreak + '1 - 0')
      else
        FWriteToGameLog(sLineBreak + 'White resigns' + sLineBreak + '0 - 1');
      FlushGameLog;
{$ENDIF}
      if (Transmittable) then
      begin
        RSplitStr(sr, sl, sr);
        if (sl = 'w') then
          wstrMsg := TLocalizer.Instance.GetMessage(31) // White resigns.
        else // (sl = 'b')
          wstrMsg := TLocalizer.Instance.GetMessage(32) // Black resigns.
      end
      else
        wstrMsg := TLocalizer.Instance.GetMessage(12); // I resign. You win this game. Congratulations!

      m_Dialogs.MessageDlg(wstrMsg, mtCustom, [mbOK], mfNone);
      ChessBoard.WriteGameToBase(grWin);

      RRetransmit(CMD_RESIGN + IfThen((_PlayerColor = fcWhite), ' b', ' w'));
    end
    else if (sl = CMD_ABORT_ACCEPTED) then
    begin
      FExitGameMode;
{$IFDEF GAME_LOG}
      FWriteToGameLog('*');
      FlushGameLog;
{$ENDIF}
      m_Dialogs.MessageDlg(TLocalizer.Instance.GetMessage(13), mtCustom,
        [mbOK], mfNone); // The game is aborted.
      RRetransmit(strSavedCmd); 
    end
    else if (sl = CMD_ABORT_DECLINED) then
    begin
      m_Dialogs.MessageDlg(TLocalizer.Instance.GetMessage(14),
        mtCustom, [mbOK], mfNone) // Sorry, but we have to finish this game.
    end
    else if (sl = CMD_DRAW_ACCEPTED) then
    begin
      FExitGameMode;
{$IFDEF GAME_LOG}
      FWriteToGameLog('=' + sLineBreak + '1/2 - 1/2');
      FlushGameLog;
{$ENDIF}
      m_Dialogs.MessageDlg(TLocalizer.Instance.GetMessage(15), mtCustom, [mbOK], mfNone); // The game is drawn.
      ChessBoard.WriteGameToBase(grDraw);

      RRetransmit(strSavedCmd);      
    end
    else if (sl = CMD_DRAW_DECLINED) then
    begin
      m_Dialogs.MessageDlg(TLocalizer.Instance.GetMessage(16), mtCustom, [mbOK], mfNone) // No draw, sorry.
    end
    else if (sl = CMD_SWITCH_CLOCK) then
    begin
      with ChessBoard do
      begin
        RSplitStr(sr, sl, sr);

        if (Transmittable) then
        begin
          if (PositionColor = fcWhite) then
            Time[fcBlack] := TChessClock.ConvertFromFullStr(sl)
          else
            Time[fcWhite] := TChessClock.ConvertFromFullStr(sl);
        end
        else
        begin
          if (_PlayerColor = fcWhite) then
            Time[fcBlack] := TChessClock.ConvertFromFullStr(sl)
          else
            Time[fcWhite] := TChessClock.ConvertFromFullStr(sl);
        end;
      end; // with
      RRetransmit(strSavedCmd);
    end
    else if (sl = CMD_FLAG) then
      with ChessBoard do
      begin
        if (Time[_PlayerColor] = 0.0) then
        begin
          RSendData(CMD_FLAG_YES);
          RRetransmit(CMD_FLAG_YES);

          FExitGameMode;
{$IFDEF GAME_LOG}
          if (_PlayerColor = fcWhite) then
            FWriteToGameLog(sLineBreak + 'White forfeits on time')
          else
            FWriteToGameLog(sLineBreak + 'Black forfeits on time');
          FlushGameLog;
{$ENDIF}
          m_Dialogs.MessageDlg(TLocalizer.Instance.GetMessage(17), mtCustom, [mbOK], mfNone); // You forfeited on time.
          ChessBoard.WriteGameToBase(grLostTime);
        end
        else
          RSendData(CMD_FLAG_NO);
      end // with
    else
    if (sl = CMD_FLAG_YES) then
    begin
      FExitGameMode;
{$IFDEF GAME_LOG}
      if (_PlayerColor = fcWhite) then
        FWriteToGameLog(sLineBreak + 'Black forfeits on time')
      else
        FWriteToGameLog(sLineBreak + 'White forfeits on time');
      FlushGameLog;
{$ENDIF}
      if (Transmittable) then
      begin
        if (_PlayerColor = fcWhite) then
          wstrMsg := TLocalizer.Instance.GetMessage(29) // Black forfeits on time.
        else
          wstrMsg := TLocalizer.Instance.GetMessage(30); // White forfeits on time.
      end
      else
        wstrMsg := TLocalizer.Instance.GetMessage(18); // Your opponent forfeited on time.

      m_Dialogs.MessageDlg(wstrMsg, mtCustom, [mbOK], mfNone);
      ChessBoard.WriteGameToBase(grWinTime);

      RRetransmit(strSavedCmd);
    end
    else if (sl = CMD_FLAG_NO) then
      with ChessBoard do
      begin
        case _PlayerColor of
          fcWhite:
            if (Time[fcBlack] = 0.0) then
              RSendData(CMD_FLAG);
          fcBlack:
            if (Time[fcWhite] = 0.0) then
              RSendData(CMD_FLAG);
        end // case
      end // with
    else if (sl = CMD_PAUSE_GAME) then
    begin
      m_Dialogs.MessageDlg(TLocalizer.Instance.GetMessage(19), mtConfirmation,
        [mbYes, mbNo], mfCanPause); // Can we pause the game?
    end
    else if (sl = CMD_PAUSE_GAME_YES) then
    begin
      PauseGame;
      RRetransmit(strSavedCmd);
    end
    else if (sl = CMD_PAUSE_GAME_NO) then
    begin
      m_Dialogs.MessageDlg(TLocalizer.Instance.GetMessage(20), mtCustom,
        [mbOk], mfNone); // No pause, sorry.
    end
    else if (sl = CMD_CONTINUE_GAME) then
    begin
      if (Assigned(m_ContinueForm)) then
        m_ContinueForm.Shut;
      if (Transmittable) then
        m_Dialogs.CloseNoneDialogs;
      ContinueGame;
      RRetransmit(strSavedCmd); 
    end
    else if (sl = CMD_TAKEBACK) then
    begin
      if (you_takebacks or ChessBoard.pTrainingMode) then
      begin
        m_Dialogs.MessageDlg(TLocalizer.Instance.GetMessage(21),
                           mtConfirmation, [mbYes, mbNo], mfMsgTakeBack); // 'May I take back last move?'
      end
      else
        RSendData(CMD_TAKEBACK_NO)
    end
    else if (sl = CMD_ADJOURN_GAME) then
    begin
      m_Dialogs.MessageDlg(TLocalizer.Instance.GetMessage(22),
                             mtConfirmation, [mbYes, mbNo], mfMsgAdjourn); // Can we adjourn this game?
    end
    else if (sl = CMD_ADJOURN_GAME_YES) then
    begin
      FAdjournGame;
      RRetransmit(strSavedCmd);
    end
    else if (sl = CMD_ADJOURN_GAME_NO) then
    begin
      m_Dialogs.MessageDlg(TLocalizer.Instance.GetMessage(23), mtCustom, [mbOk],
        mfNone); // No adjourns, sorry.
    end
    else
    if (sl = CMD_TAKEBACK_YES) then
    begin
      ChessBoard.TakeBack;
      FBuildAdjournedStr;
      TakebackGame.Enabled:= (ChessBoard.NMoveDone > 0);
{$IFDEF GAME_LOG}
      FWriteToGameLog(' <takeback>');
{$ENDIF}
      ChessBoard.SwitchClock(ChessBoard.PositionColor);
      RRetransmit(strSavedCmd);
    end
    else if (sl = CMD_TAKEBACK_NO) then
    begin
      m_Dialogs.MessageDlg(TLocalizer.Instance.GetMessage(24), mtCustom,
        [mbOK], mfNone); // Sorry, no takebacks!
    end
    else if (sl = CMD_POSITION) then
    begin
      if (CompareStr(PlayerNickId, OpponentNickId) > 0) then
      begin
        ChessBoard.StopClock;
        ChessBoard.Mode := mView;
        ChessBoard.SetPosition(sr);
      end;
      RRetransmit(strSavedCmd);
    end
    else
    begin
      with ChessBoard do
      begin
        if ((_PlayerColor <> PositionColor) or Transmittable) then
        begin
          if (DoMove(sl)) then
          begin
{$IFDEF GAME_LOG}
            if ((PositionColor = fcBlack) or (not move_done)) then
            begin
              FWriteToGameLog(' ' + IntToStr(NMoveDone) + '.');
              if (PositionColor = fcWhite) then
                FWriteToGameLog(' ...');
            end;
            FWriteToGameLog(' ' + sl);
{$ENDIF}
            move_done := TRUE;
            TakebackGame.Enabled := TRUE;
            FBuildAdjournedStr; // AdjournedStr ïîìå÷àåòñÿ òîëüêî ïðè âõîäÿùåì õîäå ïðîòèâíèêà
          end; // if (DoMove...
        end; // if (_Player...
      end; // with ChessBoard
      
      RRetransmit(strSavedCmd);
    end;
  end; // case ChessBoard.Mode
end;


procedure TManager.RRetransmit(const strCmd: string);
begin
end;


procedure TManager.ROnDestroy;
begin
  TLocalizer.Instance.DeleteSubscriber(self);

  if (m_bConnectionOccured) then
  begin
    FWritePrivateSettings;
    if (not Transmittable) then
      FWriteCommonSettings;
  end;

  m_ExtBaseList.Free;

  if (Assigned(ChessBoard)) then
  begin
    ChessBoard.Release;
    m_ChessBoard := nil;
  end;
  m_Dialogs.Free;

  TIniSettings.FreeInstance;
end;


procedure TManager.FormDestroy(Sender: TObject);
begin
  ROnDestroy;
end;


procedure TManager.LookFeelOptionsActionExecute(Sender: TObject);
var
  lookFeelOptionsForm: TLookFeelOptionsForm;
begin
  lookFeelOptionsForm := (m_Dialogs.CreateDialog(TLookFeelOptionsForm) as TLookFeelOptionsForm);
  with lookFeelOptionsForm, ChessBoard do
  begin
    AnimationComboBox.ItemIndex := ord(animation);
    HilightLastMoveBox.Checked := LastMoveHilighted;
    FlashIncomingMoveBox.Checked := FlashOnMove;
    CoordinatesBox.Checked := CoordinatesShown;
    StayOnTopBox.Checked := StayOnTop;
    ExtraExitBox.Checked := extra_exit;
  end;
  lookFeelOptionsForm.Show;
end;


procedure TManager.AbortGameClick(Sender: TObject);
begin
  RSendData(CMD_ABORT);
end;

procedure TManager.DrawGameClick(Sender: TObject);
begin
  RSendData(CMD_DRAW);
end;

procedure TManager.ResignGameClick(Sender: TObject);
begin
  m_Dialogs.MessageDlg(TLocalizer.Instance.GetMessage(25),
                mtConfirmation, [mbYes, mbNo], mfMsgResign); // Do you really want to resign?
end;


procedure TManager.ChangeColorConnectedClick(Sender: TObject);
begin
  if (Transmittable) then
  begin
    ChangeColor;
  end
  else if (ChessBoard.Mode = mView) then
  begin
    ChangeColor;

    RSendData(CMD_CHANGE_COLOR);
    RRetransmit(CMD_CHANGE_COLOR);
  end;
end;


procedure TManager.GameOptionsConnectedClick(Sender: TObject);
var
  GameOptionsForm: TGameOptionsForm;
  i: integer;
begin
  GameOptionsForm := (m_Dialogs.CreateDialog(TGameOptionsForm) as TGameOptionsForm);
  with GameOptionsForm do
  begin
    EqualTimeCheckBox.Checked := ((you_unlimited = opponent_unlimited) and
      (you_time = opponent_time) and (you_inc = opponent_inc));
    YouUnlimitedCheckBox.Checked:= you_unlimited;
    OpponentUnlimitedCheckBox.Checked:= opponent_unlimited;
    YouMinUpDown.Position := you_time;
    YouIncUpDown.Position := you_inc;
    OpponentMinUpDown.Position := opponent_time;
    OpponentIncUpDown.Position := opponent_inc;
    AutoFlagCheckBox.Checked := ChessBoard.AutoFlag;
    TakeBackCheckBox.Checked := you_takebacks;
    TrainingEnabledCheckBox.Checked := ChessBoard.pTrainingMode;
    for i := 1 to m_ExtBaseList.Count - 1 do
    begin
      ExtBaseComboBox.Items.Append(m_ExtBaseList[i]);
      if (m_strExtBaseName = m_ExtBaseList[i]) then
        ExtBaseComboBox.ItemIndex := i;
    end;
    UsrBaseCheckBox.Checked := ChessBoard.pUseUserBase;
    GamePauseCheckBox.Checked := (can_pause_game and (m_lwOpponentClientVersion >= 200706));
    GameAdjournCheckBox.Checked := (can_adjourn_game and (m_lwOpponentClientVersion >= 200801));
    Show;
  end; // with
end;


procedure TManager.StartStandartGameConnectedClick(Sender: TObject);
var
  strPositionCmd: string;
begin
  with ChessBoard do
    begin
      SetClock;
      InitPosition;
      ResetMoveList;

      strPositionCmd := CMD_POSITION + ' ' + GetPosition;
      RSendData(strPositionCmd);
      RSendData(CMD_START_GAME);

      move_done:= FALSE;
      TakebackGame.Enabled := FALSE;
      Mode := mGame;
      SwitchClock(ChessBoard.PositionColor);

      RRetransmit(strPositionCmd);
      RRetransmit(CMD_START_GAME);
    end;
{$IFDEF GAME_LOG}
  FInitGameLog;
{$ENDIF}
end;


procedure TManager.SetClock;
begin
  if (not Assigned(ChessBoard)) then
    exit;
     
  with ChessBoard do
  begin
    Unlimited[_PlayerColor] := you_unlimited;
    Time[_PlayerColor] := EncodeTime(you_time div 60, you_time mod 60, 0,0);
    if (_PlayerColor = fcWhite) then
    begin
      Unlimited[fcBlack] := opponent_unlimited;
      Time[fcBlack] := EncodeTime(opponent_time div 60,
                               opponent_time mod 60, 0,0);
    end
    else
    begin
      Unlimited[fcWhite] := opponent_unlimited;
      Time[fcWhite] := EncodeTime(opponent_time div 60,
                               opponent_time mod 60, 0,0);
    end;
  end;
end;

procedure TManager.RSetChessBoardToView;
var
  clockTime: string;
begin
  with ChessBoard do
  begin
    clockTime := NO_CLOCK_TIME;
    SetClock(clockTime);
    Mode := mView;
    Caption := CHESS4NET_TITLE;
    ChessBoard.icon := Chess4NetIcon;
    InitPosition;

    Left:= (Screen.Width - Width) div 2;
    Top:= (Screen.Height - Height) div 2;
    Show;
  end;
end;


procedure TManager.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  if (Assigned(Connector) and Connector.connected) then
  begin
    if (Assigned(m_Dialogs)) then
    begin
      m_Dialogs.MessageDlg(TLocalizer.Instance.GetMessage(26), mtConfirmation, [mbYes, mbNo], mfMsgClose); // Do you want to exit?
      Action:= caNone;
    end
    else
      Release;
  end
  else
//    Release;    
    Action := caFree;
end;


procedure TManager.RReleaseWithConnectorGracefully;
begin
  ConnectorTimer.Enabled := TRUE;
  if (Assigned(Connector)) then
    Connector.Close;
end;


procedure TManager.ConnectorTimerTimer(Sender: TObject);
begin
  ConnectorTimer.Enabled := FALSE;
  Release;
end;


procedure TManager.StartPPRandomGameConnectedClick(Sender: TObject);
var
  strPositionCmd: string;
begin
  with ChessBoard do
    begin
      SetClock;
      PPRandom;
      ResetMoveList;

      strPositionCmd := CMD_POSITION + ' ' + GetPosition;
      RSendData(strPositionCmd);
      RSendData(CMD_START_GAME);

      Mode := mGame;
      move_done := FALSE;
      TakebackGame.Enabled := FALSE;
      SwitchClock(ChessBoard.PositionColor);

      RRetransmit(strPositionCmd);
      RRetransmit(CMD_START_GAME);
    end;
{$IFDEF GAME_LOG}
  FInitGameLog;
{$ENDIF}
end;


procedure TManager.TakebackGameClick(Sender: TObject);
begin
  RSendData(CMD_TAKEBACK);
end;


constructor TManager.RCreate;
begin
//  inherited Create(Application);
  inherited Create(nil);
end;


{$IFDEF AND_RQ}
class function TManager.Create: TManager;
begin
  Result := TManagerDefault.Create;
end;
{$ENDIF}

{$IFDEF QIP}
class function TManager.Create(const accName: WideString; const protoDllHandle: integer): TManager;
begin
  Result := TManagerDefault.Create(accName, protoDllHandle);
end;
{$ENDIF}

{$IFDEF TRILLIAN}
class function TManager.Create(const vContactlistEntry: TTtkContactListEntry): TManager;
begin
  Result := TManagerDefault.Create(vContactlistEntry);
end;
{$ENDIF}

procedure TManager.DialogFormHandler(modSender: TModalForm; msgDlgID: TModalFormID);
var
  modRes: TModalResult;
  s, prevClock: string;
  strCmd: string;
begin
  modRes := modSender.ModalResult;
  case msgDlgID of
    mfNone: ;

    mfMsgClose:
    begin
      if modRes = mrYes then
      begin
{$IFDEF GAME_LOG}
        if ChessBoard.Mode = mGame then
        begin
          FWriteToGameLog('*');
          FlushGameLog;
        end;
{$ENDIF}
{$IFDEF SKYPE}
        FShowCredits;
{$ENDIF}
        Release;
      end;
    end;

    mfMsgLeave, mfIncompatible:
    begin
{$IFDEF SKYPE}
      FShowCredits;
{$ENDIF}
      if (Assigned(Connector) and Connector.Connected) then
        RReleaseWithConnectorGracefully
      else
        Close;
    end;

    mfMsgAbort:
    begin
      if ChessBoard.Mode = mGame then
      begin
        if (modRes = mrNo) or (modRes = mrNone) then
          RSendData(CMD_ABORT_DECLINED)
        else
        begin
          RSendData(CMD_ABORT_ACCEPTED);
          RRetransmit(CMD_ABORT_ACCEPTED);
          FExitGameMode;
{$IFDEF GAME_LOG}
          FWriteToGameLog('*');
          FlushGameLog;
{$ENDIF}
          m_Dialogs.MessageDlg(TLocalizer.Instance.GetMessage(13), mtCustom,
            [mbOK], mfNone); // The game is aborted.
        end;
      end;
    end;

    mfMsgResign:
    begin
	    if ChessBoard.Mode = mGame then
      begin
        if modRes = mrYes then
        begin
          FExitGameMode;
          RSendData(CMD_RESIGN);
          RRetransmit(CMD_RESIGN + IfThen((_PlayerColor = fcWhite), ' w', ' b'));
          ChessBoard.WriteGameToBase(grLost);
{$IFDEF GAME_LOG}
          if (_PlayerColor = fcWhite) then
            FWriteToGameLog(sLineBreak + 'White resigns' + sLineBreak + '0 - 1')
          else
            FWriteToGameLog(sLineBreak + 'Black resigns' + sLineBreak + '1 - 0');
          FlushGameLog;
{$ENDIF}
        end;
      end;
    end;

    mfMsgDraw:
    begin
      if ChessBoard.Mode = mGame then
      begin
        if (modRes = mrNo) or (modRes = mrNone) then
          RSendData(CMD_DRAW_DECLINED)
        else
        begin
          RSendData(CMD_DRAW_ACCEPTED);
          RRetransmit(CMD_DRAW_ACCEPTED);

          FExitGameMode;
{$IFDEF GAME_LOG}
            FWriteToGameLog('=' + sLineBreak + '1/2 - 1/2');
            FlushGameLog;
{$ENDIF}
          m_Dialogs.MessageDlg(TLocalizer.Instance.GetMessage(15), mtCustom, [mbOK], mfNone);
          ChessBoard.WriteGameToBase(grDraw); // The game is drawn.
        end;
      end;
    end;

    mfMsgTakeBack:
    begin
      if ChessBoard.Mode = mGame then
      begin
        if modRes = mrYes then
        begin
          RSendData(CMD_TAKEBACK_YES);
          RRetransmit(CMD_TAKEBACK_YES);

          ChessBoard.TakeBack;
          FBuildAdjournedStr;
          TakebackGame.Enabled:= (ChessBoard.NMoveDone > 0);
{$IFDEF GAME_LOG}
          FWriteToGameLog(' <takeback>');
{$ENDIF}
          ChessBoard.SwitchClock(ChessBoard.PositionColor);
        end
        else
          RSendData(CMD_TAKEBACK_NO);
      end;
    end;

    mfMsgAdjourn:
    begin
      if ChessBoard.Mode = mGame then
      begin
        if modRes = mrYes then
        begin
          RSendData(CMD_ADJOURN_GAME_YES);
          RRetransmit(CMD_ADJOURN_GAME_YES);
          FAdjournGame;
        end
        else
          RSendData(CMD_ADJOURN_GAME_NO);
      end;
    end;

    mfConnecting:
    begin
      m_ConnectingForm := nil;
      if modRes = mrAbort then
        Close; // ConnectionAbort;
    end;

    mfGameOptions:
    begin
      if (ChessBoard.Mode <> mGame) and (modRes = mrOK) then
        with (modSender as TGameOptionsForm) do
        begin
          prevClock := ClockToStr;
          you_unlimited := YouUnlimitedCheckBox.Checked;
          opponent_unlimited := OpponentUnlimitedCheckBox.Checked;
          you_time := StrToInt(YouMinEdit.Text);
          you_inc := StrToInt(YouIncEdit.Text);
          opponent_time := StrToInt(OpponentMinEdit.Text);
          opponent_inc := StrToInt(OpponentIncEdit.Text);
          ChessBoard.AutoFlag := AutoFlagCheckBox.Checked;
          // Îòîáðàæåíèå íà äîñêå
          SetClock;
          // ñèíõðîíèçàöèÿ âðåìåíè ó îïïîíåíòà
          s := ClockToStr;
          if (m_lwOpponentClientVersion >= 200705) then
          begin
            if (prevClock <> s) then
            begin
              strCmd := CMD_SET_CLOCK + ' ' + s;
              RSendData(strCmd);
              RRetransmit(strCmd);
            end;
            RSendData(CMD_ALLOW_TAKEBACKS + IfThen(TakeBackCheckBox.Checked, ' 1', ' 0'));
          end;
          you_takebacks := TakeBackCheckBox.Checked;
          if (m_lwOpponentClientVersion >= 200706) then
          begin
            if can_pause_game <> GamePauseCheckBox.Checked then
            begin
              can_pause_game := GamePauseCheckBox.Checked;
              RSendData(CMD_CAN_PAUSE_GAME + IfThen(can_pause_game, ' 1', ' 0'))
            end;
          end;
          if (m_lwOpponentClientVersion >= 200801) then
          begin
            if can_adjourn_game <> GameAdjournCheckBox.Checked then
            begin
              can_adjourn_game := GameAdjournCheckBox.Checked;
              RSendData(CMD_CAN_ADJOURN_GAME + IfThen(can_adjourn_game, ' 1', ' 0'))
            end;
          end;
          // Training mode
          if (m_lwOpponentClientVersion >= 200705) and (ChessBoard.pTrainingMode <> TrainingEnabledCheckBox.Checked) then
          begin
            RSendData(CMD_SET_TRAINING + IfThen(TrainingEnabledCheckBox.Checked, ' 1', ' 0'));
          end;
          ChessBoard.pTrainingMode := TrainingEnabledCheckBox.Checked;
          m_strExtBaseName := m_ExtBaseList[ExtBaseComboBox.ItemIndex];
          if (m_strExtBaseName <> '') then
            ChessBoard.SetExternalBase(Chess4NetPath + m_strExtBaseName)
          else
            ChessBoard.UnsetExternalBase;
          ChessBoard.pUseUserBase := UsrBaseCheckBox.Checked;
          GamePause.Visible := can_pause_game;
          TakebackGame.Visible := (ChessBoard.pTrainingMode or opponent_takebacks);

          if (m_lwOpponentClientVersion < 200705) then // 2007.4
          begin
            if ChessBoard.pTrainingMode then
              s := s + ' 1 1'
            else
              s := s + IfThen(you_takebacks, ' 1 0', ' 0 0');
            RSendData(CMD_GAME_OPTIONS + ' ' + s);
          end;
        end;
    end;

    mfLookFeel:
    begin
      with (modSender as TLookFeelOptionsForm), ChessBoard do
      begin
        animation := TAnimation(AnimationComboBox.ItemIndex);
        LastMoveHilighted := HilightLastMoveBox.Checked;
        FlashOnMove := FlashIncomingMoveBox.Checked;
        CoordinatesShown := CoordinatesBox.Checked;
        StayOnTop := StayOnTopBox.Checked;
        extra_exit := ExtraExitBox.Checked;
      end;
    end;

    mfContinue:
    begin
      m_ContinueForm := nil;
      if modRes = mrOk then
      begin
        RSendData(CMD_CONTINUE_GAME);
        RRetransmit(CMD_CONTINUE_GAME);
        ContinueGame;
      end;
    end;

    mfCanPause:
    begin
      if modRes = mrYes then
      begin
        RSendData(CMD_PAUSE_GAME_YES);
        RRetransmit(CMD_PAUSE_GAME_YES);
        PauseGame;
      end
      else // modRes = mrNo
        RSendData(CMD_PAUSE_GAME_NO);
    end;

    mfDontShowDlg:
    begin
      if ((modSender as TDontShowMessageDlg).DontShow) then
        m_iDontShowLastVersion := m_iQueriedDontShowLastVersion;
    end;

  end;
end;

{$IFDEF GAME_LOG}
procedure TManager.FInitGameLog;
var
  s: string;
begin
  if ((not m_bConnectionOccured) or m_bTransmittable) then
    exit; 

  gameLog := '';

  LongTimeFormat := HOUR_TIME_FORMAT;
  FWriteToGameLog('[' + DateTimeToStr(Now) + ']' + sLineBreak);

  FWriteToGameLog(RGetGameName);

  if not (you_unlimited and opponent_unlimited) then
  begin
    FWriteToGameLog(' (');
    case _PlayerColor of
      fcWhite:
      begin
        if (not you_unlimited) then
        begin
          FWriteToGameLog(IntToStr(you_time));
          if (you_inc > 0) then
            FWriteToGameLog('.' + IntToStr(you_inc));
        end
        else
          FWriteToGameLog('inf');

        FWriteToGameLog(':');

        if (not opponent_unlimited) then
        begin
          FWriteToGameLog(IntToStr(opponent_time));
          if (opponent_inc > 0) then
            FWriteToGameLog('.' + IntToStr(opponent_inc));
        end
        else
          FWriteToGameLog('inf');
      end;

      fcBlack:
      begin
        if (not opponent_unlimited) then
        begin
          FWriteToGameLog(IntToStr(opponent_time));
          if (opponent_inc > 0) then
            FWriteToGameLog('.' + IntToStr(opponent_inc));
        end
        else
          FWriteToGameLog('inf');

        FWriteToGameLog(':');

        if (not you_unlimited) then
        begin
          FWriteToGameLog(IntToStr(you_time));
          if (you_inc > 0) then
            FWriteToGameLog('.' + IntToStr(you_inc));
        end
        else
          FWriteToGameLog('inf');
      end;
    end;
    FWriteToGameLog(')');
  end;
  FWriteToGameLog(sLineBreak);

  s := ChessBoard.GetPosition;
  if (s <> INITIAL_CHESS_POSITION) then
    FWriteToGameLog(s + sLineBreak);
end;


procedure TManager.FWriteToGameLog(const s: string);
begin
  if ((not m_bConnectionOccured) or m_bTransmittable) then
    exit; 

  gameLog := gameLog + s;
end;


procedure TManager.FlushGameLog;
var
  gameLogFile: TextFile;
begin
  if ((not m_bConnectionOccured) or m_bTransmittable) then
    exit; 

  if (not move_done) then
    exit;

  AssignFile(gameLogFile, Chess4NetGamesLogPath + GAME_LOG_FILE);
{$I-}
  Append(gameLogFile);
{$I+}
  if (IOResult <> 0) then
    begin
      Rewrite(gameLogFile);
      if (IOResult = 0) then
        writeln(gameLogFile, gameLog);
    end
  else
    writeln(gameLogFile, sLineBreak + gameLog);

  CloseFile(gameLogFile);
{$IFDEF SKYPE}
  CreateLinkForGameLogFile;
{$ENDIF}
end;
{$ENDIF}

procedure TManager.FPopulateExtBaseList;
var
  sr: TSearchRec;
  extBaseName: string;
begin
  m_ExtBaseList.Append('');
  if (FindFirst(Chess4NetPath + '*.pos', faAnyFile, sr) = 0) then
  begin
    repeat
      extBaseName := LeftStr(sr.Name, length(sr.Name) - length(ExtractFileExt(sr.Name)));
      if (extBaseName <> USR_BASE_NAME) and FileExists(Chess4NetPath + extBaseName + '.mov') then
        m_ExtBaseList.Append(extBaseName);
    until FindNext(sr) <> 0;
  end; // if
  FindClose(sr);
end;


procedure TManager.RCreateAndPopulateExtBaseList;
begin
  m_ExtBaseList := TStringList.Create;
  FPopulateExtBaseList;
  m_strExtBaseName := '';
end;


procedure TManager.RReadPrivateSettings;
var
  initialClockTime: string;
begin
  // Îáùèå íàñòðîéêè ïî óìîë÷àíèþ
  initialClockTime := INITIAL_CLOCK_TIME;
  SetClock(initialClockTime);

  ChessBoard.AutoFlag := TRUE;
  you_takebacks := FALSE;
  opponent_takebacks := FALSE;

  // Reading private settings
  ChessBoard.animation := TIniSettings.Instance.Animation;
  ChessBoard.LastMoveHilighted := TIniSettings.Instance.LastMoveHilighted;
  ChessBoard.FlashOnMove := TIniSettings.Instance.FlashOnMove;
  ChessBoard.CoordinatesShown := TIniSettings.Instance.CoordinatesShown;
  // TODO: read screen position and size
  ChessBoard.StayOnTop := TIniSettings.Instance.StayOnTop;
  extra_exit := TIniSettings.Instance.ExtraExit;
  TLocalizer.Instance.ActiveLanguage := TIniSettings.Instance.ActiveLanguage;
  m_iDontShowLastVersion := TIniSettings.Instance.DontShowLastVersion;
{$IFDEF SKYPE}
  m_bDontShowCredits := TIniSettings.Instance.DontShowCredits;
{$ENDIF}
end;


function TManager.FReadCommonSettings(setToOpponent: boolean): boolean;
var
  strClock: string;
  bFlag: boolean;
begin
  if (m_lwOpponentClientVersion < 200705) then // For 2007.4 common settings are not applied
  begin
    Result := TRUE;
    exit;
  end;

  Result := FALSE;

  TIniSettings.Instance.SetOpponentId(OpponentId);
  if (not TIniSettings.Instance.HasCommonSettings) then
    exit;

  if (setToOpponent) then
  begin
    if (_PlayerColor = TIniSettings.Instance.PlayerColor) then // Every time change the saved color to opposite one
    begin
      ChangeColor;
      RSendData(CMD_CHANGE_COLOR);
      RRetransmit(CMD_CHANGE_COLOR);
    end;

    strClock := TIniSettings.Instance.Clock;
    if (strClock <> ClockToStr) then
    begin
      SetClock(strClock);
      RSendData(CMD_SET_CLOCK + ' ' + ClockToStr);
    end;

    bFlag := TIniSettings.Instance.TrainingMode;
    if (ChessBoard.pTrainingMode <> bFlag) then
    begin
      ChessBoard.pTrainingMode := bFlag;
      RSendData(CMD_SET_TRAINING + IfThen(ChessBoard.pTrainingMode, ' 1', ' 0'));
    end;

    if (m_lwOpponentClientVersion >= 200706) then
    begin
      bFlag := TIniSettings.Instance.CanPauseGame;
      if (can_pause_game <> bFlag) then
      begin
        can_pause_game := bFlag;
        RSendData(CMD_CAN_PAUSE_GAME + IfThen(can_pause_game, ' 1', ' 0'));
      end;
    end; { if opponentClientVersion >= 200706}

    if (m_lwOpponentClientVersion >= 200801) then
    begin
      bFlag := TIniSettings.Instance.CanAdjournGame;
      if (can_adjourn_game <> bFlag) then
      begin
        can_adjourn_game := bFlag;
        RSendData(CMD_CAN_ADJOURN_GAME + IfThen(can_adjourn_game, ' 1', ' 0'));
      end;
    end; { opponentClientVersion >= 200801 }
  end; { if setToOpponent }

  m_strExtBaseName := TIniSettings.Instance.ExternalBaseName;
  if (m_strExtBaseName <> '') then
    ChessBoard.SetExternalBase(Chess4NetPath + m_strExtBaseName)
  else
    ChessBoard.UnsetExternalBase;

  ChessBoard.pUseUserBase := TIniSettings.Instance.UseUserBase;

  bFlag := TIniSettings.Instance.AllowTakebacks;
  if (you_takebacks <> bFlag) then
  begin
    you_takebacks := bFlag;
    RSendData(CMD_ALLOW_TAKEBACKS + IfThen(you_takebacks, ' 1', ' 0'));
  end;

  ChessBoard.AutoFlag := TIniSettings.Instance.AutoFlag;

  TakebackGame.Visible := (opponent_takebacks or ChessBoard.pTrainingMode);
  GamePause.Visible := can_pause_game;

  if (m_lwOpponentClientVersion >= 200801) then
  begin
    if (AdjournedStr <> '') then
    begin
      RSendData(CMD_SET_ADJOURNED + ' ' + AdjournedStr);
    end;
  end;

  Result := TRUE;
end;


procedure TManager.FWritePrivateSettings;
begin
  // Write private settings
  TIniSettings.Instance.Animation := ChessBoard.Animation;
  TIniSettings.Instance.LastMoveHilighted := ChessBoard.LastMoveHilighted;
  TIniSettings.Instance.FlashOnMove := ChessBoard.FlashOnMove;
  TIniSettings.Instance.CoordinatesShown := ChessBoard.CoordinatesShown;
  // TODO: write screen position
  TIniSettings.Instance.StayOnTop := ChessBoard.StayOnTop;
  TIniSettings.Instance.ExtraExit := extra_exit;
  TIniSettings.Instance.ActiveLanguage := TLocalizer.Instance.ActiveLanguage;
  if (m_iDontShowLastVersion > CHESS4NET_VERSION) then
    TIniSettings.Instance.DontShowLastVersion := m_iDontShowLastVersion;
{$IFDEF SKYPE}
  if (m_bDontShowCredits) then
    TIniSettings.Instance.DontShowCredits := m_bDontShowCredits;
{$ENDIF}
end;


procedure TManager.FWriteCommonSettings;
begin
  TIniSettings.Instance.SetOpponentId(OpponentId);

  TIniSettings.Instance.PlayerColor := _PlayerColor;
  TIniSettings.Instance.Clock := ClockToStr;
  TIniSettings.Instance.TrainingMode := ChessBoard.pTrainingMode;
  TIniSettings.Instance.ExternalBaseName := m_strExtBaseName;
  TIniSettings.Instance.UseUserBase := ChessBoard.pUseUserBase;
  TIniSettings.Instance.AllowTakebacks := you_takebacks;
  TIniSettings.Instance.CanPauseGame := can_pause_game;
  TIniSettings.Instance.CanAdjournGame := can_adjourn_game;
  TIniSettings.Instance.AutoFlag := ChessBoard.AutoFlag;
end;


function TManager.ClockToStr: string;
var
  s: string;
begin
  if (you_unlimited) then
    s := 'u'
  else
    s := IntToStr(you_time) + ' ' + IntToStr(you_inc);
  if (opponent_unlimited) then
    s := s + ' u'
  else
    s := s + ' ' + IntToStr(opponent_time) + ' ' + IntToStr(opponent_inc);

  Result := s;
end;


procedure TManager.ChangeColor;
begin
  with ChessBoard do
  begin
    if (_PlayerColor = fcWhite) then
    begin
      StartStandartGameConnected.Enabled := FALSE;
      StartPPRandomGameConnected.Enabled := FALSE;
      _PlayerColor := fcBlack;
    end
    else // fcBlack
    begin
      StartStandartGameConnected.Enabled := TRUE;
      StartPPRandomGameConnected.Enabled := TRUE;
      _PlayerColor := fcWhite;
    end;
    RUpdateChessBoardCaption;
    SetClock;
  end;
end;


procedure TManager.GamePauseClick(Sender: TObject);
begin
  RSendData(CMD_PAUSE_GAME);
end;


procedure TManager.PauseGame;
begin
  ChessBoard.StopClock;
  if (not Transmittable) then
  begin
    m_ContinueForm := (m_Dialogs.CreateDialog(TContinueForm) as TContinueForm);
    m_ContinueForm.Show;
  end;
end;


procedure TManager.ContinueGame;
begin
  ChessBoard.SwitchClock(ChessBoard.PositionColor);
end;

procedure TManager.AboutActionExecute(Sender: TObject);
begin
  ShowInfo;
end;

procedure TManager.AdjournGameClick(Sender: TObject);
begin
  RSendData(CMD_ADJOURN_GAME);
end;

procedure TManager.StartAdjournedGameConnectedClick(Sender: TObject);
begin
  if (AdjournedStr <> '') then
  begin
    RSendData(CMD_START_ADJOURNED_GAME);
    FStartAdjournedGame;
    RRetransmit(CMD_GAME_CONTEXT + ' ' + RGetGameContextStr);
    RRetransmit(CMD_CONTINUE_GAME);
  end;
end;


procedure TManager.FAdjournGame;
begin
  if (ChessBoard.Mode <> mGame) then
    exit;
  FBuildAdjournedStr;  
  ChessBoard.StopClock;
  ChessBoard.Mode := mView;
{$IFDEF GAME_LOG}
  FWriteToGameLog('*');
  FlushGameLog;
{$ENDIF}
  m_Dialogs.MessageDlg(TLocalizer.Instance.GetMessage(27), mtCustom, [mbOK], mfNone); // The game is adjourned.
end;

procedure TManager.FExitGameMode;
begin
  ChessBoard.StopClock;
  ChessBoard.Mode := mView;
  if (move_done) then
    AdjournedStr := '';
end;


function TManager.RGetGameContextStr: string;
var
  str: string;
begin
  // Result ::= <position>&<this player's color>&<time control>&<current time>
  with ChessBoard do
  begin
    // <position>
    str := ChessBoard.GetPosition + '&';
    // <this player's color>
    str := str + IfThen((_PlayerColor = fcWhite), 'w', 'b') + '&';
    // <time control>
    str := str + ClockToStr + '&';
    // <current time>
    str := str + TChessClock.ConvertToFullStr(Time[fcWhite], FALSE) + ' ' +
                 TChessClock.ConvertToFullStr(Time[fcBlack], FALSE);
  end;

  Result := str;
end;


procedure TManager.FBuildAdjournedStr;
begin
  AdjournedStr := RGetGameContextStr;
end;


procedure TManager.FStartAdjournedGame;
begin
  if (AdjournedStr = '') then
    exit;

  RSetGameContext(AdjournedStr);

  with ChessBoard do
  begin
    ResetMoveList;
    move_done := TRUE;
    TakebackGame.Enabled := FALSE;
    Mode := mGame;
    SwitchClock(PositionColor);
  end;
{$IFDEF GAME_LOG}
  FInitGameLog;
{$ENDIF}
end;


function TManager.FGetAdjournedStr: string;
begin
  Result := TIniSettings.Instance.Adjourned;
end;


procedure TManager.FSetAdjournedStr(const strValue: string);
begin
  TIniSettings.Instance.Adjourned := strValue;
end;


procedure TManager.RSetGameContext(const strValue: string);
var
  str: string;
  l: integer;
  strPosition, strPlayerColor, strTimeControl, strCurrentTime: string;
begin
  if (strValue = '') then
    exit;

  // strValue ::= <position>&<this player's color>&<time control>&<current time>

  str := strValue;

  l := pos('&', str);
  strPosition := LeftStr(str, l - 1);
  str := RightStr(str, length(str) - l);

  l := pos('&', str);
  strPlayerColor := LeftStr(str, l - 1);
  str := RightStr(str, length(str) - l);

  l := pos('&', str);
  strTimeControl := LeftStr(str, l - 1);
  strCurrentTime := RightStr(str, length(str) - l);

  SetClock(strTimeControl);

  if (((_PlayerColor = fcWhite) and (strPlayerColor <> 'w')) or
      ((_PlayerColor = fcBlack) and (strPlayerColor <> 'b'))) then
    ChangeColor;

  with ChessBoard do
  begin
    SetPosition(strPosition);

    RSplitStr(strCurrentTime, str, strCurrentTime);

    Time[fcWhite] := TChessClock.ConvertFromFullStr(str);
    Time[fcBlack] := TChessClock.ConvertFromFullStr(strCurrentTime);
  end;
end;


procedure TManager.GamePopupMenuPopup(Sender: TObject);
begin
  N6.Visible := ((not Transmittable) and
    (AdjournGame.Visible or GamePause.Visible or TakebackGame.Visible));
  ResignGame.Enabled := move_done;
  DrawGame.Enabled := (move_done and (_PlayerColor = ChessBoard.PositionColor));
end;


procedure TManager.RLocalize;
begin
  with TLocalizer.Instance do
  begin
    StartAdjournedGameConnected.Caption := GetLabel(51);
    StartStandartGameConnected.Caption := GetLabel(52);
    StartPPRandomGameConnected.Caption := GetLabel(53);
    ChangeColorConnected.Caption := GetLabel(54);
    GameOptionsConnected.Caption := GetLabel(55);
    LookFeelOptionsAction.Caption := GetLabel(56);
    AboutAction.Caption := GetLabel(57);

    AbortGame.Caption := GetLabel(58);
    DrawGame.Caption := GetLabel(59);
    ResignGame.Caption := GetLabel(60);
    AdjournGame.Caption := GetLabel(61);
    GamePause.Caption := GetLabel(62);
    TakebackGame.Caption := GetLabel(63);
    BroadcastAction.Caption := GetLabel(69);
  end;
end;


function TManager.FGetOpponentNickId: string;
begin
  if ((not m_bTransmittable) or (m_strOverridedOpponentNickId = '')) then
    Result := OpponentNick + OpponentId
  else
    Result := m_strOverridedOpponentNickId;
end;


procedure TManager.FSetTransmittable(bValue: boolean);
begin
  m_bTransmittable := bValue;
  if (bValue) then
  begin
    // connected menu
    StartAdjournedGameConnected.Visible := FALSE;
    StartStandartGameConnected.Visible := FALSE;
    StartPPRandomGameConnected.Visible := FALSE;
//    ChangeColorConnected.Visible := FALSE;
    GameOptionsConnected.Visible := FALSE;

{$IFDEF SKYPE}
    BroadcastAction.Visible := FALSE;
{$ENDIF}

    ChessBoard.ViewGaming := TRUE;
  end;
end;


function TManager.FGetPlayerColor: TFigureColor;
begin
  if (Assigned(ChessBoard)) then
    Result := ChessBoard.PlayerColor
  else
    Result := fcWhite;
end;


procedure TManager.FSetPlayerColor(Value: TFigureColor);
begin
  if (Assigned(ChessBoard)) then
    ChessBoard.PlayerColor := Value;
end;


procedure TManager.ActionListUpdate(Action: TBasicAction;
  var Handled: Boolean);
begin
  AdjournGame.Visible := (can_adjourn_game and (not Transmittable));
  AdjournGame.Enabled := ((adjournedStr <> '') and move_done);
  StartAdjournedGameConnected.Visible := ((adjournedStr <> '') and (not Transmittable));
end;

{$IFDEF SKYPE}
procedure TManager.FShowCredits;

  function NFridayThe13: boolean; // just for fun!
  begin
    Result := ((DayOfTheMonth(Today) = 13) and (DayOfWeek(Today) = 6));
  end;

begin // TManager.FShowCredits
  if (m_bConnectionOccured and (not m_bDontShowCredits) and (not NFridayThe13)) then
  begin
    with TCreditsForm.Create(nil) do
    try
      ShowModal;
      m_bDontShowCredits := DontShowAgain;
    finally
      Free;
    end;
  end;
end;
{$ENDIF}

function TManager.RGetGameName: string;
begin
  if (_PlayerColor = fcWhite) then
    Result := PlayerNick + ' - ' + OpponentNick
  else // fcBlack
    Result := OpponentNick + ' - ' + PlayerNick;
end;


procedure TManager.BroadcastActionExecute(Sender: TObject);
begin
  RBroadcast;
end;


procedure TManager.RBroadcast;
begin
end;

////////////////////////////////////////////////////////////////////////////////
// TManagerDefault

{$IFDEF AND_RQ}
constructor TManagerDefault.Create;
begin
  RCreate;
end;
{$ENDIF}

{$IFDEF QIP}
constructor TManagerDefault.Create(const accName: WideString; const protoDllHandle: integer);
begin
  iProtoDllHandle := protoDllHandle;
  wAccName := accName;

  RCreate;
end;
{$ENDIF}

{$IFDEF TRILLIAN}
constructor TManagerDefault.Create(const vContactlistEntry: TTtkContactListEntry);
begin
  contactListEntry := vContactlistEntry;
  RCreate;
end;
{$ENDIF}

procedure TManagerDefault.ROnCreate;
begin
  try
    RCreateChessBoardAndDialogs;

    TLocalizer.Instance.AddSubscriber(self);
    RLocalize;

    RSetChessBoardToView;
    RReadPrivateSettings;

{$IFDEF AND_RQ}
    Connector := TConnector.Create(RQ_GetChatUIN, ConnectorHandler);
{$ENDIF}
{$IFDEF QIP}
//    QIPConnectionError := FALSE;
    Connector := TConnector.Create(wAccName, iProtoDllHandle, ConnectorHandler);
{$ENDIF}
{$IFDEF TRILLIAN}
    Connector := TConnector.Create(@contactlistEntry, ConnectorHandler);
{$ENDIF}

    RCreateAndPopulateExtBaseList;

    // nicks initialisation
{$IFDEF AND_RQ}
    PlayerNick := RQ_GetDisplayedName(RQ_GetCurrentUser);
    OpponentNick := RQ_GetDisplayedName(RQ_GetChatUIN);
    OpponentId := IntToStr(RQ_GetChatUIN);
{$ENDIF}
{$IFDEF QIP}
    PlayerNick := GetOwnerNick(wAccName, iProtoDllHandle);
    OpponentNick := GetContactNick(wAccName, iProtoDllHandle);
    OpponentId := wAccName;
{$ENDIF}
{$IFDEF TRILLIAN}
    PlayerNick := trillianOwnerNick;
    OpponentNick := contactlistEntry.name;
    OpponentId := contactlistEntry.real_name;
{$ENDIF}
{$IFDEF QIP}
    if (not QIPConnectionError) then
    begin
{$ENDIF}
      RShowConnectingForm;
{$IFDEF QIP}
    end;
{$ENDIF}

  except
    Release;
    raise;
  end;
end;


procedure TManagerDefault.ROnDestroy;
begin
  if (Assigned(Connector)) then
  begin
    Connector.Close;
  end;

  inherited ROnDestroy;
end;


procedure TManagerDefault.RSendData(const cmd: string);
const
  last_cmd: string = '';
begin
  if (cmd = '') then
    exit;
  last_cmd := cmd + CMD_DELIMITER;
  Connector.SendData(last_cmd);
end;

end.