summaryrefslogtreecommitdiff
path: root/src/settings_gui.cpp
blob: 587a664a27258b5ffa12140327f7225b126546c6 (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
/* $Id$ */

/** @file settings_gui.cpp GUI for settings. */

#include "stdafx.h"
#include "openttd.h"
#include "currency.h"
#include "gui.h"
#include "window_gui.h"
#include "textbuf_gui.h"
#include "command_func.h"
#include "engine_func.h"
#include "screenshot.h"
#include "network/network.h"
#include "town.h"
#include "variables.h"
#include "settings_internal.h"
#include "newgrf_townname.h"
#include "strings_func.h"
#include "window_func.h"
#include "string_func.h"
#include "gfx_func.h"
#include "waypoint.h"
#include "widgets/dropdown_type.h"
#include "widgets/dropdown_func.h"
#include "station_func.h"
#include "highscore.h"
#include "gfxinit.h"
#include "company_base.h"
#include "company_func.h"
#include <map>

#include "table/sprites.h"
#include "table/strings.h"

static const StringID _units_dropdown[] = {
	STR_UNITS_IMPERIAL,
	STR_UNITS_METRIC,
	STR_UNITS_SI,
	INVALID_STRING_ID
};

static const StringID _driveside_dropdown[] = {
	STR_GAME_OPTIONS_ROAD_VEHICLES_DROPDOWN_LEFT,
	STR_GAME_OPTIONS_ROAD_VEHICLES_DROPDOWN_RIGHT,
	INVALID_STRING_ID
};

static const StringID _autosave_dropdown[] = {
	STR_GAME_OPTIONS_AUTOSAVE_DROPDOWN_OFF,
	STR_GAME_OPTIONS_AUTOSAVE_DROPDOWN_EVERY_1_MONTH,
	STR_GAME_OPTIONS_AUTOSAVE_DROPDOWN_EVERY_3_MONTHS,
	STR_GAME_OPTIONS_AUTOSAVE_DROPDOWN_EVERY_6_MONTHS,
	STR_GAME_OPTIONS_AUTOSAVE_DROPDOWN_EVERY_12_MONTHS,
	INVALID_STRING_ID,
};

static StringID *BuildDynamicDropdown(StringID base, int num)
{
	static StringID buf[32 + 1];
	StringID *p = buf;
	while (--num >= 0) *p++ = base++;
	*p = INVALID_STRING_ID;
	return buf;
}

int _nb_orig_names = SPECSTR_TOWNNAME_LAST - SPECSTR_TOWNNAME_START + 1;
static StringID *_grf_names = NULL;
static int _nb_grf_names = 0;

void InitGRFTownGeneratorNames()
{
	free(_grf_names);
	_grf_names = GetGRFTownNameList();
	_nb_grf_names = 0;
	for (StringID *s = _grf_names; *s != INVALID_STRING_ID; s++) _nb_grf_names++;
}

static inline StringID TownName(int town_name)
{
	if (town_name < _nb_orig_names) return STR_TOWNNAME_ORIGINAL_ENGLISH + town_name;
	town_name -= _nb_orig_names;
	if (town_name < _nb_grf_names) return _grf_names[town_name];
	return STR_UNDEFINED;
}

static int GetCurRes()
{
	int i;

	for (i = 0; i != _num_resolutions; i++) {
		if ((int)_resolutions[i].width == _screen.width &&
				(int)_resolutions[i].height == _screen.height) {
			break;
		}
	}
	return i;
}

/** Widgets of the game options menu */
enum GameOptionsWidgets {
	GOW_CLOSEBOX = 0,        ///< Close the window
	GOW_CAPTION,             ///< Caption of the window
	GOW_BACKGROUND,          ///< Background of the window
	GOW_CURRENCY_FRAME,      ///< Frame of the currency dropdown
	GOW_CURRENCY_DROPDOWN,   ///< Currency dropdown
	GOW_DISTANCE_FRAME,      ///< Measuring unit frame
	GOW_DISTANCE_DROPDOWN,   ///< Measuring unit dropdown
	GOW_ROADSIDE_FRAME,      ///< Road side frame
	GOW_ROADSIDE_DROPDOWN,   ///< Dropdown to select the road side (to set the right side ;))
	GOW_TOWNNAME_FRAME,      ///< Frame for the town name dropdown
	GOW_TOWNNAME_DROPDOWN,   ///< Town name dropdown
	GOW_AUTOSAVE_FRAME,      ///< Frame for autosave
	GOW_AUTOSAVE_DROPDOWN,   ///< Dropdown to say how often to autosave
	GOW_LANG_FRAME,          ///< Language dropdown frame
	GOW_LANG_DROPDOWN,       ///< Language dropdown
	GOW_RESOLUTION_FRAME,    ///< Frame for the dropdown for the resolution
	GOW_RESOLUTION_DROPDOWN, ///< Dropdown for the resolution
	GOW_FULLSCREEN_LABEL,    ///< Text (right) to the fullscreen button
	GOW_FULLSCREEN_BUTTON,   ///< Toggle fullscreen
	GOW_SCREENSHOT_FRAME,    ///< Frame for the screenshot type
	GOW_SCREENSHOT_DROPDOWN, ///< Select the screenshot type... please use PNG!
	GOW_BASE_GRF_FRAME,      ///< Base GRF selection frame
	GOW_BASE_GRF_DROPDOWN,   ///< Use to select a base GRF
	GOW_BASE_GRF_STATUS,     ///< Info about missing files etc.
	GOW_BASE_GRF_DESCRIPTION,///< Description of selected base GRF
};

/**
 * Update/redraw the townnames dropdown
 * @param w   the window the dropdown belongs to
 * @param sel the currently selected townname generator
 */
static void ShowTownnameDropdown(Window *w, int sel)
{
	typedef std::map<StringID, int, StringIDCompare> TownList;
	TownList townnames;

	/* Add and sort original townnames generators */
	for (int i = 0; i < _nb_orig_names; i++) townnames[STR_TOWNNAME_ORIGINAL_ENGLISH + i] = i;

	/* Add and sort newgrf townnames generators */
	for (int i = 0; i < _nb_grf_names; i++) townnames[_grf_names[i]] = _nb_orig_names + i;

	DropDownList *list = new DropDownList();
	for (TownList::iterator it = townnames.begin(); it != townnames.end(); it++) {
		list->push_back(new DropDownListStringItem((*it).first, (*it).second, !(_game_mode == GM_MENU || Town::GetNumItems() == 0 || (*it).second == sel)));
	}

	ShowDropDownList(w, list, sel, GOW_TOWNNAME_DROPDOWN);
}

static void ShowCustCurrency();

static void ShowGraphicsSetMenu(Window *w)
{
	int n = GetNumGraphicsSets();
	int current = GetIndexOfCurrentGraphicsSet();

	DropDownList *list = new DropDownList();
	for (int i = 0; i < n; i++) {
		list->push_back(new DropDownListCharStringItem(GetGraphicsSetName(i), i, (_game_mode == GM_MENU) ? false : (current != i)));
	}

	ShowDropDownList(w, list, current, GOW_BASE_GRF_DROPDOWN);
}

struct GameOptionsWindow : Window {
	GameSettings *opt;
	bool reload;

	GameOptionsWindow(const WindowDesc *desc) : Window(desc)
	{
		this->opt = (_game_mode == GM_MENU) ? &_settings_newgame : &_settings_game;
		this->reload = false;
		this->FindWindowPlacementAndResize(desc);
	}

	~GameOptionsWindow()
	{
		DeleteWindowById(WC_CUSTOM_CURRENCY, 0);
		if (this->reload) _switch_mode = SM_MENU;
	}

	virtual void OnPaint()
	{
		SetDParam(1, _currency_specs[this->opt->locale.currency].name);
		SetDParam(2, STR_UNITS_IMPERIAL + this->opt->locale.units);
		SetDParam(3, STR_GAME_OPTIONS_ROAD_VEHICLES_DROPDOWN_LEFT + this->opt->vehicle.road_side);
		SetDParam(4, TownName(this->opt->game_creation.town_name));
		SetDParam(5, _autosave_dropdown[_settings_client.gui.autosave]);
		SetDParam(6, SPECSTR_LANGUAGE_START + _dynlang.curr);
		int i = GetCurRes();
		SetDParam(7, i == _num_resolutions ? STR_RES_OTHER : SPECSTR_RESOLUTION_START + i);
		SetDParam(8, SPECSTR_SCREENSHOT_START + _cur_screenshot_format);
		this->SetWidgetLoweredState(GOW_FULLSCREEN_BUTTON, _fullscreen);
		SetDParamStr(9, GetGraphicsSetName(GetIndexOfCurrentGraphicsSet()));
		int missing_files = GetGraphicsSetNumMissingFiles(GetIndexOfCurrentGraphicsSet());
		SetDParam(10, missing_files);
		SetWidgetHiddenState(GOW_BASE_GRF_STATUS, missing_files == 0);

		this->DrawWidgets();

		SetDParam(0, STR_JUST_RAW_STRING);
		SetDParamStr(1, GetGraphicsSetDescription(GetIndexOfCurrentGraphicsSet()));
		const Widget *desc = &this->widget[GOW_BASE_GRF_DESCRIPTION];
		int y = DrawStringMultiLine(desc->left, desc->right, desc->top, UINT16_MAX, STR_BLACK_STRING);

		if (y != desc->bottom) {
			this->SetDirty();
			ResizeWindowForWidget(this, GOW_BASE_GRF_DESCRIPTION, 0, y - desc->bottom);
			this->SetDirty();
		}
	}

	virtual void OnClick(Point pt, int widget)
	{
		switch (widget) {
			case GOW_CURRENCY_DROPDOWN: // Setup currencies dropdown
				ShowDropDownMenu(this, BuildCurrencyDropdown(), this->opt->locale.currency, GOW_CURRENCY_DROPDOWN, _game_mode == GM_MENU ? 0 : ~GetMaskOfAllowedCurrencies(), 0);
				break;

			case GOW_DISTANCE_DROPDOWN: // Setup distance unit dropdown
				ShowDropDownMenu(this, _units_dropdown, this->opt->locale.units, GOW_DISTANCE_DROPDOWN, 0, 0);
				break;

			case GOW_ROADSIDE_DROPDOWN: { // Setup road-side dropdown
				int i = 0;
				extern bool RoadVehiclesAreBuilt();

				/* You can only change the drive side if you are in the menu or ingame with
				 * no vehicles present. In a networking game only the server can change it */
				if ((_game_mode != GM_MENU && RoadVehiclesAreBuilt()) || (_networking && !_network_server)) {
					i = (-1) ^ (1 << this->opt->vehicle.road_side); // disable the other value
				}

				ShowDropDownMenu(this, _driveside_dropdown, this->opt->vehicle.road_side, GOW_ROADSIDE_DROPDOWN, i, 0);
			} break;

			case GOW_TOWNNAME_DROPDOWN: // Setup townname dropdown
				ShowTownnameDropdown(this, this->opt->game_creation.town_name);
				break;

			case GOW_AUTOSAVE_DROPDOWN: // Setup autosave dropdown
				ShowDropDownMenu(this, _autosave_dropdown, _settings_client.gui.autosave, GOW_AUTOSAVE_DROPDOWN, 0, 0);
				break;

			case GOW_LANG_DROPDOWN: { // Setup interface language dropdown
				typedef std::map<StringID, int, StringIDCompare> LangList;

				/* Sort language names */
				LangList langs;
				for (int i = 0; i < _dynlang.num; i++) langs[SPECSTR_LANGUAGE_START + i] = i;

				DropDownList *list = new DropDownList();
				for (LangList::iterator it = langs.begin(); it != langs.end(); it++) {
					list->push_back(new DropDownListStringItem((*it).first, (*it).second, false));
				}

				ShowDropDownList(this, list, _dynlang.curr, GOW_LANG_DROPDOWN);
			} break;

			case GOW_RESOLUTION_DROPDOWN: // Setup resolution dropdown
				ShowDropDownMenu(this, BuildDynamicDropdown(SPECSTR_RESOLUTION_START, _num_resolutions), GetCurRes(), GOW_RESOLUTION_DROPDOWN, 0, 0);
				break;

			case GOW_FULLSCREEN_BUTTON: // Click fullscreen on/off
				/* try to toggle full-screen on/off */
				if (!ToggleFullScreen(!_fullscreen)) {
					ShowErrorMessage(INVALID_STRING_ID, STR_FULLSCREEN_FAILED, 0, 0);
				}
				this->SetWidgetLoweredState(GOW_FULLSCREEN_BUTTON, _fullscreen);
				this->SetDirty();
				break;

			case GOW_SCREENSHOT_DROPDOWN: // Setup screenshot format dropdown
				ShowDropDownMenu(this, BuildDynamicDropdown(SPECSTR_SCREENSHOT_START, _num_screenshot_formats), _cur_screenshot_format, GOW_SCREENSHOT_DROPDOWN, 0, 0);
				break;

			case GOW_BASE_GRF_DROPDOWN:
				ShowGraphicsSetMenu(this);
				break;
		}
	}

	virtual void OnDropdownSelect(int widget, int index)
	{
		switch (widget) {
			case GOW_CURRENCY_DROPDOWN: // Currency
				if (index == CUSTOM_CURRENCY_ID) ShowCustCurrency();
				this->opt->locale.currency = index;
				MarkWholeScreenDirty();
				break;

			case GOW_DISTANCE_DROPDOWN: // Measuring units
				this->opt->locale.units = index;
				MarkWholeScreenDirty();
				break;

			case GOW_ROADSIDE_DROPDOWN: // Road side
				if (this->opt->vehicle.road_side != index) { // only change if setting changed
					uint i;
					if (GetSettingFromName("vehicle.road_side", &i) == NULL) NOT_REACHED();
					SetSettingValue(i, index);
					MarkWholeScreenDirty();
				}
				break;

			case GOW_TOWNNAME_DROPDOWN: // Town names
				if (_game_mode == GM_MENU || Town::GetNumItems() == 0) {
					this->opt->game_creation.town_name = index;
					InvalidateWindow(WC_GAME_OPTIONS, 0);
				}
				break;

			case GOW_AUTOSAVE_DROPDOWN: // Autosave options
				_settings_client.gui.autosave = index;
				this->SetDirty();
				break;

			case GOW_LANG_DROPDOWN: // Change interface language
				ReadLanguagePack(index);
				CheckForMissingGlyphsInLoadedLanguagePack();
				UpdateAllStationVirtCoord();
				UpdateAllWaypointSigns();
				ReInitAllWindows();
				MarkWholeScreenDirty();
				break;

			case GOW_RESOLUTION_DROPDOWN: // Change resolution
				if (index < _num_resolutions && ChangeResInGame(_resolutions[index].width, _resolutions[index].height)) {
					this->SetDirty();
				}
				break;

			case GOW_SCREENSHOT_DROPDOWN: // Change screenshot format
				SetScreenshotFormat(index);
				this->SetDirty();
				break;

			case GOW_BASE_GRF_DROPDOWN:
				if (_game_mode == GM_MENU) {
					const char *name = GetGraphicsSetName(index);

					free(_ini_graphics_set);
					_ini_graphics_set = strdup(name);

					SetGraphicsSet(name);
					this->reload = true;
					this->SetDirty();
				}
				break;
		}
	}
};

static const Widget _game_options_widgets[] = {
{   WWT_CLOSEBOX,   RESIZE_NONE,  COLOUR_GREY,     0,    10,     0,    13, STR_BLACK_CROSS,                           STR_TOOLTIP_CLOSE_WINDOW},                          // GOW_CLOSEBOX
{    WWT_CAPTION,   RESIZE_NONE,  COLOUR_GREY,    11,   369,     0,    13, STR_GAME_OPTIONS_CAPTION,                  STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS},                // GOW_CAPTION
{      WWT_PANEL,   RESIZE_NONE,  COLOUR_GREY,     0,   369,    14,   248, 0x0,                                       STR_NULL},                                          // GOW_BACKGROUND
{      WWT_FRAME,   RESIZE_NONE,  COLOUR_GREY,    10,   179,    20,    55, STR_GAME_OPTIONS_CURRENCY_UNITS_FRAME,     STR_NULL},                                          // GOW_CURRENCY_FRAME
{   WWT_DROPDOWN,   RESIZE_NONE,  COLOUR_GREY,    20,   169,    34,    45, STR_GAME_OPTIONS_CURRENCY_UNITS_DROPDOWN,  STR_GAME_OPTIONS_CURRENCY_UNITS_DROPDOWN_TOOLTIP},  // GOW_CURRENCY_DROPDOWN
{      WWT_FRAME,   RESIZE_NONE,  COLOUR_GREY,   190,   359,    20,    55, STR_GAME_OPTIONS_MEASURING_UNITS_FRAME,    STR_NULL},                                          // GOW_DISTANCE_FRAME
{   WWT_DROPDOWN,   RESIZE_NONE,  COLOUR_GREY,   200,   349,    34,    45, STR_GAME_OPTIONS_MEASURING_UNITS_DROPDOWN, STR_GAME_OPTIONS_MEASURING_UNITS_DROPDOWN_TOOLTIP}, // GOW_DISTANCE_DROPDOWN
{      WWT_FRAME,   RESIZE_NONE,  COLOUR_GREY,    10,   179,    62,    97, STR_GAME_OPTIONS_ROAD_VEHICLES_FRAME,      STR_NULL},                                          // GOW_ROADSIDE_FRAME
{   WWT_DROPDOWN,   RESIZE_NONE,  COLOUR_GREY,    20,   169,    76,    87, STR_GAME_OPTIONS_ROAD_VEHICLES_DROPDOWN,   STR_GAME_OPTIONS_ROAD_VEHICLES_DROPDOWN_TOOLTIP},   // GOW_ROADSIDE_DROPDOWN
{      WWT_FRAME,   RESIZE_NONE,  COLOUR_GREY,   190,   359,    62,    97, STR_GAME_OPTIONS_TOWN_NAMES_FRAME,         STR_NULL},                                          // GOW_TOWNNAME_FRAME
{   WWT_DROPDOWN,   RESIZE_NONE,  COLOUR_GREY,   200,   349,    76,    87, STR_GAME_OPTIONS_TOWN_NAMES_DROPDOWN,      STR_GAME_OPTIONS_TOWN_NAMES_DROPDOWN_TOOLTIP},      // GOW_TOWNNAME_DROPDOWN
{      WWT_FRAME,   RESIZE_NONE,  COLOUR_GREY,    10,   179,   104,   139, STR_GAME_OPTIONS_AUTOSAVE_FRAME,           STR_NULL},                                          // GOW_AUTOSAVE_FRAME
{   WWT_DROPDOWN,   RESIZE_NONE,  COLOUR_GREY,    20,   169,   118,   129, STR_GAME_OPTIONS_AUTOSAVE_DROPDOWN,        STR_GAME_OPTIONS_AUTOSAVE_DROPDOWN_TOOLTIP},        // GOW_AUTOSAVE_DROPDOWN

{      WWT_FRAME,   RESIZE_NONE,  COLOUR_GREY,   190,   359,   104,   139, STR_OPTIONS_LANG,                          STR_NULL},                                          // GOW_LANG_FRAME
{   WWT_DROPDOWN,   RESIZE_NONE,  COLOUR_GREY,   200,   349,   118,   129, STR_OPTIONS_LANG_CBO,                      STR_OPTIONS_LANG_TIP},                              // GOW_LANG_DROPDOWN

{      WWT_FRAME,   RESIZE_NONE,  COLOUR_GREY,    10,   179,   146,   190, STR_OPTIONS_RES,                           STR_NULL},                                          // GOW_RESOLUTION_FRAME
{   WWT_DROPDOWN,   RESIZE_NONE,  COLOUR_GREY,    20,   169,   160,   171, STR_OPTIONS_RES_CBO,                       STR_OPTIONS_RES_TIP},                               // GOW_RESOLUTION_DROPDOWN
{       WWT_TEXT,   RESIZE_NONE,  COLOUR_GREY,    20,   146,   175,   186, STR_OPTIONS_FULLSCREEN,                    STR_NULL},                                          // GOW_FULLSCREEN_LABEL
{    WWT_TEXTBTN,   RESIZE_NONE,  COLOUR_GREY,   149,   169,   176,   184, STR_EMPTY,                                 STR_OPTIONS_FULLSCREEN_TIP},                        // GOW_FULLSCREEN_BUTTON

{      WWT_FRAME,   RESIZE_NONE,  COLOUR_GREY,   190,   359,   146,   190, STR_OPTIONS_SCREENSHOT_FORMAT,             STR_NULL},                                          // GOW_SCREENSHOT_FRAME
{   WWT_DROPDOWN,   RESIZE_NONE,  COLOUR_GREY,   200,   349,   160,   171, STR_OPTIONS_SCREENSHOT_FORMAT_CBO,         STR_OPTIONS_SCREENSHOT_FORMAT_TIP},                 // GOW_SCREENSHOT_DROPDOWN

{      WWT_FRAME,   RESIZE_NONE,  COLOUR_GREY,    10,   359,   197,   238, STR_OPTIONS_BASE_GRF,                      STR_NULL},                                          // GOW_BASE_GRF_FRAME
{   WWT_DROPDOWN,   RESIZE_NONE,  COLOUR_GREY,    20,   169,   211,   222, STR_OPTIONS_BASE_GRF_CBO,                  STR_OPTIONS_BASE_GRF_TIP},                          // GOW_BASE_GRF_DROPDOWN
{       WWT_TEXT,   RESIZE_NONE,  COLOUR_GREY,   200,   349,   211,   222, STR_OPTIONS_BASE_GRF_STATUS,               STR_NULL},                                          // GOW_BASE_GRF_STATUS
{       WWT_TEXT,   RESIZE_NONE,  COLOUR_GREY,    20,   349,   229,   228, STR_EMPTY,                                 STR_OPTIONS_BASE_GRF_DESCRIPTION_TIP},              // GOW_BASE_GRF_DESCRIPTION

{   WIDGETS_END},
};

static const NWidgetPart _nested_game_options_widgets[] = {
	NWidget(NWID_HORIZONTAL),
		NWidget(WWT_CLOSEBOX, COLOUR_GREY, GOW_CLOSEBOX),
		NWidget(WWT_CAPTION, COLOUR_GREY, GOW_CAPTION), SetDataTip(STR_GAME_OPTIONS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
	EndContainer(),
	NWidget(WWT_PANEL, COLOUR_GREY, GOW_BACKGROUND), SetPIP(6, 6, 10),
		NWidget(NWID_HORIZONTAL), SetPIP(10, 10, 10),
			NWidget(NWID_VERTICAL), SetPIP(0, 6, 0),
				NWidget(WWT_FRAME, COLOUR_GREY, GOW_CURRENCY_FRAME), SetDataTip(STR_GAME_OPTIONS_CURRENCY_UNITS_FRAME, STR_NULL),
					NWidget(WWT_DROPDOWN, COLOUR_GREY, GOW_CURRENCY_DROPDOWN), SetMinimalSize(150, 12), SetDataTip(STR_GAME_OPTIONS_CURRENCY_UNITS_DROPDOWN, STR_GAME_OPTIONS_CURRENCY_UNITS_DROPDOWN_TOOLTIP), SetPadding(14, 10, 10, 10),
				EndContainer(),
				NWidget(WWT_FRAME, COLOUR_GREY, GOW_ROADSIDE_FRAME), SetDataTip(STR_GAME_OPTIONS_ROAD_VEHICLES_FRAME, STR_NULL),
					NWidget(WWT_DROPDOWN, COLOUR_GREY, GOW_ROADSIDE_DROPDOWN), SetMinimalSize(150, 12), SetDataTip(STR_GAME_OPTIONS_ROAD_VEHICLES_DROPDOWN, STR_GAME_OPTIONS_ROAD_VEHICLES_DROPDOWN_TOOLTIP), SetPadding(14, 10, 10, 10),
				EndContainer(),
				NWidget(WWT_FRAME, COLOUR_GREY, GOW_AUTOSAVE_FRAME), SetDataTip(STR_GAME_OPTIONS_AUTOSAVE_FRAME, STR_NULL),
					NWidget(WWT_DROPDOWN, COLOUR_GREY, GOW_AUTOSAVE_DROPDOWN), SetMinimalSize(150, 12), SetDataTip(STR_GAME_OPTIONS_AUTOSAVE_DROPDOWN, STR_GAME_OPTIONS_AUTOSAVE_DROPDOWN_TOOLTIP), SetPadding(14, 10, 10, 10),
				EndContainer(),
				NWidget(WWT_FRAME, COLOUR_GREY, GOW_RESOLUTION_FRAME), SetDataTip(STR_OPTIONS_RES, STR_NULL),
					NWidget(WWT_DROPDOWN, COLOUR_GREY, GOW_RESOLUTION_DROPDOWN), SetMinimalSize(150, 12), SetDataTip(STR_OPTIONS_RES_CBO, STR_OPTIONS_RES_TIP), SetPadding(14, 10, 3, 10),
					NWidget(NWID_HORIZONTAL),
						NWidget(WWT_TEXT, COLOUR_GREY, GOW_FULLSCREEN_LABEL), SetMinimalSize(0, 12), SetFill(true, false), SetDataTip(STR_OPTIONS_FULLSCREEN, STR_NULL), SetPadding(0, 2, 4, 10),
						NWidget(WWT_TEXTBTN, COLOUR_GREY, GOW_FULLSCREEN_BUTTON), SetMinimalSize(21, 9), SetDataTip(STR_EMPTY, STR_OPTIONS_FULLSCREEN_TIP), SetPadding(0, 10, 4, 0),
					EndContainer(),
				EndContainer(),
			EndContainer(),

			NWidget(NWID_VERTICAL), SetPIP(0, 6, 0),
				NWidget(WWT_FRAME, COLOUR_GREY, GOW_DISTANCE_FRAME), SetDataTip(STR_GAME_OPTIONS_MEASURING_UNITS_FRAME, STR_NULL),
					NWidget(WWT_DROPDOWN, COLOUR_GREY, GOW_DISTANCE_DROPDOWN), SetMinimalSize(150, 12), SetDataTip(STR_GAME_OPTIONS_MEASURING_UNITS_DROPDOWN, STR_GAME_OPTIONS_MEASURING_UNITS_DROPDOWN_TOOLTIP), SetPadding(14, 10, 10, 10),
				EndContainer(),
				NWidget(WWT_FRAME, COLOUR_GREY, GOW_TOWNNAME_FRAME), SetDataTip(STR_GAME_OPTIONS_TOWN_NAMES_FRAME, STR_NULL),
					NWidget(WWT_DROPDOWN, COLOUR_GREY, GOW_TOWNNAME_DROPDOWN), SetMinimalSize(150, 12), SetDataTip(STR_GAME_OPTIONS_TOWN_NAMES_DROPDOWN, STR_GAME_OPTIONS_TOWN_NAMES_DROPDOWN_TOOLTIP), SetPadding(14, 10, 10, 10),
				EndContainer(),
				NWidget(WWT_FRAME, COLOUR_GREY, GOW_LANG_FRAME), SetDataTip(STR_OPTIONS_LANG, STR_NULL),
					NWidget(WWT_DROPDOWN, COLOUR_GREY, GOW_LANG_DROPDOWN), SetMinimalSize(150, 12), SetDataTip(STR_OPTIONS_LANG_CBO, STR_OPTIONS_LANG_TIP), SetPadding(14, 10, 10, 10),
				EndContainer(),
				NWidget(WWT_FRAME, COLOUR_GREY, GOW_SCREENSHOT_FRAME), SetDataTip(STR_OPTIONS_SCREENSHOT_FORMAT, STR_NULL),
					NWidget(WWT_DROPDOWN, COLOUR_GREY, GOW_SCREENSHOT_DROPDOWN), SetMinimalSize(150, 12), SetDataTip(STR_OPTIONS_SCREENSHOT_FORMAT_CBO, STR_OPTIONS_SCREENSHOT_FORMAT_TIP), SetPadding(14, 10, 10, 10),
					NWidget(NWID_SPACER), SetMinimalSize(0, 9),
				EndContainer(),
			EndContainer(),
		EndContainer(),

		NWidget(WWT_FRAME, COLOUR_GREY, GOW_BASE_GRF_FRAME), SetDataTip(STR_OPTIONS_BASE_GRF, STR_NULL),
			NWidget(NWID_HORIZONTAL), SetPIP(10, 30, 10),
				NWidget(WWT_DROPDOWN, COLOUR_GREY, GOW_BASE_GRF_DROPDOWN), SetMinimalSize(150, 12), SetDataTip(STR_OPTIONS_BASE_GRF_CBO, STR_OPTIONS_BASE_GRF_TIP), SetPadding(14, 0, 0, 0),
				NWidget(WWT_TEXT, COLOUR_GREY, GOW_BASE_GRF_STATUS), SetMinimalSize(150, 12), SetDataTip(STR_OPTIONS_BASE_GRF_STATUS, STR_NULL), SetPadding(14, 0, 0, 0),
			EndContainer(),
			NWidget(WWT_TEXT, COLOUR_GREY, GOW_BASE_GRF_DESCRIPTION), SetMinimalSize(330, 0), SetDataTip(STR_EMPTY, STR_OPTIONS_BASE_GRF_DESCRIPTION_TIP), SetPadding(6, 10, 10, 10),
		EndContainer(),
	EndContainer(),
};

static const WindowDesc _game_options_desc(
	WDP_CENTER, WDP_CENTER, 370, 249, 370, 249,
	WC_GAME_OPTIONS, WC_NONE,
	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
	_game_options_widgets, _nested_game_options_widgets, lengthof(_nested_game_options_widgets)
);


void ShowGameOptions()
{
	DeleteWindowById(WC_GAME_OPTIONS, 0);
	new GameOptionsWindow(&_game_options_desc);
}

extern void StartupEconomy();


/* Names of the game difficulty settings window */
enum GameDifficultyWidgets {
	GDW_CAPTION,
	GDW_UPPER_BG,
	GDW_LVL_EASY,
	GDW_LVL_MEDIUM,
	GDW_LVL_HARD,
	GDW_LVL_CUSTOM,
	GDW_HIGHSCORE,
	GDW_SETTING_BG,
	GDW_LOWER_BG,
	GDW_ACCEPT,
	GDW_CANCEL,
};

/* Widget definition for the game difficulty settings window */
static const Widget _game_difficulty_widgets[] = {
{    WWT_CAPTION,   RESIZE_NONE,  COLOUR_MAUVE,      0,   369,     0,    13, STR_DIFFICULTY_LEVEL_CAPTION,           STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS}, // GDW_CAPTION
{      WWT_PANEL,   RESIZE_NONE,  COLOUR_MAUVE,      0,   369,    14,    41, 0x0,                                    STR_NULL},                           // GDW_UPPER_BG
{ WWT_PUSHTXTBTN,   RESIZE_NONE,  COLOUR_YELLOW,    10,    96,    16,    27, STR_DIFFICULTY_LEVEL_EASY,              STR_NULL},                           // GDW_LVL_EASY
{ WWT_PUSHTXTBTN,   RESIZE_NONE,  COLOUR_YELLOW,    97,   183,    16,    27, STR_DIFFICULTY_LEVEL_MEDIUM,            STR_NULL},                           // GDW_LVL_MEDIUM
{ WWT_PUSHTXTBTN,   RESIZE_NONE,  COLOUR_YELLOW,   184,   270,    16,    27, STR_DIFFICULTY_LEVEL_HARD,              STR_NULL},                           // GDW_LVL_HARD
{ WWT_PUSHTXTBTN,   RESIZE_NONE,  COLOUR_YELLOW,   271,   357,    16,    27, STR_DIFFICULTY_LEVEL_CUSTOM,            STR_NULL},                           // GDW_LVL_CUSTOM
{    WWT_TEXTBTN,   RESIZE_NONE,  COLOUR_GREEN,     10,   357,    28,    39, STR_DIFFICULTY_LEVEL_HIGH_SCORE_BUTTON, STR_NULL},                           // GDW_HIGHSCORE
{      WWT_PANEL,   RESIZE_NONE,  COLOUR_MAUVE,      0,   369,    42,   262, 0x0,                                    STR_NULL},                           // GDW_SETTING_BG
{      WWT_PANEL,   RESIZE_NONE,  COLOUR_MAUVE,      0,   369,   263,   278, 0x0,                                    STR_NULL},                           // GDW_LOWER_BG
{ WWT_PUSHTXTBTN,   RESIZE_NONE,  COLOUR_YELLOW,   105,   185,   265,   276, STR_OPTIONS_SAVE_CHANGES,               STR_NULL},                           // GDW_ACCEPT
{ WWT_PUSHTXTBTN,   RESIZE_NONE,  COLOUR_YELLOW,   186,   266,   265,   276, STR_QUERY_CANCEL,                       STR_NULL},                           // GDW_CANCEL
{   WIDGETS_END},
};

static const NWidgetPart _nested_game_difficulty_widgets[] = {
	NWidget(WWT_CAPTION, COLOUR_MAUVE, GDW_CAPTION), SetMinimalSize(370, 14), SetDataTip(STR_DIFFICULTY_LEVEL_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
	NWidget(WWT_PANEL, COLOUR_MAUVE, GDW_UPPER_BG),
		NWidget(NWID_SPACER), SetMinimalSize(0, 2),
		NWidget(NWID_HORIZONTAL),
			NWidget(NWID_SPACER), SetMinimalSize(10, 0),
			NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, GDW_LVL_EASY), SetMinimalSize(87, 12), SetDataTip(STR_DIFFICULTY_LEVEL_EASY, STR_NULL),
			NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, GDW_LVL_MEDIUM), SetMinimalSize(87, 12), SetDataTip(STR_DIFFICULTY_LEVEL_MEDIUM, STR_NULL),
			NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, GDW_LVL_HARD), SetMinimalSize(87, 12), SetDataTip(STR_DIFFICULTY_LEVEL_HARD, STR_NULL),
			NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, GDW_LVL_CUSTOM), SetMinimalSize(87, 12), SetDataTip(STR_DIFFICULTY_LEVEL_CUSTOM, STR_NULL),
			NWidget(NWID_SPACER), SetMinimalSize(12, 0),
		EndContainer(),
		NWidget(NWID_HORIZONTAL),
			NWidget(NWID_SPACER), SetMinimalSize(10, 0),
			NWidget(WWT_TEXTBTN, COLOUR_GREEN, GDW_HIGHSCORE), SetMinimalSize(348, 12), SetDataTip(STR_DIFFICULTY_LEVEL_HIGH_SCORE_BUTTON, STR_NULL),
			NWidget(NWID_SPACER), SetMinimalSize(12, 0),
		EndContainer(),
		NWidget(NWID_SPACER), SetMinimalSize(0, 2),
	EndContainer(),
	NWidget(WWT_PANEL, COLOUR_MAUVE, GDW_SETTING_BG), SetMinimalSize(370, 221),
	EndContainer(),
	NWidget(WWT_PANEL, COLOUR_MAUVE, GDW_LOWER_BG),
		NWidget(NWID_SPACER), SetMinimalSize(0, 2),
		NWidget(NWID_HORIZONTAL),
			NWidget(NWID_SPACER), SetMinimalSize(105, 0),
			NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, GDW_ACCEPT), SetMinimalSize(81, 12), SetDataTip(STR_OPTIONS_SAVE_CHANGES, STR_NULL),
			NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, GDW_CANCEL), SetMinimalSize(81, 12), SetDataTip(STR_QUERY_CANCEL, STR_NULL),
			NWidget(NWID_SPACER), SetMinimalSize(103, 0),
		EndContainer(),
		NWidget(NWID_SPACER), SetMinimalSize(0, 2),
	EndContainer(),
};

/* Window definition for the game difficulty settings window */
static const WindowDesc _game_difficulty_desc(
	WDP_CENTER, WDP_CENTER, 370, 279, 370, 279,
	WC_GAME_OPTIONS, WC_NONE,
	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
	_game_difficulty_widgets, _nested_game_difficulty_widgets, lengthof(_nested_game_difficulty_widgets)
);

void SetDifficultyLevel(int mode, DifficultySettings *gm_opt);

struct GameDifficultyWindow : public Window {
private:
	static const uint GAME_DIFFICULTY_NUM = 18;
	bool clicked_increase;
	uint8 clicked_button;
	uint8 timeout;

	/* Temporary holding place of values in the difficulty window until 'Save' is clicked */
	GameSettings opt_mod_temp;

	enum {
		GAMEDIFF_WND_TOP_OFFSET = 45,
		GAMEDIFF_WND_ROWSIZE    = 9,
		NO_SETTINGS_BUTTON = 0xFF,
	};

public:
	GameDifficultyWindow() : Window(&_game_difficulty_desc)
	{
		/* Copy current settings (ingame or in intro) to temporary holding place
		 * change that when setting stuff, copy back on clicking 'OK' */
		this->opt_mod_temp = (_game_mode == GM_MENU) ? _settings_newgame : _settings_game;
		this->clicked_increase = false;
		this->clicked_button = NO_SETTINGS_BUTTON;
		this->timeout = 0;
		/* Setup disabled buttons when creating window
		 * disable all other difficulty buttons during gameplay except for 'custom' */
		this->SetWidgetsDisabledState(_game_mode == GM_NORMAL,
			GDW_LVL_EASY,
			GDW_LVL_MEDIUM,
			GDW_LVL_HARD,
			GDW_LVL_CUSTOM,
			WIDGET_LIST_END);
		this->SetWidgetDisabledState(GDW_HIGHSCORE, _game_mode == GM_EDITOR || _networking); // highscore chart in multiplayer
		this->SetWidgetDisabledState(GDW_ACCEPT, _networking && !_network_server); // Save-button in multiplayer (and if client)
		this->LowerWidget(GDW_LVL_EASY + this->opt_mod_temp.difficulty.diff_level);
		this->FindWindowPlacementAndResize(&_game_difficulty_desc);
	}

	virtual void OnPaint()
	{
		this->DrawWidgets();

		uint i;
		const SettingDesc *sd = GetSettingFromName("difficulty.max_no_competitors", &i);
		int y = GAMEDIFF_WND_TOP_OFFSET;
		StringID str = STR_DIFFICULTY_LEVEL_SETTING_MAXIMUM_NO_COMPETITORS;
		for (i = 0; i < GAME_DIFFICULTY_NUM; i++, sd++) {
			const SettingDescBase *sdb = &sd->desc;
			/* skip deprecated difficulty options */
			if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
			int32 value = (int32)ReadValue(GetVariableAddress(&this->opt_mod_temp, &sd->save), sd->save.conv);
			bool editable = (_game_mode == GM_MENU || (sdb->flags & SGF_NEWGAME_ONLY) == 0);

			DrawArrowButtons(5, y, COLOUR_YELLOW,
					(this->clicked_button == i) ? 1 + !!this->clicked_increase : 0,
					editable && sdb->min != value,
					editable && sdb->max != (uint32)value);

			value += sdb->str;
			SetDParam(0, value);
			DrawString(30, this->width, y, str);

			y += GAMEDIFF_WND_ROWSIZE + 2; // space items apart a bit
			str++;
		}
	}

	virtual void OnClick(Point pt, int widget)
	{
		switch (widget) {
			case GDW_SETTING_BG: { // Difficulty settings widget, decode click
				/* Don't allow clients to make any changes */
				if (_networking && !_network_server) return;

				const int x = pt.x - 5;
				if (!IsInsideMM(x, 0, 21)) return; // Button area

				const int y = pt.y - GAMEDIFF_WND_TOP_OFFSET;
				if (y < 0) return;

				/* Get button from Y coord. */
				uint8 btn = y / (GAMEDIFF_WND_ROWSIZE + 2);
				if (btn >= 1) btn++; // Skip the deprecated option "competitor start time"
				if (btn >= 8) btn++; // Skip the deprecated option "competitor intelligence"
				if (btn >= GAME_DIFFICULTY_NUM || y % (GAMEDIFF_WND_ROWSIZE + 2) >= 9) return;

				uint i;
				const SettingDesc *sd = GetSettingFromName("difficulty.max_no_competitors", &i) + btn;
				const SettingDescBase *sdb = &sd->desc;

				/* Clicked disabled button? */
				bool editable = (_game_mode == GM_MENU || (sdb->flags & SGF_NEWGAME_ONLY) == 0);
				if (!editable) return;

				this->timeout = 5;
				int32 val = (int32)ReadValue(GetVariableAddress(&this->opt_mod_temp, &sd->save), sd->save.conv);

				if (x >= 10) {
					/* Increase button clicked */
					val = min(val + sdb->interval, sdb->max);
					this->clicked_increase = true;
				} else {
					/* Decrease button clicked */
					val -= sdb->interval;
					val = max(val, sdb->min);
					this->clicked_increase = false;
				}
				this->clicked_button = btn;

				/* save value in temporary variable */
				WriteValue(GetVariableAddress(&this->opt_mod_temp, &sd->save), sd->save.conv, val);
				this->RaiseWidget(GDW_LVL_EASY + this->opt_mod_temp.difficulty.diff_level);
				SetDifficultyLevel(3, &this->opt_mod_temp.difficulty); // set difficulty level to custom
				this->LowerWidget(GDW_LVL_CUSTOM);
				this->SetDirty();
			} break;

			case GDW_LVL_EASY:
			case GDW_LVL_MEDIUM:
			case GDW_LVL_HARD:
			case GDW_LVL_CUSTOM:
				/* temporarily change difficulty level */
				this->RaiseWidget(GDW_LVL_EASY + this->opt_mod_temp.difficulty.diff_level);
				SetDifficultyLevel(widget - GDW_LVL_EASY, &this->opt_mod_temp.difficulty);
				this->LowerWidget(GDW_LVL_EASY + this->opt_mod_temp.difficulty.diff_level);
				this->SetDirty();
				break;

			case GDW_HIGHSCORE: // Highscore Table
				ShowHighscoreTable(this->opt_mod_temp.difficulty.diff_level, -1);
				break;

			case GDW_ACCEPT: { // Save button - save changes
				GameSettings *opt_ptr = (_game_mode == GM_MENU) ? &_settings_newgame : &_settings_game;

				uint i;
				const SettingDesc *sd = GetSettingFromName("difficulty.max_no_competitors", &i);
				for (uint btn = 0; btn != GAME_DIFFICULTY_NUM; btn++, sd++) {
					int32 new_val = (int32)ReadValue(GetVariableAddress(&this->opt_mod_temp, &sd->save), sd->save.conv);
					int32 cur_val = (int32)ReadValue(GetVariableAddress(opt_ptr, &sd->save), sd->save.conv);
					/* if setting has changed, change it */
					if (new_val != cur_val) {
						DoCommandP(0, i + btn, new_val, CMD_CHANGE_SETTING);
					}
				}

				GetSettingFromName("difficulty.diff_level", &i);
				DoCommandP(0, i, this->opt_mod_temp.difficulty.diff_level, CMD_CHANGE_SETTING);
				delete this;
				/* If we are in the editor, we should reload the economy.
				 * This way when you load a game, the max loan and interest rate
				 * are loaded correctly. */
				if (_game_mode == GM_EDITOR) StartupEconomy();
				break;
			}

			case GDW_CANCEL: // Cancel button - close window, abandon changes
				delete this;
				break;
		}
	}

	virtual void OnTick()
	{
		if (this->timeout != 0) {
			this->timeout--;
			if (this->timeout == 0) this->clicked_button = NO_SETTINGS_BUTTON;
			this->SetDirty();
		}
	}
};

void ShowGameDifficulty()
{
	DeleteWindowById(WC_GAME_OPTIONS, 0);
	new GameDifficultyWindow();
}

static const int SETTING_HEIGHT = 11; ///< Height of a single setting in the tree view in pixels
static const int LEVEL_WIDTH = 15;    ///< Indenting width of a sub-page in pixels

/**
 * Flags for #SettingEntry
 * @note The #SEF_BUTTONS_MASK matches expectations of the formal parameter 'state' of #DrawArrowButtons
 */
enum SettingEntryFlags {
	SEF_LEFT_DEPRESSED  = 0x01, ///< Of a numeric setting entry, the left button is depressed
	SEF_RIGHT_DEPRESSED = 0x02, ///< Of a numeric setting entry, the right button is depressed
	SEF_BUTTONS_MASK = (SEF_LEFT_DEPRESSED | SEF_RIGHT_DEPRESSED), ///< Bit-mask for button flags

	SEF_LAST_FIELD = 0x04, ///< This entry is the last one in a (sub-)page

	/* Entry kind */
	SEF_SETTING_KIND = 0x10, ///< Entry kind: Entry is a setting
	SEF_SUBTREE_KIND = 0x20, ///< Entry kind: Entry is a sub-tree
	SEF_KIND_MASK    = (SEF_SETTING_KIND | SEF_SUBTREE_KIND), ///< Bit-mask for fetching entry kind
};

struct SettingsPage; // Forward declaration

/** Data fields for a sub-page (#SEF_SUBTREE_KIND kind)*/
struct SettingEntrySubtree {
	SettingsPage *page; ///< Pointer to the sub-page
	bool folded;        ///< Sub-page is folded (not visible except for its title)
	StringID title;     ///< Title of the sub-page
};

/** Data fields for a single setting (#SEF_SETTING_KIND kind) */
struct SettingEntrySetting {
	const char *name;           ///< Name of the setting
	const SettingDesc *setting; ///< Setting description of the setting
	uint index;                 ///< Index of the setting in the settings table
};

/** Data structure describing a single setting in a tab */
struct SettingEntry {
	byte flags; ///< Flags of the setting entry. @see SettingEntryFlags
	byte level; ///< Nesting level of this setting entry
	union {
		SettingEntrySetting entry; ///< Data fields if entry is a setting
		SettingEntrySubtree sub;   ///< Data fields if entry is a sub-page
	} d; ///< Data fields for each kind

	SettingEntry(const char *nm);
	SettingEntry(SettingsPage *sub, StringID title);

	void Init(byte level, bool last_field);
	void FoldAll();
	void SetButtons(byte new_val);

	uint Length() const;
	SettingEntry *FindEntry(uint row, uint *cur_row);

	uint Draw(GameSettings *settings_ptr, int base_x, int base_y, int max_x, uint first_row, uint max_row, uint cur_row, uint parent_last);

private:
	void DrawSetting(GameSettings *settings_ptr, const SettingDesc *sd, int x, int y, int max_x, int state);
};

/** Data structure describing one page of settings in the settings window. */
struct SettingsPage {
	SettingEntry *entries; ///< Array of setting entries of the page.
	byte num;              ///< Number of entries on the page (statically filled).

	void Init(byte level = 0);
	void FoldAll();

	uint Length() const;
	SettingEntry *FindEntry(uint row, uint *cur_row) const;

	uint Draw(GameSettings *settings_ptr, int base_x, int base_y, int max_x, uint first_row, uint max_row, uint cur_row = 0, uint parent_last = 0) const;
};


/* == SettingEntry methods == */

/**
 * Constructor for a single setting in the 'advanced settings' window
 * @param nm Name of the setting in the setting table
 */
SettingEntry::SettingEntry(const char *nm)
{
	this->flags = SEF_SETTING_KIND;
	this->level = 0;
	this->d.entry.name = nm;
	this->d.entry.setting = NULL;
	this->d.entry.index = 0;
}

/**
 * Constructor for a sub-page in the 'advanced settings' window
 * @param sub   Sub-page
 * @param title Title of the sub-page
 */
SettingEntry::SettingEntry(SettingsPage *sub, StringID title)
{
	this->flags = SEF_SUBTREE_KIND;
	this->level = 0;
	this->d.sub.page = sub;
	this->d.sub.folded = true;
	this->d.sub.title = title;
}

/**
 * Initialization of a setting entry
 * @param level      Page nesting level of this entry
 * @param last_field Boolean indicating this entry is the last at the (sub-)page
 */
void SettingEntry::Init(byte level, bool last_field)
{
	this->level = level;
	if (last_field) this->flags |= SEF_LAST_FIELD;

	switch (this->flags & SEF_KIND_MASK) {
		case SEF_SETTING_KIND:
			this->d.entry.setting = GetSettingFromName(this->d.entry.name, &this->d.entry.index);
			assert(this->d.entry.setting != NULL);
			break;
		case SEF_SUBTREE_KIND:
			this->d.sub.page->Init(level + 1);
			break;
		default: NOT_REACHED();
	}
}

/** Recursively close all folds of sub-pages */
void SettingEntry::FoldAll()
{
	switch(this->flags & SEF_KIND_MASK) {
		case SEF_SETTING_KIND:
			break;

		case SEF_SUBTREE_KIND:
			this->d.sub.folded = true;
			this->d.sub.page->FoldAll();
			break;

		default: NOT_REACHED();
	}
}


/**
 * Set the button-depressed flags (#SEF_LEFT_DEPRESSED and #SEF_RIGHT_DEPRESSED) to a specified value
 * @param new_val New value for the button flags
 * @see SettingEntryFlags
 */
void SettingEntry::SetButtons(byte new_val)
{
	assert((new_val & ~SEF_BUTTONS_MASK) == 0); // Should not touch any flags outside the buttons
	this->flags = (this->flags & ~SEF_BUTTONS_MASK) | new_val;
}

/** Return numbers of rows needed to display the entry */
uint SettingEntry::Length() const
{
	switch (this->flags & SEF_KIND_MASK) {
		case SEF_SETTING_KIND:
			return 1;
		case SEF_SUBTREE_KIND:
			if (this->d.sub.folded) return 1; // Only displaying the title

			return 1 + this->d.sub.page->Length(); // 1 extra row for the title
		default: NOT_REACHED();
	}
}

/**
 * Find setting entry at row \a row_num
 * @param row_num Index of entry to return
 * @param cur_row Current row number
 * @return The requested setting entry or \c NULL if it not found
 */
SettingEntry *SettingEntry::FindEntry(uint row_num, uint *cur_row)
{
	if (row_num == *cur_row) return this;

	switch (this->flags & SEF_KIND_MASK) {
		case SEF_SETTING_KIND:
			(*cur_row)++;
			break;
		case SEF_SUBTREE_KIND:
			(*cur_row)++; // add one for row containing the title
			if (this->d.sub.folded) {
				break;
			}

			/* sub-page is visible => search it too */
			return this->d.sub.page->FindEntry(row_num, cur_row);
		default: NOT_REACHED();
	}
	return NULL;
}

/**
 * Draw a row in the settings panel.
 *
 * See SettingsPage::Draw() for an explanation about how drawing is performed.
 *
 * The \a parent_last parameter ensures that the vertical lines at the left are
 * only drawn when another entry follows, that it prevents output like
 * \verbatim
 *  |-- setting
 *  |-- (-) - Title
 *  |    |-- setting
 *  |    |-- setting
 * \endverbatim
 * The left-most vertical line is not wanted. It is prevented by setting the
 * appropiate bit in the \a parent_last parameter.
 *
 * @param settings_ptr Pointer to current values of all settings
 * @param base_x       Left-most position in window/panel to start drawing \a first_row
 * @param base_y       Upper-most position in window/panel to start drawing \a first_row
 * @param max_x        The maximum x position to draw strings add.
 * @param first_row    First row number to draw
 * @param max_row      Row-number to stop drawing (the row-number of the row below the last row to draw)
 * @param cur_row      Current row number (internal variable)
 * @param parent_last  Last-field booleans of parent page level (page level \e i sets bit \e i to 1 if it is its last field)
 * @return Row number of the next row to draw
 */
uint SettingEntry::Draw(GameSettings *settings_ptr, int base_x, int base_y, int max_x, uint first_row, uint max_row, uint cur_row, uint parent_last)
{
	if (cur_row >= max_row) return cur_row;

	int x = base_x;
	int y = base_y;
	if (cur_row >= first_row) {
		int colour = _colour_gradient[COLOUR_ORANGE][4];
		y = base_y + (cur_row - first_row) * SETTING_HEIGHT; // Compute correct y start position

		/* Draw vertical for parent nesting levels */
		for (uint lvl = 0; lvl < this->level; lvl++) {
			if (!HasBit(parent_last, lvl)) GfxDrawLine(x + 4, y, x + 4, y + SETTING_HEIGHT - 1, colour);
			x += LEVEL_WIDTH;
		}
		/* draw own |- prefix */
		int halfway_y = y + SETTING_HEIGHT / 2;
		int bottom_y = (flags & SEF_LAST_FIELD) ? halfway_y : y + SETTING_HEIGHT - 1;
		GfxDrawLine(x + 4, y, x + 4, bottom_y, colour);
		/* Small horizontal line from the last vertical line */
		GfxDrawLine(x + 4, halfway_y, x + LEVEL_WIDTH - 4, halfway_y, colour);
		x += LEVEL_WIDTH;
	}

	switch(this->flags & SEF_KIND_MASK) {
		case SEF_SETTING_KIND:
			if (cur_row >= first_row) {
				DrawSetting(settings_ptr, this->d.entry.setting, x, y, max_x, this->flags & SEF_BUTTONS_MASK);
			}
			cur_row++;
			break;
		case SEF_SUBTREE_KIND:
			if (cur_row >= first_row) {
				DrawSprite((this->d.sub.folded ? SPR_CIRCLE_FOLDED : SPR_CIRCLE_UNFOLDED), PAL_NONE, x, y);
				DrawString(x + 12, max_x, y, this->d.sub.title);
			}
			cur_row++;
			if (!this->d.sub.folded) {
				if (this->flags & SEF_LAST_FIELD) {
					assert(this->level < sizeof(parent_last));
					SetBit(parent_last, this->level); // Add own last-field state
				}

				cur_row = this->d.sub.page->Draw(settings_ptr, base_x, base_y, max_x, first_row, max_row, cur_row, parent_last);
			}
			break;
		default: NOT_REACHED();
	}
	return cur_row;
}

const void *ResolveVariableAddress(const GameSettings *settings_ptr, const SettingDesc *sd)
{
	if ((sd->desc.flags & SGF_PER_COMPANY) != 0) {
		if (Company::IsValidID(_local_company) && _game_mode != GM_MENU) {
			return GetVariableAddress(&Company::Get(_local_company)->settings, &sd->save);
		} else {
			return GetVariableAddress(&_settings_client.company, &sd->save);
		}
	} else {
		return GetVariableAddress(settings_ptr, &sd->save);
	}
}

/**
 * Private function to draw setting value (button + text + current value)
 * @param settings_ptr Pointer to current values of all settings
 * @param sd           Pointer to value description of setting to draw
 * @param x            Left-most position in window/panel to start drawing
 * @param y            Upper-most position in window/panel to start drawing
 * @param max_x        The maximum x position to draw strings add.
 * @param state        State of the left + right arrow buttons to draw for the setting
 */
void SettingEntry::DrawSetting(GameSettings *settings_ptr, const SettingDesc *sd, int x, int y, int max_x, int state)
{
	const SettingDescBase *sdb = &sd->desc;
	const void *var = ResolveVariableAddress(settings_ptr, sd);
	bool editable = true;
	bool disabled = false;

	/* We do not allow changes of some items when we are a client in a networkgame */
	if (!(sd->save.conv & SLF_NETWORK_NO) && _networking && !_network_server && !(sdb->flags & SGF_PER_COMPANY)) editable = false;
	if ((sdb->flags & SGF_NETWORK_ONLY) && !_networking) editable = false;
	if ((sdb->flags & SGF_NO_NETWORK) && _networking) editable = false;

	if (sdb->cmd == SDT_BOOLX) {
		static const Colours _bool_ctabs[2][2] = {{COLOUR_CREAM, COLOUR_RED}, {COLOUR_DARK_GREEN, COLOUR_GREEN}};
		/* Draw checkbox for boolean-value either on/off */
		bool on = (*(bool*)var);

		DrawFrameRect(x, y, x + 19, y + 8, _bool_ctabs[!!on][!!editable], on ? FR_LOWERED : FR_NONE);
		SetDParam(0, on ? STR_CONFIG_SETTING_ON : STR_CONFIG_SETTING_OFF);
	} else {
		int32 value;

		value = (int32)ReadValue(var, sd->save.conv);

		/* Draw [<][>] boxes for settings of an integer-type */
		DrawArrowButtons(x, y, COLOUR_YELLOW, state, editable && value != (sdb->flags & SGF_0ISDISABLED ? 0 : sdb->min), editable && (uint32)value != sdb->max);

		disabled = (value == 0) && (sdb->flags & SGF_0ISDISABLED);
		if (disabled) {
			SetDParam(0, STR_CONFIG_SETTING_DISABLED);
		} else {
			if (sdb->flags & SGF_CURRENCY) {
				SetDParam(0, STR_CONFIG_SETTING_CURRENCY);
			} else if (sdb->flags & SGF_MULTISTRING) {
				SetDParam(0, sdb->str + value + 1);
			} else {
				SetDParam(0, (sdb->flags & SGF_NOCOMMA) ? STR_CONFIG_SETTING_INT32 : STR_JUST_COMMA);
			}
			SetDParam(1, value);
		}
	}
	DrawString(x + 25, max_x, y, (sdb->str) + disabled);
}


/* == SettingsPage methods == */

/**
 * Initialization of an entire setting page
 * @param level Nesting level of this page (internal variable, do not provide a value for it when calling)
 */
void SettingsPage::Init(byte level)
{
	for (uint field = 0; field < this->num; field++) {
		this->entries[field].Init(level, field + 1 == num);
	}
}

/** Recursively close all folds of sub-pages */
void SettingsPage::FoldAll()
{
	for (uint field = 0; field < this->num; field++) {
		this->entries[field].FoldAll();
	}
}

/** Return number of rows needed to display the whole page */
uint SettingsPage::Length() const
{
	uint length = 0;
	for (uint field = 0; field < this->num; field++) {
		length += this->entries[field].Length();
	}
	return length;
}

/**
 * Find the setting entry at row number \a row_num
 * @param row_num Index of entry to return
 * @param cur_row Variable used for keeping track of the current row number. Should point to memory initialized to \c 0 when first called.
 * @return The requested setting entry or \c NULL if it does not exist
 */
SettingEntry *SettingsPage::FindEntry(uint row_num, uint *cur_row) const
{
	SettingEntry *pe = NULL;

	for (uint field = 0; field < this->num; field++) {
		pe = this->entries[field].FindEntry(row_num, cur_row);
		if (pe != NULL) {
			break;
		}
	}
	return pe;
}

/**
 * Draw a selected part of the settings page.
 *
 * The scrollbar uses rows of the page, while the page data strucure is a tree of #SettingsPage and #SettingEntry objects.
 * As a result, the drawing routing traverses the tree from top to bottom, counting rows in \a cur_row until it reaches \a first_row.
 * Then it enables drawing rows while traversing until \a max_row is reached, at which point drawing is terminated.
 *
 * @param settings_ptr Pointer to current values of all settings
 * @param base_x       Left-most position in window/panel to start drawing of each setting row
 * @param base_y       Upper-most position in window/panel to start drawing of row number \a first_row
 * @param max_x        The maximum x position to draw strings add.
 * @param first_row    Number of first row to draw
 * @param max_row      Row-number to stop drawing (the row-number of the row below the last row to draw)
 * @param cur_row      Current row number (internal variable)
 * @param parent_last  Last-field booleans of parent page level (page level \e i sets bit \e i to 1 if it is its last field)
 * @return Row number of the next row to draw
 */
uint SettingsPage::Draw(GameSettings *settings_ptr, int base_x, int base_y, int max_x, uint first_row, uint max_row, uint cur_row, uint parent_last) const
{
	if (cur_row >= max_row) return cur_row;

	for (uint i = 0; i < this->num; i++) {
		cur_row = this->entries[i].Draw(settings_ptr, base_x, base_y, max_x, first_row, max_row, cur_row, parent_last);
		if (cur_row >= max_row) {
			break;
		}
	}
	return cur_row;
}


static SettingEntry _settings_ui_display[] = {
	SettingEntry("gui.vehicle_speed"),
	SettingEntry("gui.status_long_date"),
	SettingEntry("gui.date_format_in_default_names"),
	SettingEntry("gui.population_in_label"),
	SettingEntry("gui.measure_tooltip"),
	SettingEntry("gui.loading_indicators"),
	SettingEntry("gui.liveries"),
	SettingEntry("gui.show_track_reservation"),
	SettingEntry("gui.expenses_layout"),
};
/** Display options sub-page */
static SettingsPage _settings_ui_display_page = {_settings_ui_display, lengthof(_settings_ui_display)};

static SettingEntry _settings_ui_interaction[] = {
	SettingEntry("gui.window_snap_radius"),
	SettingEntry("gui.window_soft_limit"),
	SettingEntry("gui.link_terraform_toolbar"),
	SettingEntry("gui.prefer_teamchat"),
	SettingEntry("gui.autoscroll"),
	SettingEntry("gui.reverse_scroll"),
	SettingEntry("gui.smooth_scroll"),
	SettingEntry("gui.left_mouse_btn_scrolling"),
	/* While the horizontal scrollwheel scrolling is written as general code, only
	 *  the cocoa (OSX) driver generates input for it.
	 *  Since it's also able to completely disable the scrollwheel will we display it on all platforms anyway */
	SettingEntry("gui.scrollwheel_scrolling"),
	SettingEntry("gui.scrollwheel_multiplier"),
#ifdef __APPLE__
	/* We might need to emulate a right mouse button on mac */
	SettingEntry("gui.right_mouse_btn_emulation"),
#endif
};
/** Interaction sub-page */
static SettingsPage _settings_ui_interaction_page = {_settings_ui_interaction, lengthof(_settings_ui_interaction)};

static SettingEntry _settings_ui[] = {
	SettingEntry(&_settings_ui_display_page, STR_CONFIG_SETTING_DISPLAY_OPTIONS),
	SettingEntry(&_settings_ui_interaction_page, STR_CONFIG_SETTING_INTERACTION),
	SettingEntry("gui.show_finances"),
	SettingEntry("gui.errmsg_duration"),
	SettingEntry("gui.toolbar_pos"),
	SettingEntry("gui.pause_on_newgame"),
	SettingEntry("gui.advanced_vehicle_list"),
	SettingEntry("gui.timetable_in_ticks"),
	SettingEntry("gui.quick_goto"),
	SettingEntry("gui.default_rail_type"),
	SettingEntry("gui.always_build_infrastructure"),
	SettingEntry("gui.persistent_buildingtools"),
	SettingEntry("gui.coloured_news_year"),
};
/** Interface subpage */
static SettingsPage _settings_ui_page = {_settings_ui, lengthof(_settings_ui)};

static SettingEntry _settings_construction_signals[] = {
	SettingEntry("construction.signal_side"),
	SettingEntry("gui.enable_signal_gui"),
	SettingEntry("gui.drag_signals_density"),
	SettingEntry("gui.semaphore_build_before"),
	SettingEntry("gui.default_signal_type"),
	SettingEntry("gui.cycle_signal_types"),
};
/** Signals subpage */
static SettingsPage _settings_construction_signals_page = {_settings_construction_signals, lengthof(_settings_construction_signals)};

static SettingEntry _settings_construction[] = {
	SettingEntry(&_settings_construction_signals_page, STR_CONFIG_SETTING_CONSTRUCTION_SIGNALS),
	SettingEntry("construction.build_on_slopes"),
	SettingEntry("construction.autoslope"),
	SettingEntry("construction.extra_dynamite"),
	SettingEntry("construction.longbridges"),
	SettingEntry("station.never_expire_airports"),
	SettingEntry("construction.freeform_edges"),
};
/** Construction sub-page */
static SettingsPage _settings_construction_page = {_settings_construction, lengthof(_settings_construction)};

static SettingEntry _settings_stations_cargo[] = {
	SettingEntry("order.improved_load"),
	SettingEntry("order.gradual_loading"),
	SettingEntry("order.selectgoods"),
};
/** Cargo handling sub-page */
static SettingsPage _settings_stations_cargo_page = {_settings_stations_cargo, lengthof(_settings_stations_cargo)};

static SettingEntry _settings_stations[] = {
	SettingEntry(&_settings_stations_cargo_page, STR_CONFIG_SETTING_STATIONS_CARGOHANDLING),
	SettingEntry("station.join_stations"),
	SettingEntry("station.nonuniform_stations"),
	SettingEntry("station.adjacent_stations"),
	SettingEntry("station.distant_join_stations"),
	SettingEntry("station.station_spread"),
	SettingEntry("economy.station_noise_level"),
	SettingEntry("station.modified_catchment"),
	SettingEntry("construction.road_stop_on_town_road"),
	SettingEntry("construction.road_stop_on_competitor_road"),
};
/** Stations sub-page */
static SettingsPage _settings_stations_page = {_settings_stations, lengthof(_settings_stations)};

static SettingEntry _settings_economy_towns[] = {
	SettingEntry("economy.bribe"),
	SettingEntry("economy.exclusive_rights"),
	SettingEntry("economy.town_layout"),
	SettingEntry("economy.allow_town_roads"),
	SettingEntry("economy.mod_road_rebuild"),
	SettingEntry("economy.town_growth_rate"),
	SettingEntry("economy.larger_towns"),
	SettingEntry("economy.initial_city_size"),
};
/** Towns sub-page */
static SettingsPage _settings_economy_towns_page = {_settings_economy_towns, lengthof(_settings_economy_towns)};

static SettingEntry _settings_economy_industries[] = {
	SettingEntry("construction.raw_industry_construction"),
	SettingEntry("economy.multiple_industry_per_town"),
	SettingEntry("economy.same_industry_close"),
	SettingEntry("game_creation.oil_refinery_limit"),
};
/** Industries sub-page */
static SettingsPage _settings_economy_industries_page = {_settings_economy_industries, lengthof(_settings_economy_industries)};

static SettingEntry _settings_economy[] = {
	SettingEntry(&_settings_economy_towns_page, STR_CONFIG_SETTING_ECONOMY_TOWNS),
	SettingEntry(&_settings_economy_industries_page, STR_CONFIG_SETTING_ECONOMY_INDUSTRIES),
	SettingEntry("economy.inflation"),
	SettingEntry("economy.smooth_economy"),
};
/** Economy sub-page */
static SettingsPage _settings_economy_page = {_settings_economy, lengthof(_settings_economy)};

static SettingEntry _settings_ai_npc[] = {
	SettingEntry("ai.ai_in_multiplayer"),
	SettingEntry("ai.ai_disable_veh_train"),
	SettingEntry("ai.ai_disable_veh_roadveh"),
	SettingEntry("ai.ai_disable_veh_aircraft"),
	SettingEntry("ai.ai_disable_veh_ship"),
	SettingEntry("ai.ai_max_opcode_till_suspend"),
};
/** Computer players sub-page */
static SettingsPage _settings_ai_npc_page = {_settings_ai_npc, lengthof(_settings_ai_npc)};

static SettingEntry _settings_ai[] = {
	SettingEntry(&_settings_ai_npc_page, STR_CONFIG_SETTING_AI_NPC),
	SettingEntry("economy.give_money"),
	SettingEntry("economy.allow_shares"),
};
/** AI sub-page */
static SettingsPage _settings_ai_page = {_settings_ai, lengthof(_settings_ai)};

static SettingEntry _settings_vehicles_routing[] = {
	SettingEntry("pf.pathfinder_for_trains"),
	SettingEntry("pf.forbid_90_deg"),
	SettingEntry("pf.pathfinder_for_roadvehs"),
	SettingEntry("pf.roadveh_queue"),
	SettingEntry("pf.pathfinder_for_ships"),
};
/** Autorenew sub-page */
static SettingsPage _settings_vehicles_routing_page = {_settings_vehicles_routing, lengthof(_settings_vehicles_routing)};

static SettingEntry _settings_vehicles_autorenew[] = {
	SettingEntry("company.engine_renew"),
	SettingEntry("company.engine_renew_months"),
	SettingEntry("company.engine_renew_money"),
};
/** Autorenew sub-page */
static SettingsPage _settings_vehicles_autorenew_page = {_settings_vehicles_autorenew, lengthof(_settings_vehicles_autorenew)};

static SettingEntry _settings_vehicles_servicing[] = {
	SettingEntry("vehicle.servint_ispercent"),
	SettingEntry("vehicle.servint_trains"),
	SettingEntry("vehicle.servint_roadveh"),
	SettingEntry("vehicle.servint_ships"),
	SettingEntry("vehicle.servint_aircraft"),
	SettingEntry("order.no_servicing_if_no_breakdowns"),
	SettingEntry("order.serviceathelipad"),
};
/** Servicing sub-page */
static SettingsPage _settings_vehicles_servicing_page = {_settings_vehicles_servicing, lengthof(_settings_vehicles_servicing)};

static SettingEntry _settings_vehicles_trains[] = {
	SettingEntry("vehicle.train_acceleration_model"),
	SettingEntry("vehicle.mammoth_trains"),
	SettingEntry("gui.lost_train_warn"),
	SettingEntry("vehicle.wagon_speed_limits"),
	SettingEntry("vehicle.disable_elrails"),
	SettingEntry("vehicle.freight_trains"),
	SettingEntry("gui.stop_location"),
};
/** Trains sub-page */
static SettingsPage _settings_vehicles_trains_page = {_settings_vehicles_trains, lengthof(_settings_vehicles_trains)};

static SettingEntry _settings_vehicles[] = {
	SettingEntry(&_settings_vehicles_routing_page, STR_CONFIG_SETTING_VEHICLES_ROUTING),
	SettingEntry(&_settings_vehicles_autorenew_page, STR_CONFIG_SETTING_VEHICLES_AUTORENEW),
	SettingEntry(&_settings_vehicles_servicing_page, STR_CONFIG_SETTING_VEHICLES_SERVICING),
	SettingEntry(&_settings_vehicles_trains_page, STR_CONFIG_SETTING_VEHICLES_TRAINS),
	SettingEntry("order.gotodepot"),
	SettingEntry("gui.new_nonstop"),
	SettingEntry("gui.order_review_system"),
	SettingEntry("gui.vehicle_income_warn"),
	SettingEntry("vehicle.never_expire_vehicles"),
	SettingEntry("vehicle.max_trains"),
	SettingEntry("vehicle.max_roadveh"),
	SettingEntry("vehicle.max_aircraft"),
	SettingEntry("vehicle.max_ships"),
	SettingEntry("vehicle.plane_speed"),
	SettingEntry("order.timetabling"),
	SettingEntry("vehicle.dynamic_engines"),
};
/** Vehicles sub-page */
static SettingsPage _settings_vehicles_page = {_settings_vehicles, lengthof(_settings_vehicles)};

static SettingEntry _settings_main[] = {
	SettingEntry(&_settings_ui_page,           STR_CONFIG_SETTING_GUI),
	SettingEntry(&_settings_construction_page, STR_CONFIG_SETTING_CONSTRUCTION),
	SettingEntry(&_settings_vehicles_page,     STR_CONFIG_SETTING_VEHICLES),
	SettingEntry(&_settings_stations_page,     STR_CONFIG_SETTING_STATIONS),
	SettingEntry(&_settings_economy_page,      STR_CONFIG_SETTING_ECONOMY),
	SettingEntry(&_settings_ai_page,           STR_CONFIG_SETTING_AI),
};

/** Main page, holding all advanced settings */
static SettingsPage _settings_main_page = {_settings_main, lengthof(_settings_main)};

/** Widget numbers of settings window */
enum GameSettingsWidgets {
	SETTINGSEL_CLOSEBOX,     ///< Close box at top-left
	SETTINGSEL_CAPTION,      ///< Title bar
	SETTINGSEL_OPTIONSPANEL, ///< Panel widget containing the option lists
	SETTINGSEL_SCROLLBAR,    ///< Scrollbar
	SETTINGSEL_RESIZE,       ///< Resize button
};

struct GameSettingsWindow : Window {
	static const int SETTINGTREE_LEFT_OFFSET; ///< Position of left edge of setting values
	static const int SETTINGTREE_TOP_OFFSET;  ///< Position of top edge of setting values

	static GameSettings *settings_ptr;  ///< Pointer to the game settings being displayed and modified

	SettingEntry *valuewindow_entry; ///< If non-NULL, pointer to setting for which a value-entering window has been opened
	SettingEntry *clicked_entry; ///< If non-NULL, pointer to a clicked numeric setting (with a depressed left or right button)

	GameSettingsWindow(const WindowDesc *desc) : Window(desc)
	{
		/* Check that the widget doesn't get moved without adapting the constant as well.
		 *  - SETTINGTREE_LEFT_OFFSET should be 5 pixels to the right of the left edge of the panel
		 *  - SETTINGTREE_TOP_OFFSET should be 5 pixels below the top edge of the panel
		 */
		assert(this->widget[SETTINGSEL_OPTIONSPANEL].left + 5 == SETTINGTREE_LEFT_OFFSET);
		assert(this->widget[SETTINGSEL_OPTIONSPANEL].top + 5 == SETTINGTREE_TOP_OFFSET);

		static bool first_time = true;

		settings_ptr = (_game_mode == GM_MENU) ? &_settings_newgame : &_settings_game;

		/* Build up the dynamic settings-array only once per OpenTTD session */
		if (first_time) {
			_settings_main_page.Init();
			first_time = false;
		} else {
			_settings_main_page.FoldAll(); // Close all sub-pages
		}

		this->valuewindow_entry = NULL; // No setting entry for which a entry window is opened
		this->clicked_entry = NULL; // No numeric setting buttons are depressed
		this->vscroll.pos = 0;
		this->vscroll.cap = (this->widget[SETTINGSEL_OPTIONSPANEL].bottom - this->widget[SETTINGSEL_OPTIONSPANEL].top - 8) / SETTING_HEIGHT;
		SetVScrollCount(this, _settings_main_page.Length());

		this->resize.step_height = SETTING_HEIGHT;
		this->resize.height = this->height;
		this->resize.step_width = 1;
		this->resize.width = this->width;

		this->FindWindowPlacementAndResize(desc);
	}

	virtual void OnPaint()
	{
		this->DrawWidgets();
		_settings_main_page.Draw(settings_ptr, SETTINGTREE_LEFT_OFFSET, SETTINGTREE_TOP_OFFSET,
				this->width - 13, this->vscroll.pos, this->vscroll.pos + this->vscroll.cap);
	}

	virtual void OnClick(Point pt, int widget)
	{
		if (widget != SETTINGSEL_OPTIONSPANEL) return;

		int y = pt.y - SETTINGTREE_TOP_OFFSET;  // Shift y coordinate
		if (y < 0) return;  // Clicked above first entry

		byte btn = this->vscroll.pos + y / SETTING_HEIGHT;  // Compute which setting is selected
		if (y % SETTING_HEIGHT > SETTING_HEIGHT - 2) return;  // Clicked too low at the setting

		uint cur_row = 0;
		SettingEntry *pe = _settings_main_page.FindEntry(btn, &cur_row);

		if (pe == NULL) return;  // Clicked below the last setting of the page

		int x = pt.x - SETTINGTREE_LEFT_OFFSET - (pe->level + 1) * LEVEL_WIDTH;  // Shift x coordinate
		if (x < 0) return;  // Clicked left of the entry

		if ((pe->flags & SEF_KIND_MASK) == SEF_SUBTREE_KIND) {
			pe->d.sub.folded = !pe->d.sub.folded; // Flip 'folded'-ness of the sub-page

			SetVScrollCount(this, _settings_main_page.Length());
			this->SetDirty();
			return;
		}

		assert((pe->flags & SEF_KIND_MASK) == SEF_SETTING_KIND);
		const SettingDesc *sd = pe->d.entry.setting;

		/* return if action is only active in network, or only settable by server */
		if (!(sd->save.conv & SLF_NETWORK_NO) && _networking && !_network_server && !(sd->desc.flags & SGF_PER_COMPANY)) return;
		if ((sd->desc.flags & SGF_NETWORK_ONLY) && !_networking) return;
		if ((sd->desc.flags & SGF_NO_NETWORK) && _networking) return;

		const void *var = ResolveVariableAddress(settings_ptr, sd);
		int32 value = (int32)ReadValue(var, sd->save.conv);

		/* clicked on the icon on the left side. Either scroller or bool on/off */
		if (x < 21) {
			const SettingDescBase *sdb = &sd->desc;
			int32 oldvalue = value;

			switch (sdb->cmd) {
				case SDT_BOOLX: value ^= 1; break;
				case SDT_ONEOFMANY:
				case SDT_NUMX: {
					/* Add a dynamic step-size to the scroller. In a maximum of
					 * 50-steps you should be able to get from min to max,
					 * unless specified otherwise in the 'interval' variable
					 * of the current setting. */
					uint32 step = (sdb->interval == 0) ? ((sdb->max - sdb->min) / 50) : sdb->interval;
					if (step == 0) step = 1;

					/* don't allow too fast scrolling */
					if ((this->flags4 & WF_TIMEOUT_MASK) > WF_TIMEOUT_TRIGGER) {
						_left_button_clicked = false;
						return;
					}

					/* Increase or decrease the value and clamp it to extremes */
					if (x >= 10) {
						value += step;
						if (sdb->min < 0) {
							assert((int32)sdb->max >= 0);
							if (value > (int32)sdb->max) value = (int32)sdb->max;
						} else {
							if ((uint32)value > sdb->max) value = (int32)sdb->max;
						}
						if (value < sdb->min) value = sdb->min; // skip between "disabled" and minimum
					} else {
						value -= step;
						if (value < sdb->min) value = (sdb->flags & SGF_0ISDISABLED) ? 0 : sdb->min;
					}

					/* Set up scroller timeout for numeric values */
					if (value != oldvalue && !(sd->desc.flags & SGF_MULTISTRING)) {
						if (this->clicked_entry != NULL) { // Release previous buttons if any
							this->clicked_entry->SetButtons(0);
						}
						this->clicked_entry = pe;
						this->clicked_entry->SetButtons((x >= 10) ? SEF_RIGHT_DEPRESSED : SEF_LEFT_DEPRESSED);
						this->flags4 |= WF_TIMEOUT_BEGIN;
						_left_button_clicked = false;
					}
				} break;

				default: NOT_REACHED();
			}

			if (value != oldvalue) {
				if ((sd->desc.flags & SGF_PER_COMPANY) != 0) {
					SetCompanySetting(pe->d.entry.index, value);
				} else {
					SetSettingValue(pe->d.entry.index, value);
				}
				this->SetDirty();
			}
		} else {
			/* only open editbox for types that its sensible for */
			if (sd->desc.cmd != SDT_BOOLX && !(sd->desc.flags & SGF_MULTISTRING)) {
				/* Show the correct currency-translated value */
				if (sd->desc.flags & SGF_CURRENCY) value *= _currency->rate;

				this->valuewindow_entry = pe;
				SetDParam(0, value);
				ShowQueryString(STR_CONFIG_SETTING_INT32, STR_CONFIG_SETTING_QUERY_CAPT, 10, 100, this, CS_NUMERAL, QSF_NONE);
			}
		}
	}

	virtual void OnTimeout()
	{
		if (this->clicked_entry != NULL) { // On timeout, release any depressed buttons
			this->clicked_entry->SetButtons(0);
			this->clicked_entry = NULL;
			this->SetDirty();
		}
	}

	virtual void OnQueryTextFinished(char *str)
	{
		if (!StrEmpty(str)) {
			assert(this->valuewindow_entry != NULL);
			assert((this->valuewindow_entry->flags & SEF_KIND_MASK) == SEF_SETTING_KIND);
			const SettingDesc *sd = this->valuewindow_entry->d.entry.setting;
			int32 value = atoi(str);

			/* Save the correct currency-translated value */
			if (sd->desc.flags & SGF_CURRENCY) value /= _currency->rate;

			if ((sd->desc.flags & SGF_PER_COMPANY) != 0) {
				SetCompanySetting(this->valuewindow_entry->d.entry.index, value);
			} else {
				SetSettingValue(this->valuewindow_entry->d.entry.index, value);
			}
			this->SetDirty();
		}
	}

	virtual void OnResize(Point delta)
	{
		this->vscroll.cap += delta.y / SETTING_HEIGHT;
		SetVScrollCount(this, _settings_main_page.Length());
	}
};

GameSettings *GameSettingsWindow::settings_ptr = NULL;
const int GameSettingsWindow::SETTINGTREE_LEFT_OFFSET = 5;
const int GameSettingsWindow::SETTINGTREE_TOP_OFFSET = 19;

static const Widget _settings_selection_widgets[] = {
{   WWT_CLOSEBOX,   RESIZE_NONE,  COLOUR_MAUVE,     0,    10,     0,    13, STR_BLACK_CROSS,                 STR_TOOLTIP_CLOSE_WINDOW},             // SETTINGSEL_CLOSEBOX
{    WWT_CAPTION,  RESIZE_RIGHT,  COLOUR_MAUVE,    11,   411,     0,    13, STR_CONFIG_SETTING_CAPTION,      STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS},   // SETTINGSEL_CAPTION
{      WWT_PANEL,     RESIZE_RB,  COLOUR_MAUVE,     0,   399,    14,   187, 0x0,                             STR_NULL},                             // SETTINGSEL_OPTIONSPANEL
{  WWT_SCROLLBAR,    RESIZE_LRB,  COLOUR_MAUVE,   400,   411,    14,   175, 0x0,                             STR_TOOLTIP_VSCROLL_BAR_SCROLLS_LIST}, // SETTINGSEL_SCROLLBAR
{  WWT_RESIZEBOX,   RESIZE_LRTB,  COLOUR_MAUVE,   400,   411,   176,   187, 0x0,                             STR_RESIZE_BUTTON},                    // SETTINGSEL_RESIZE
{   WIDGETS_END},
};

static const NWidgetPart _nested_settings_selection_widgets[] = {
	NWidget(NWID_HORIZONTAL),
		NWidget(WWT_CLOSEBOX, COLOUR_MAUVE, SETTINGSEL_CLOSEBOX),
		NWidget(WWT_CAPTION, COLOUR_MAUVE, SETTINGSEL_CAPTION), SetDataTip(STR_CONFIG_SETTING_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
	EndContainer(),
	NWidget(NWID_HORIZONTAL),
		NWidget(WWT_PANEL, COLOUR_MAUVE, SETTINGSEL_OPTIONSPANEL), SetMinimalSize(400, 174), SetResize(1, SETTING_HEIGHT), EndContainer(),
		NWidget(NWID_VERTICAL),
			NWidget(WWT_SCROLLBAR, COLOUR_MAUVE, SETTINGSEL_SCROLLBAR),
			NWidget(WWT_RESIZEBOX, COLOUR_MAUVE, SETTINGSEL_RESIZE),
		EndContainer(),
	EndContainer(),
};

static const WindowDesc _settings_selection_desc(
	WDP_CENTER, WDP_CENTER, 412, 188, 450, 397,
	WC_GAME_OPTIONS, WC_NONE,
	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_RESIZABLE,
	_settings_selection_widgets, _nested_settings_selection_widgets, lengthof(_nested_settings_selection_widgets)
);

void ShowGameSettings()
{
	DeleteWindowById(WC_GAME_OPTIONS, 0);
	new GameSettingsWindow(&_settings_selection_desc);
}


/**
 * Draw [<][>] boxes.
 * @param x the x position to draw
 * @param y the y position to draw
 * @param button_colour the colour of the button
 * @param state 0 = none clicked, 1 = first clicked, 2 = second clicked
 * @param clickable_left is the left button clickable?
 * @param clickable_right is the right button clickable?
 */
void DrawArrowButtons(int x, int y, Colours button_colour, byte state, bool clickable_left, bool clickable_right)
{
	int colour = _colour_gradient[button_colour][2];

	DrawFrameRect(x,      y + 1, x +  9, y + 9, button_colour, (state == 1) ? FR_LOWERED : FR_NONE);
	DrawFrameRect(x + 10, y + 1, x + 19, y + 9, button_colour, (state == 2) ? FR_LOWERED : FR_NONE);
	DrawString(x,      x +  9, y + 1, STR_ARROW_LEFT_SMALL, TC_FROMSTRING, SA_CENTER); // [<]
	DrawString(x + 10, x + 19, y + 1, STR_ARROW_RIGHT_SMALL, TC_FROMSTRING, SA_CENTER); // [>]

	/* Grey out the buttons that aren't clickable */
	if (!clickable_left) {
		GfxFillRect(x +  1, y + 1, x +  1 + 8, y + 8, colour, FILLRECT_CHECKER);
	}
	if (!clickable_right) {
		GfxFillRect(x + 11, y + 1, x + 11 + 8, y + 8, colour, FILLRECT_CHECKER);
	}
}

/** Widget numbers of the custom currency window. */
enum CustomCurrencyWidgets {
	CUSTCURR_CLOSEBOX,
	CUSTCURR_CAPTION,
	CUSTCURR_BACKGROUND,

	CUSTCURR_RATE_DOWN,
	CUSTCURR_RATE_UP,
	CUSTCURR_RATE,
	CUSTCURR_SEPARATOR_EDIT,
	CUSTCURR_SEPARATOR,
	CUSTCURR_PREFIX_EDIT,
	CUSTCURR_PREFIX,
	CUSTCURR_SUFFIX_EDIT,
	CUSTCURR_SUFFIX,
	CUSTCURR_YEAR_DOWN,
	CUSTCURR_YEAR_UP,
	CUSTCURR_YEAR,
	CUSTCURR_PREVIEW,
};

struct CustomCurrencyWindow : Window {
	int query_widget;

	CustomCurrencyWindow(const WindowDesc *desc) : Window(desc)
	{
		this->FindWindowPlacementAndResize(desc);

		SetButtonState();
	}

	void SetButtonState()
	{
		this->SetWidgetDisabledState(CUSTCURR_RATE_DOWN, _custom_currency.rate == 1);
		this->SetWidgetDisabledState(CUSTCURR_RATE_UP, _custom_currency.rate == UINT16_MAX);
		this->SetWidgetDisabledState(CUSTCURR_YEAR_DOWN, _custom_currency.to_euro == CF_NOEURO);
		this->SetWidgetDisabledState(CUSTCURR_YEAR_UP, _custom_currency.to_euro == MAX_YEAR);
	}

	virtual void OnPaint()
	{
		SetDParam(0, 1);
		SetDParam(1, 1);
		SetDParamStr(2, _custom_currency.separator);
		SetDParamStr(3, _custom_currency.prefix);
		SetDParamStr(4, _custom_currency.suffix);
		SetDParam(5, _custom_currency.to_euro);
		this->widget[CUSTCURR_YEAR].data = (_custom_currency.to_euro != CF_NOEURO) ? STR_CURRENCY_SWITCH_TO_EURO : STR_CURRENCY_SWITCH_TO_EURO_NEVER;
		SetDParam(6, 10000);
		this->DrawWidgets();
	}

	virtual void OnClick(Point pt, int widget)
	{
		int line = 0;
		int len = 0;
		StringID str = 0;
		CharSetFilter afilter = CS_ALPHANUMERAL;

		switch (widget) {
			case CUSTCURR_RATE_DOWN:
				if (_custom_currency.rate > 1) _custom_currency.rate--;
				if (_custom_currency.rate == 1) this->DisableWidget(CUSTCURR_RATE_DOWN);
				this->EnableWidget(CUSTCURR_RATE_UP);
				break;

			case CUSTCURR_RATE_UP:
				if (_custom_currency.rate < UINT16_MAX) _custom_currency.rate++;
				if (_custom_currency.rate == UINT16_MAX) this->DisableWidget(CUSTCURR_RATE_UP);
				this->EnableWidget(CUSTCURR_RATE_DOWN);
				break;

			case CUSTCURR_RATE:
				SetDParam(0, _custom_currency.rate);
				str = STR_CONFIG_SETTING_INT32;
				len = 5;
				line = CUSTCURR_RATE;
				afilter = CS_NUMERAL;
				break;

			case CUSTCURR_SEPARATOR_EDIT:
			case CUSTCURR_SEPARATOR:
				SetDParamStr(0, _custom_currency.separator);
				str = STR_JUST_RAW_STRING;
				len = 1;
				line = CUSTCURR_SEPARATOR;
				break;

			case CUSTCURR_PREFIX_EDIT:
			case CUSTCURR_PREFIX:
				SetDParamStr(0, _custom_currency.prefix);
				str = STR_JUST_RAW_STRING;
				len = 12;
				line = CUSTCURR_PREFIX;
				break;

			case CUSTCURR_SUFFIX_EDIT:
			case CUSTCURR_SUFFIX:
				SetDParamStr(0, _custom_currency.suffix);
				str = STR_JUST_RAW_STRING;
				len = 12;
				line = CUSTCURR_SUFFIX;
				break;

			case CUSTCURR_YEAR_DOWN:
				_custom_currency.to_euro = (_custom_currency.to_euro <= 2000) ? CF_NOEURO : _custom_currency.to_euro - 1;
				if (_custom_currency.to_euro == CF_NOEURO) this->DisableWidget(CUSTCURR_YEAR_DOWN);
				this->EnableWidget(CUSTCURR_YEAR_UP);
				break;

			case CUSTCURR_YEAR_UP:
				_custom_currency.to_euro = Clamp(_custom_currency.to_euro + 1, 2000, MAX_YEAR);
				if (_custom_currency.to_euro == MAX_YEAR) this->DisableWidget(CUSTCURR_YEAR_UP);
				this->EnableWidget(CUSTCURR_YEAR_DOWN);
				break;

			case CUSTCURR_YEAR:
				SetDParam(0, _custom_currency.to_euro);
				str = STR_CONFIG_SETTING_INT32;
				len = 7;
				line = CUSTCURR_YEAR;
				afilter = CS_NUMERAL;
				break;
		}

		if (len != 0) {
			this->query_widget = line;
			ShowQueryString(str, STR_CURRENCY_CHANGE_PARAMETER, len + 1, 250, this, afilter, QSF_NONE);
		}

		this->flags4 |= WF_TIMEOUT_BEGIN;
		this->SetDirty();
	}

	virtual void OnQueryTextFinished(char *str)
	{
		if (str == NULL) return;

		switch (this->query_widget) {
			case CUSTCURR_RATE:
				_custom_currency.rate = Clamp(atoi(str), 1, UINT16_MAX);
				break;

			case CUSTCURR_SEPARATOR: // Thousands seperator
				strecpy(_custom_currency.separator, str, lastof(_custom_currency.separator));
				break;

			case CUSTCURR_PREFIX:
				strecpy(_custom_currency.prefix, str, lastof(_custom_currency.prefix));
				break;

			case CUSTCURR_SUFFIX:
				strecpy(_custom_currency.suffix, str, lastof(_custom_currency.suffix));
				break;

			case CUSTCURR_YEAR: { // Year to switch to euro
				int val = atoi(str);

				_custom_currency.to_euro = (val < 2000 ? CF_NOEURO : min(val, MAX_YEAR));
				break;
			}
		}
		MarkWholeScreenDirty();
		SetButtonState();
	}

	virtual void OnTimeout()
	{
		this->SetDirty();
	}
};

static const Widget _cust_currency_widgets[] = {
{   WWT_CLOSEBOX,   RESIZE_NONE,  COLOUR_GREY,       0,    10,     0,    13, STR_BLACK_CROSS,             STR_TOOLTIP_CLOSE_WINDOW},                     // CUSTCURR_CLOSEBOX
{    WWT_CAPTION,   RESIZE_NONE,  COLOUR_GREY,      11,   229,     0,    13, STR_CURRENCY_WINDOW,         STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS},           // CUSTCURR_CAPTION
{      WWT_PANEL,   RESIZE_NONE,  COLOUR_GREY,       0,   229,    14,   119, 0x0,                         STR_NULL},                                     // CUSTCURR_BACKGROUND

{ WWT_PUSHTXTBTN,   RESIZE_NONE,  COLOUR_YELLOW,    10,    19,    21,    29, STR_ARROW_LEFT_SMALL,        STR_TOOLTIP_DECREASE_EXCHANGE_RATE},           // CUSTCURR_RATE_DOWN
{ WWT_PUSHTXTBTN,   RESIZE_NONE,  COLOUR_YELLOW,    20,    29,    21,    29, STR_ARROW_RIGHT_SMALL,       STR_TOOLTIP_INCREASE_EXCHANGE_RATE},           // CUSTCURR_RATE_UP
{       WWT_TEXT,   RESIZE_NONE,  COLOUR_BLUE,      35,   227,    21,    29, STR_CURRENCY_EXCHANGE_RATE,  STR_TOOLTIP_SET_EXCHANGE_RATE},                // CUSTCURR_RATE

{    WWT_PUSHBTN,   RESIZE_NONE,  COLOUR_DARK_BLUE, 10,    29,    33,    41, 0x0,                         STR_TOOLTIP_SET_CUSTOM_CURRENCY_SEPARATOR},    // CUSTCURR_SEPARATOR_EDIT
{       WWT_TEXT,   RESIZE_NONE,  COLOUR_BLUE,      35,   227,    33,    41, STR_CURRENCY_SEPARATOR,      STR_TOOLTIP_SET_CUSTOM_CURRENCY_SEPARATOR},    // CUSTCURR_SEPARATOR

{    WWT_PUSHBTN,   RESIZE_NONE,  COLOUR_DARK_BLUE, 10,    29,    45,    53, 0x0,                         STR_TOOLTIP_SET_CUSTOM_CURRENCY_PREFIX},       // CUSTCURR_PREFIX_EDIT
{       WWT_TEXT,   RESIZE_NONE,  COLOUR_BLUE,      35,   227,    45,    53, STR_CURRENCY_PREFIX,         STR_TOOLTIP_SET_CUSTOM_CURRENCY_PREFIX},       // CUSTCURR_PREFIX

{    WWT_PUSHBTN,   RESIZE_NONE,  COLOUR_DARK_BLUE, 10,    29,    57,    65, 0x0,                         STR_TOOLTIP_SET_CUSTOM_CURRENCY_SUFFIX},       // CUSTCURR_SUFFIX_EDIT
{       WWT_TEXT,   RESIZE_NONE,  COLOUR_BLUE,      35,   227,    57,    65, STR_CURRENCY_SUFFIX,         STR_TOOLTIP_SET_CUSTOM_CURRENCY_SUFFIX},       // CUSTCURR_SUFFIX

{ WWT_PUSHTXTBTN,   RESIZE_NONE,  COLOUR_YELLOW,    10,    19,    69,    77, STR_ARROW_LEFT_SMALL,        STR_TOOLTIP_DECREASE_CUSTOM_CURRENCY_TO_EURO}, // CUSTCURR_YEAR_DOWN
{ WWT_PUSHTXTBTN,   RESIZE_NONE,  COLOUR_YELLOW,    20,    29,    69,    77, STR_ARROW_RIGHT_SMALL,       STR_TOOLTIP_INCREASE_CUSTOM_CURRENCY_TO_EURO}, // CUSTCURR_YEAR_UP
{       WWT_TEXT,   RESIZE_NONE,  COLOUR_BLUE,      35,   227,    69,    77, STR_CURRENCY_SWITCH_TO_EURO, STR_TOOLTIP_SET_CUSTOM_CURRENCY_TO_EURO},      // CUSTCURR_YEAR

{      WWT_LABEL,   RESIZE_NONE,  COLOUR_BLUE,       2,   227,    93,   101, STR_CURRENCY_PREVIEW,        STR_TOOLTIP_CUSTOM_CURRENCY_PREVIEW},          // CUSTCURR_PREVIEW

{   WIDGETS_END},
};

static const NWidgetPart _nested_cust_currency_widgets[] = {
	NWidget(NWID_HORIZONTAL),
		NWidget(WWT_CLOSEBOX, COLOUR_GREY, CUSTCURR_CLOSEBOX),
		NWidget(WWT_CAPTION, COLOUR_GREY, CUSTCURR_CAPTION), SetDataTip(STR_CURRENCY_WINDOW, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
	EndContainer(),
	NWidget(WWT_PANEL, COLOUR_GREY, CUSTCURR_BACKGROUND),
		NWidget(NWID_SPACER), SetMinimalSize(0,7),
		NWidget(NWID_HORIZONTAL), SetPIP(10, 0, 2),
			NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, CUSTCURR_RATE_DOWN), SetMinimalSize(10, 9), SetDataTip(STR_ARROW_LEFT_SMALL, STR_TOOLTIP_DECREASE_EXCHANGE_RATE),
			NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, CUSTCURR_RATE_UP), SetMinimalSize(10, 9), SetDataTip(STR_ARROW_RIGHT_SMALL, STR_TOOLTIP_INCREASE_EXCHANGE_RATE),
			NWidget(NWID_SPACER), SetMinimalSize(5, 0),
			NWidget(WWT_TEXT, COLOUR_BLUE, CUSTCURR_RATE), SetMinimalSize(193, 9), SetDataTip(STR_CURRENCY_EXCHANGE_RATE, STR_TOOLTIP_SET_EXCHANGE_RATE),
			NWidget(NWID_SPACER), SetFill(1, 0),
		EndContainer(),
		NWidget(NWID_SPACER), SetMinimalSize(0, 3),
		NWidget(NWID_HORIZONTAL), SetPIP(10, 0, 2),
			NWidget(WWT_PUSHBTN, COLOUR_DARK_BLUE, CUSTCURR_SEPARATOR_EDIT), SetMinimalSize(20, 9), SetDataTip(0x0, STR_TOOLTIP_SET_CUSTOM_CURRENCY_SEPARATOR),
			NWidget(NWID_SPACER), SetMinimalSize(5, 0),
			NWidget(WWT_TEXT, COLOUR_BLUE, CUSTCURR_SEPARATOR), SetMinimalSize(193, 9), SetDataTip(STR_CURRENCY_SEPARATOR, STR_TOOLTIP_SET_CUSTOM_CURRENCY_SEPARATOR),
			NWidget(NWID_SPACER), SetFill(1, 0),
		EndContainer(),
		NWidget(NWID_SPACER), SetMinimalSize(0, 3),
		NWidget(NWID_HORIZONTAL), SetPIP(10, 0, 2),
			NWidget(WWT_PUSHBTN, COLOUR_DARK_BLUE, CUSTCURR_PREFIX_EDIT), SetMinimalSize(20, 9), SetDataTip(0x0, STR_TOOLTIP_SET_CUSTOM_CURRENCY_PREFIX),
			NWidget(NWID_SPACER), SetMinimalSize(5, 0),
			NWidget(WWT_TEXT, COLOUR_BLUE, CUSTCURR_PREFIX), SetMinimalSize(193, 9), SetDataTip(STR_CURRENCY_PREFIX, STR_TOOLTIP_SET_CUSTOM_CURRENCY_PREFIX),
			NWidget(NWID_SPACER), SetFill(1, 0),
		EndContainer(),
		NWidget(NWID_SPACER), SetMinimalSize(0, 3),
		NWidget(NWID_HORIZONTAL), SetPIP(10, 0, 2),
			NWidget(WWT_PUSHBTN, COLOUR_DARK_BLUE, CUSTCURR_SUFFIX_EDIT), SetMinimalSize(20, 9), SetDataTip(0x0, STR_TOOLTIP_SET_CUSTOM_CURRENCY_SUFFIX),
			NWidget(NWID_SPACER), SetMinimalSize(5, 0),
			NWidget(WWT_TEXT, COLOUR_BLUE, CUSTCURR_SUFFIX), SetMinimalSize(193, 9), SetDataTip(STR_CURRENCY_SUFFIX, STR_TOOLTIP_SET_CUSTOM_CURRENCY_SUFFIX),
			NWidget(NWID_SPACER), SetFill(1, 0),
		EndContainer(),
		NWidget(NWID_SPACER), SetMinimalSize(0, 3),
		NWidget(NWID_HORIZONTAL), SetPIP(10, 0, 2),
			NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, CUSTCURR_YEAR_DOWN), SetMinimalSize(10, 9), SetDataTip(STR_ARROW_LEFT_SMALL, STR_TOOLTIP_DECREASE_CUSTOM_CURRENCY_TO_EURO),
			NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, CUSTCURR_YEAR_UP), SetMinimalSize(10, 9), SetDataTip(STR_ARROW_RIGHT_SMALL, STR_TOOLTIP_INCREASE_CUSTOM_CURRENCY_TO_EURO),
			NWidget(NWID_SPACER), SetMinimalSize(5, 0),
			NWidget(WWT_TEXT, COLOUR_BLUE, CUSTCURR_YEAR), SetMinimalSize(193, 9), SetDataTip(STR_CURRENCY_SWITCH_TO_EURO, STR_TOOLTIP_SET_CUSTOM_CURRENCY_TO_EURO),
			NWidget(NWID_SPACER), SetFill(1, 0),
		EndContainer(),
		NWidget(WWT_LABEL, COLOUR_BLUE, CUSTCURR_PREVIEW), SetMinimalSize(226, 9),
								SetDataTip(STR_CURRENCY_PREVIEW, STR_TOOLTIP_CUSTOM_CURRENCY_PREVIEW), SetPadding(15, 1, 18, 2),
	EndContainer(),
};

static const WindowDesc _cust_currency_desc(
	WDP_CENTER, WDP_CENTER, 230, 120, 230, 120,
	WC_CUSTOM_CURRENCY, WC_NONE,
	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
	_cust_currency_widgets, _nested_cust_currency_widgets, lengthof(_nested_cust_currency_widgets)
);

static void ShowCustCurrency()
{
	DeleteWindowById(WC_CUSTOM_CURRENCY, 0);
	new CustomCurrencyWindow(&_cust_currency_desc);
}