summaryrefslogtreecommitdiff
path: root/misc_gui.c
blob: 10f53f7017904217bb3b0dea69b40339d5ca0542 (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
/* $Id$ */

#include "stdafx.h"
#include "openttd.h"
#include "hal.h"
#include "heightmap.h"
#include "debug.h"
#include "functions.h"
#include "gfxinit.h"
#include "saveload.h"
#include "strings.h"
#include "table/sprites.h"
#include "table/strings.h"
#include "table/tree_land.h"
#include "map.h"
#include "window.h"
#include "gui.h"
#include "viewport.h"
#include "gfx.h"
#include "station.h"
#include "command.h"
#include "player.h"
#include "town.h"
#include "sound.h"
#include "network.h"
#include "string.h"
#include "variables.h"
#include "vehicle.h"
#include "train.h"
#include "tgp.h"
#include "settings.h"
#include "date.h"
#include "resize_window_widgets.h"

#include "fios.h"
/* Variables to display file lists */
FiosItem *_fios_list;
int _saveload_mode;

extern void GenerateLandscape(byte mode);
extern void SwitchMode(int new_mode);

static bool _fios_path_changed;
static bool _savegame_sort_dirty;

typedef struct LandInfoData {
	Town *town;
	int32 costclear;
	AcceptedCargo ac;
	TileIndex tile;
	TileDesc td;
} LandInfoData;

static void LandInfoWndProc(Window *w, WindowEvent *e)
{
	if (e->event == WE_PAINT) {
		const LandInfoData *lid;
		StringID str;
		int i;

		DrawWindowWidgets(w);

		lid = WP(w,void_d).data;

		SetDParam(0, lid->td.dparam[0]);
		DrawStringCentered(140, 16, lid->td.str, 13);

		SetDParam(0, STR_01A6_N_A);
		if (lid->td.owner != OWNER_NONE && lid->td.owner != OWNER_WATER)
			GetNameOfOwner(lid->td.owner, lid->tile);
		DrawStringCentered(140, 27, STR_01A7_OWNER, 0);

		str = STR_01A4_COST_TO_CLEAR_N_A;
		if (!CmdFailed(lid->costclear)) {
			SetDParam(0, lid->costclear);
			str = STR_01A5_COST_TO_CLEAR;
		}
		DrawStringCentered(140, 38, str, 0);

		snprintf(_userstring, lengthof(_userstring), "0x%.4X", lid->tile);
		SetDParam(0, TileX(lid->tile));
		SetDParam(1, TileY(lid->tile));
		SetDParam(2, STR_SPEC_USERSTRING);
		DrawStringCentered(140, 49, STR_LANDINFO_COORDS, 0);

		SetDParam(0, STR_01A9_NONE);
		if (lid->town != NULL) {
			SetDParam(0, STR_TOWN);
			SetDParam(1, lid->town->index);
		}
		DrawStringCentered(140,60, STR_01A8_LOCAL_AUTHORITY, 0);

		{
			char buf[512];
			char *p = GetString(buf, STR_01CE_CARGO_ACCEPTED);
			bool found = false;

			for (i = 0; i < NUM_CARGO; ++i) {
				if (lid->ac[i] > 0) {
					// Add a comma between each item.
					if (found) {
						*p++ = ',';
						*p++ = ' ';
					}
					found = true;

					// If the accepted value is less than 8, show it in 1/8:ths
					if (lid->ac[i] < 8) {
						SetDParam(0, lid->ac[i]);
						SetDParam(1, _cargoc.names_s[i]);
						p = GetString(p, STR_01D1_8);
					} else {
						p = GetString(p, _cargoc.names_s[i]);
					}
				}
			}

			if (found) DrawStringMultiCenter(140, 76, BindCString(buf), 276);
		}

		if (lid->td.build_date != 0) {
			SetDParam(0,lid->td.build_date);
			DrawStringCentered(140,71, STR_BUILD_DATE, 0);
		}
	}
}

static const Widget _land_info_widgets[] = {
{   WWT_CLOSEBOX,   RESIZE_NONE,    14,     0,    10,     0,    13, STR_00C5,                       STR_018B_CLOSE_WINDOW},
{    WWT_CAPTION,   RESIZE_NONE,    14,    11,   279,     0,    13, STR_01A3_LAND_AREA_INFORMATION, STR_018C_WINDOW_TITLE_DRAG_THIS},
{     WWT_IMGBTN,   RESIZE_NONE,    14,     0,   279,    14,    92, 0x0,                            STR_NULL},
{    WIDGETS_END},
};

static const WindowDesc _land_info_desc = {
	-1, -1, 280, 93,
	WC_LAND_INFO,0,
	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
	_land_info_widgets,
	LandInfoWndProc
};

static void Place_LandInfo(TileIndex tile)
{
	Player *p;
	static LandInfoData lid;
	Window *w;
	int64 old_money;

	DeleteWindowById(WC_LAND_INFO, 0);

	w = AllocateWindowDesc(&_land_info_desc);
	WP(w,void_d).data = &lid;

	lid.tile = tile;
	lid.town = ClosestTownFromTile(tile, _patches.dist_local_authority);

	p = GetPlayer(_local_player < MAX_PLAYERS ? _local_player : 0);

	old_money = p->money64;
	p->money64 = p->player_money = 0x7fffffff;
	lid.costclear = DoCommand(tile, 0, 0, 0, CMD_LANDSCAPE_CLEAR);
	p->money64 = old_money;
	UpdatePlayerMoney32(p);

	// Becuase build_date is not set yet in every TileDesc, we make sure it is empty
	lid.td.build_date = 0;

	GetAcceptedCargo(tile, lid.ac);
	GetTileDesc(tile, &lid.td);

#if defined(_DEBUG)
#	define LANDINFOD_LEVEL 0
#else
#	define LANDINFOD_LEVEL 1
#endif
	DEBUG(misc, LANDINFOD_LEVEL) ("TILE: %#x (%i,%i)", tile, TileX(tile), TileY(tile));
	DEBUG(misc, LANDINFOD_LEVEL) ("type_height  = %#x", _m[tile].type_height);
	DEBUG(misc, LANDINFOD_LEVEL) ("m1           = %#x", _m[tile].m1);
	DEBUG(misc, LANDINFOD_LEVEL) ("m2           = %#x", _m[tile].m2);
	DEBUG(misc, LANDINFOD_LEVEL) ("m3           = %#x", _m[tile].m3);
	DEBUG(misc, LANDINFOD_LEVEL) ("m4           = %#x", _m[tile].m4);
	DEBUG(misc, LANDINFOD_LEVEL) ("m5           = %#x", _m[tile].m5);
	DEBUG(misc, LANDINFOD_LEVEL) ("extra        = %#x", _m[tile].extra);
#undef LANDINFOD_LEVEL
}

void PlaceLandBlockInfo(void)
{
	if (_cursor.sprite == SPR_CURSOR_QUERY) {
		ResetObjectToPlace();
	} else {
		_place_proc = Place_LandInfo;
		SetObjectToPlace(SPR_CURSOR_QUERY, 1, 1, 0);
	}
}

static const char *credits[] = {
	/*************************************************************************
	 *                      maximum length of string which fits in window   -^*/
	"Original design by Chris Sawyer",
	"Original graphics by Simon Foster",
	"",
	"The OpenTTD team (in alphabetical order):",
	"  Bjarni Corfitzen (Bjarni) - MacOSX port, coder",
	"  Matthijs Kooijman (blathijs) - Pathfinder-god",
	"  Victor Fischer (Celestar) - Programming everywhere you need him to",
	"  Tamás Faragó (Darkvater) - Lead coder",
	"  Attila Bán (MiHaMiX) - WebTranslator, Nightlies, Wiki and bugtracker host",
	"  Owen Rudge (orudge) - Forum- and masterserver host, OS/2 port",
	"  Peter Nelson (peter1138) - Spiritual descendant from newgrf gods",
	"  Christoph Mallon (Tron) - Programmer, code correctness police",
	"  Patric Stout (TrueLight) - Coder, network guru, SVN- and website host",
	"",
	"Retired Developers:",
	"  Ludvig Strigeus (ludde) - OpenTTD author, main coder (0.1 - 0.3.3)",
	"  Serge Paquet (vurlix) - Assistant project manager, coder (0.1 - 0.3.3)",
	"  Dominik Scherer (dominik81) - Lead programmer, GUI expert (0.3.0 - 0.3.6)",
	"",
	"Special thanks go out to:",
	"  Josef Drexler - For his great work on TTDPatch",
	"  Marcin Grzegorczyk - For his documentation of TTD internals",
	"  Petr Baudis (pasky) - Many patches, newgrf support",
	"  Stefan Meißner (sign_de) - For his work on the console",
	"  Simon Sasburg (HackyKid) - Many bugfixes he has blessed us with (and PBS)",
	"  Cian Duffy (MYOB) - BeOS port / manual writing",
	"  Christian Rosentreter (tokai) - MorphOS / AmigaOS port",
	"",
	"  Michael Blunck - Pre-Signals and Semaphores © 2003",
	"  George - Canal/Lock graphics © 2003-2004",
	"  Marcin Grzegorczyk - Foundations for Tracks on Slopes",
	"  All Translators - Who made OpenTTD a truly international game",
	"  Bug Reporters - Without whom OpenTTD would still be full of bugs!",
	"",
	"",
	"And last but not least:",
	"  Chris Sawyer - For an amazing game!"
};

static void AboutWindowProc(Window *w, WindowEvent *e)
{
	switch (e->event) {
	case WE_CREATE: /* Set up window counter and start position of scroller */
		WP(w, scroller_d).counter = 0;
		WP(w, scroller_d).height = w->height - 40;
		break;
	case WE_PAINT: {
		uint i;
		int y = WP(w, scroller_d).height;
		DrawWindowWidgets(w);

		// Show original copyright and revision version
		DrawStringCentered(210, 17, STR_00B6_ORIGINAL_COPYRIGHT, 0);
		DrawStringCentered(210, 17 + 10, STR_00B7_VERSION, 0);

		// Show all scrolling credits
		for (i = 0; i < lengthof(credits); i++) {
			if (y >= 50 && y < (w->height - 40)) {
				DoDrawString(credits[i], 10, y, 0x10);
			}
			y += 10;
		}

		// If the last text has scrolled start anew from the start
		if (y < 50) WP(w, scroller_d).height = w->height - 40;

		DoDrawStringCentered(210, w->height - 25, "Website: http://www.openttd.org", 16);
		DrawStringCentered(210, w->height - 15, STR_00BA_COPYRIGHT_OPENTTD, 0);
	}	break;
	case WE_MOUSELOOP: /* Timer to scroll the text and adjust the new top */
		if (WP(w, scroller_d).counter++ % 3 == 0) {
			WP(w, scroller_d).height--;
			SetWindowDirty(w);
		}
		break;
	}
}

static const Widget _about_widgets[] = {
{   WWT_CLOSEBOX,   RESIZE_NONE,    14,     0,    10,     0,    13, STR_00C5,         STR_018B_CLOSE_WINDOW},
{    WWT_CAPTION,   RESIZE_NONE,    14,    11,   419,     0,    13, STR_015B_OPENTTD, STR_NULL},
{      WWT_PANEL,   RESIZE_NONE,    14,     0,   419,    14,   271, 0x0,              STR_NULL},
{      WWT_FRAME,   RESIZE_NONE,    14,     5,   414,    40,   245, STR_NULL,         STR_NULL},
{    WIDGETS_END},
};

static const WindowDesc _about_desc = {
	WDP_CENTER, WDP_CENTER, 420, 272,
	WC_GAME_OPTIONS,0,
	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
	_about_widgets,
	AboutWindowProc
};


void ShowAboutWindow(void)
{
	DeleteWindowById(WC_GAME_OPTIONS, 0);
	AllocateWindowDesc(&_about_desc);
}

static int _tree_to_plant;

static const uint32 _tree_sprites[] = {
	0x655, 0x663, 0x678, 0x62B, 0x647, 0x639, 0x64E, 0x632, 0x67F, 0x68D, 0x69B, 0x6A9,
	0x6AF, 0x6D2, 0x6D9, 0x6C4, 0x6CB, 0x6B6, 0x6BD, 0x6E0,
	0x72E, 0x734, 0x74A, 0x74F, 0x76B, 0x78F, 0x788, 0x77B, 0x75F, 0x774, 0x720, 0x797,
	0x79E, 0x7A5 | PALETTE_TO_GREEN, 0x7AC | PALETTE_TO_RED, 0x7B3, 0x7BA, 0x7C1 | PALETTE_TO_RED, 0x7C8 | PALETTE_TO_PALE_GREEN, 0x7CF | PALETTE_TO_YELLOW, 0x7D6 | PALETTE_TO_RED
};

static void BuildTreesWndProc(Window *w, WindowEvent *e)
{
	switch (e->event) {
	case WE_PAINT: {
		int x,y;
		int i, count;

		DrawWindowWidgets(w);

		WP(w,tree_d).base = i = _tree_base_by_landscape[_opt.landscape];
		WP(w,tree_d).count = count = _tree_count_by_landscape[_opt.landscape];

		x = 18;
		y = 54;
		do {
			DrawSprite(_tree_sprites[i], x, y);
			x += 35;
			if (!(++i & 3)) {
				x -= 35 * 4;
				y += 47;
			}
		} while (--count);
	} break;

	case WE_CLICK: {
		int wid = e->we.click.widget;

		switch (wid) {
		case 0:
			ResetObjectToPlace();
			break;

		case 3: case 4: case 5: case 6:
		case 7: case 8: case 9: case 10:
		case 11:case 12: case 13: case 14:
			if (wid - 3 >= WP(w,tree_d).count) break;

			if (HandlePlacePushButton(w, wid, SPR_CURSOR_TREE, 1, NULL))
				_tree_to_plant = WP(w,tree_d).base + wid - 3;
			break;

		case 15: // tree of random type.
			if (HandlePlacePushButton(w, 15, SPR_CURSOR_TREE, 1, NULL))
				_tree_to_plant = -1;
			break;

		case 16: /* place trees randomly over the landscape*/
			w->click_state |= 1 << 16;
			w->flags4 |= 5 << WF_TIMEOUT_SHL;
			SndPlayFx(SND_15_BEEP);
			PlaceTreesRandomly();
			MarkWholeScreenDirty();
			break;
		}
	} break;

	case WE_PLACE_OBJ:
		VpStartPlaceSizing(e->we.place.tile, VPM_X_AND_Y_LIMITED);
		VpSetPlaceSizingLimit(20);
		break;

	case WE_PLACE_DRAG:
		VpSelectTilesWithMethod(e->we.place.pt.x, e->we.place.pt.y, e->we.place.userdata);
		return;

	case WE_PLACE_MOUSEUP:
		if (e->we.click.pt.x != -1) {
			DoCommandP(e->we.place.tile, _tree_to_plant, e->we.place.starttile, NULL,
				CMD_PLANT_TREE | CMD_AUTO | CMD_MSG(STR_2805_CAN_T_PLANT_TREE_HERE));
		}
		break;

	case WE_TIMEOUT:
		UnclickSomeWindowButtons(w, 1<<16);
		break;

	case WE_ABORT_PLACE_OBJ:
		w->click_state = 0;
		SetWindowDirty(w);
		break;
	}
}

static const Widget _build_trees_widgets[] = {
{   WWT_CLOSEBOX,   RESIZE_NONE,     7,     0,    10,     0,    13, STR_00C5,              STR_018B_CLOSE_WINDOW},
{    WWT_CAPTION,   RESIZE_NONE,     7,    11,   142,     0,    13, STR_2802_TREES,        STR_018C_WINDOW_TITLE_DRAG_THIS},
{      WWT_PANEL,   RESIZE_NONE,     7,     0,   142,    14,   170, 0x0,                   STR_NULL},
{      WWT_PANEL,   RESIZE_NONE,    14,     2,    35,    16,    61, 0x0,                   STR_280D_SELECT_TREE_TYPE_TO_PLANT},
{      WWT_PANEL,   RESIZE_NONE,    14,    37,    70,    16,    61, 0x0,                   STR_280D_SELECT_TREE_TYPE_TO_PLANT},
{      WWT_PANEL,   RESIZE_NONE,    14,    72,   105,    16,    61, 0x0,                   STR_280D_SELECT_TREE_TYPE_TO_PLANT},
{      WWT_PANEL,   RESIZE_NONE,    14,   107,   140,    16,    61, 0x0,                   STR_280D_SELECT_TREE_TYPE_TO_PLANT},
{      WWT_PANEL,   RESIZE_NONE,    14,     2,    35,    63,   108, 0x0,                   STR_280D_SELECT_TREE_TYPE_TO_PLANT},
{      WWT_PANEL,   RESIZE_NONE,    14,    37,    70,    63,   108, 0x0,                   STR_280D_SELECT_TREE_TYPE_TO_PLANT},
{      WWT_PANEL,   RESIZE_NONE,    14,    72,   105,    63,   108, 0x0,                   STR_280D_SELECT_TREE_TYPE_TO_PLANT},
{      WWT_PANEL,   RESIZE_NONE,    14,   107,   140,    63,   108, 0x0,                   STR_280D_SELECT_TREE_TYPE_TO_PLANT},
{      WWT_PANEL,   RESIZE_NONE,    14,     2,    35,   110,   155, 0x0,                   STR_280D_SELECT_TREE_TYPE_TO_PLANT},
{      WWT_PANEL,   RESIZE_NONE,    14,    37,    70,   110,   155, 0x0,                   STR_280D_SELECT_TREE_TYPE_TO_PLANT},
{      WWT_PANEL,   RESIZE_NONE,    14,    72,   105,   110,   155, 0x0,                   STR_280D_SELECT_TREE_TYPE_TO_PLANT},
{      WWT_PANEL,   RESIZE_NONE,    14,   107,   140,   110,   155, 0x0,                   STR_280D_SELECT_TREE_TYPE_TO_PLANT},
{    WWT_TEXTBTN,   RESIZE_NONE,    14,     2,   140,   157,   168, STR_TREES_RANDOM_TYPE, STR_TREES_RANDOM_TYPE_TIP},
{    WIDGETS_END},
};

static const WindowDesc _build_trees_desc = {
	497, 22, 143, 171,
	WC_BUILD_TREES, WC_SCEN_LAND_GEN,
	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
	_build_trees_widgets,
	BuildTreesWndProc
};

static const Widget _build_trees_scen_widgets[] = {
{   WWT_CLOSEBOX,   RESIZE_NONE,     7,     0,    10,     0,    13, STR_00C5,              STR_018B_CLOSE_WINDOW},
{    WWT_CAPTION,   RESIZE_NONE,     7,    11,   142,     0,    13, STR_2802_TREES,        STR_018C_WINDOW_TITLE_DRAG_THIS},
{      WWT_PANEL,   RESIZE_NONE,     7,     0,   142,    14,   183, 0x0,                   STR_NULL},
{      WWT_PANEL,   RESIZE_NONE,    14,     2,    35,    16,    61, 0x0,                   STR_280D_SELECT_TREE_TYPE_TO_PLANT},
{      WWT_PANEL,   RESIZE_NONE,    14,    37,    70,    16,    61, 0x0,                   STR_280D_SELECT_TREE_TYPE_TO_PLANT},
{      WWT_PANEL,   RESIZE_NONE,    14,    72,   105,    16,    61, 0x0,                   STR_280D_SELECT_TREE_TYPE_TO_PLANT},
{      WWT_PANEL,   RESIZE_NONE,    14,   107,   140,    16,    61, 0x0,                   STR_280D_SELECT_TREE_TYPE_TO_PLANT},
{      WWT_PANEL,   RESIZE_NONE,    14,     2,    35,    63,   108, 0x0,                   STR_280D_SELECT_TREE_TYPE_TO_PLANT},
{      WWT_PANEL,   RESIZE_NONE,    14,    37,    70,    63,   108, 0x0,                   STR_280D_SELECT_TREE_TYPE_TO_PLANT},
{      WWT_PANEL,   RESIZE_NONE,    14,    72,   105,    63,   108, 0x0,                   STR_280D_SELECT_TREE_TYPE_TO_PLANT},
{      WWT_PANEL,   RESIZE_NONE,    14,   107,   140,    63,   108, 0x0,                   STR_280D_SELECT_TREE_TYPE_TO_PLANT},
{      WWT_PANEL,   RESIZE_NONE,    14,     2,    35,   110,   155, 0x0,                   STR_280D_SELECT_TREE_TYPE_TO_PLANT},
{      WWT_PANEL,   RESIZE_NONE,    14,    37,    70,   110,   155, 0x0,                   STR_280D_SELECT_TREE_TYPE_TO_PLANT},
{      WWT_PANEL,   RESIZE_NONE,    14,    72,   105,   110,   155, 0x0,                   STR_280D_SELECT_TREE_TYPE_TO_PLANT},
{      WWT_PANEL,   RESIZE_NONE,    14,   107,   140,   110,   155, 0x0,                   STR_280D_SELECT_TREE_TYPE_TO_PLANT},
{    WWT_TEXTBTN,   RESIZE_NONE,    14,     2,   140,   157,   168, STR_TREES_RANDOM_TYPE, STR_TREES_RANDOM_TYPE_TIP},
{    WWT_TEXTBTN,   RESIZE_NONE,    14,     2,   140,   170,   181, STR_028A_RANDOM_TREES, STR_028B_PLANT_TREES_RANDOMLY_OVER},
{    WIDGETS_END},
};

static const WindowDesc _build_trees_scen_desc = {
	-1, -1, 143, 184,
	WC_BUILD_TREES,0,
	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
	_build_trees_scen_widgets,
	BuildTreesWndProc
};


void ShowBuildTreesToolbar(void)
{
	AllocateWindowDescFront(&_build_trees_desc, 0);
}

void ShowBuildTreesScenToolbar(void)
{
	AllocateWindowDescFront(&_build_trees_scen_desc, 0);
}

static uint32 _errmsg_decode_params[20];
static StringID _errmsg_message_1, _errmsg_message_2;
static uint _errmsg_duration;


static const Widget _errmsg_widgets[] = {
{   WWT_CLOSEBOX,   RESIZE_NONE,     4,     0,    10,     0,    13, STR_00C5,         STR_018B_CLOSE_WINDOW},
{    WWT_CAPTION,   RESIZE_NONE,     4,    11,   239,     0,    13, STR_00B2_MESSAGE, STR_NULL},
{      WWT_PANEL,   RESIZE_NONE,     4,     0,   239,    14,    45, 0x0,              STR_NULL},
{    WIDGETS_END},
};

static const Widget _errmsg_face_widgets[] = {
{   WWT_CLOSEBOX,   RESIZE_NONE,     4,     0,    10,     0,    13, STR_00C5,              STR_018B_CLOSE_WINDOW},
{    WWT_CAPTION,   RESIZE_NONE,     4,    11,   333,     0,    13, STR_00B3_MESSAGE_FROM, STR_NULL},
{      WWT_PANEL,   RESIZE_NONE,     4,     0,   333,    14,   136, 0x0,                   STR_NULL},
{   WIDGETS_END},
};

static void ErrmsgWndProc(Window *w, WindowEvent *e)
{
	switch (e->event) {
	case WE_PAINT:
		COPY_IN_DPARAM(0, _errmsg_decode_params, lengthof(_errmsg_decode_params));
		DrawWindowWidgets(w);
		COPY_IN_DPARAM(0, _errmsg_decode_params, lengthof(_errmsg_decode_params));
		if (!IsWindowOfPrototype(w, _errmsg_face_widgets)) {
			DrawStringMultiCenter(
				120,
				(_errmsg_message_1 == INVALID_STRING_ID ? 25 : 15),
				_errmsg_message_2,
				238);
			if (_errmsg_message_1 != INVALID_STRING_ID)
				DrawStringMultiCenter(
					120,
					30,
					_errmsg_message_1,
					238);
		} else {
			const Player *p = GetPlayer(GetDParamX(_errmsg_decode_params,2));
			DrawPlayerFace(p->face, p->player_color, 2, 16);

			DrawStringMultiCenter(
				214,
				(_errmsg_message_1 == INVALID_STRING_ID ? 65 : 45),
				_errmsg_message_2,
				238);
			if (_errmsg_message_1 != INVALID_STRING_ID)
				DrawStringMultiCenter(
					214,
					90,
					_errmsg_message_1,
					238);
		}
		break;

	case WE_MOUSELOOP:
		if (_right_button_down) DeleteWindow(w);
		break;

	case WE_4:
		if (--_errmsg_duration == 0) DeleteWindow(w);
		break;

	case WE_DESTROY:
		SetRedErrorSquare(0);
		_switch_mode_errorstr = INVALID_STRING_ID;
		break;

	case WE_KEYPRESS:
		if (e->we.keypress.keycode == WKC_SPACE) {
			// Don't continue.
			e->we.keypress.cont = false;
			DeleteWindow(w);
		}
		break;
	}
}

void ShowErrorMessage(StringID msg_1, StringID msg_2, int x, int y)
{
	Window *w;
	ViewPort *vp;
	Point pt;

	DeleteWindowById(WC_ERRMSG, 0);

	//assert(msg_2);
	if (msg_2 == 0) msg_2 = STR_EMPTY;

	_errmsg_message_1 = msg_1;
	_errmsg_message_2 = msg_2;
	COPY_OUT_DPARAM(_errmsg_decode_params, 0, lengthof(_errmsg_decode_params));
	_errmsg_duration = _patches.errmsg_duration;
	if (!_errmsg_duration)
		return;

	if (_errmsg_message_1 != STR_013B_OWNED_BY || GetDParamX(_errmsg_decode_params,2) >= 8) {

		if ( (x|y) != 0) {
			pt = RemapCoords2(x, y);
			for (w = _windows; w->window_class != WC_MAIN_WINDOW; w++) {}
			vp = w->viewport;

			// move x pos to opposite corner
			pt.x = ((pt.x - vp->virtual_left) >> vp->zoom) + vp->left;
			pt.x = (pt.x < (_screen.width >> 1)) ? _screen.width - 260 : 20;

			// move y pos to opposite corner
			pt.y = ((pt.y - vp->virtual_top) >> vp->zoom) + vp->top;
			pt.y = (pt.y < (_screen.height >> 1)) ? _screen.height - 80 : 100;

		} else {
			pt.x = (_screen.width - 240) >> 1;
			pt.y = (_screen.height - 46) >> 1;
		}
		w = AllocateWindow(pt.x, pt.y, 240, 46, ErrmsgWndProc, WC_ERRMSG, _errmsg_widgets);
	} else {
		if ( (x|y) != 0) {
			pt = RemapCoords2(x, y);
			for (w = _windows; w->window_class != WC_MAIN_WINDOW; w++) {}
			vp = w->viewport;
			pt.x = clamp(((pt.x - vp->virtual_left) >> vp->zoom) + vp->left - (334/2), 0, _screen.width - 334);
			pt.y = clamp(((pt.y - vp->virtual_top) >> vp->zoom) + vp->top - (137/2), 22, _screen.height - 137);
		} else {
			pt.x = (_screen.width - 334) >> 1;
			pt.y = (_screen.height - 137) >> 1;
		}
		w = AllocateWindow(pt.x, pt.y, 334, 137, ErrmsgWndProc, WC_ERRMSG, _errmsg_face_widgets);
	}

	w->desc_flags = WDF_STD_BTN | WDF_DEF_WIDGET;
}


void ShowEstimatedCostOrIncome(int32 cost, int x, int y)
{
	StringID msg = STR_0805_ESTIMATED_COST;

	if (cost < 0) {
		cost = -cost;
		msg = STR_0807_ESTIMATED_INCOME;
	}
	SetDParam(0, cost);
	ShowErrorMessage(INVALID_STRING_ID, msg, x, y);
}

void ShowCostOrIncomeAnimation(int x, int y, int z, int32 cost)
{
	StringID msg;
	Point pt = RemapCoords(x,y,z);

	msg = STR_0801_COST;
	if (cost < 0) {
		cost = -cost;
		msg = STR_0803_INCOME;
	}
	SetDParam(0, cost);
	AddTextEffect(msg, pt.x, pt.y, 0x250);
}

void ShowFeederIncomeAnimation(int x, int y, int z, int32 cost)
{
	Point pt = RemapCoords(x,y,z);

	SetDParam(0, cost);
	AddTextEffect(STR_FEEDER, pt.x, pt.y, 0x250);
}

static const Widget _tooltips_widgets[] = {
{      WWT_PANEL,   RESIZE_NONE,    14,     0,   199,     0,    31, 0x0, STR_NULL},
{   WIDGETS_END},
};


static void TooltipsWndProc(Window *w, WindowEvent *e)
{
	switch (e->event) {
		case WE_PAINT:
			GfxFillRect(0, 0, w->width - 1, w->height - 1, 0);
			GfxFillRect(1, 1, w->width - 2, w->height - 2, 0x44);
			DrawStringMultiCenter((w->width >> 1), (w->height >> 1) - 5, WP(w,tooltips_d).string_id, 197);
			break;

		case WE_MOUSELOOP:
			if (!_right_button_down) DeleteWindow(w);
			break;
	}
}

void GuiShowTooltips(StringID string_id)
{
	char buffer[512];
	Window *w;
	int right,bottom;
	int x,y;

	if (string_id == 0) return;

	w = FindWindowById(WC_TOOLTIPS, 0);
	if (w != NULL) {
		if (WP(w,tooltips_d).string_id == string_id)
			return;
		DeleteWindow(w);
	}

	GetString(buffer, string_id);

	right = GetStringBoundingBox(buffer).width + 6;

	/* Cut tooltip length to 200 pixels max, wrap to new line if longer */
	bottom = 14;
	if (right > 200) {
		bottom += ((right - 4) / 176) * 10;
		right = 200;
	}

	/* Correctly position the tooltip position, watch out for window and cursor size
	 * Clamp value to below main toolbar and above statusbar. If tooltip would
	 * go below window, flip it so it is shown above the cursor */
	y = clamp(_cursor.pos.y + _cursor.size.y + _cursor.offs.y + 5, 22, _screen.height - 12);
	if (y + bottom > _screen.height - 12) y = _cursor.pos.y + _cursor.offs.y - bottom - 5;
	x = clamp(_cursor.pos.x - (right >> 1), 0, _screen.width - right);

	w = AllocateWindow(x, y, right, bottom, TooltipsWndProc, WC_TOOLTIPS, _tooltips_widgets);
	WP(w,tooltips_d).string_id = string_id;
	w->flags4 &= ~WF_WHITE_BORDER_MASK; // remove white-border from tooltip
	w->widget[0].right = right;
	w->widget[0].bottom = bottom;
}


static void DrawStationCoverageText(const AcceptedCargo accepts,
	int str_x, int str_y, uint mask)
{
	char *b = _userstring;
	int i;

	b = InlineString(b, STR_000D_ACCEPTS);

	for (i = 0; i != NUM_CARGO; i++, mask >>= 1) {
		if (accepts[i] >= 8 && mask & 1) {
			b = InlineString(b, _cargoc.names_s[i]);
			*b++ = ',';
			*b++ = ' ';
		}
	}

	if (b == &_userstring[3]) {
		b = InlineString(b, STR_00D0_NOTHING);
		*b++ = '\0';
	} else {
		b[-2] = '\0';
	}

	DrawStringMultiLine(str_x, str_y, STR_SPEC_USERSTRING, 144);
}

void DrawStationCoverageAreaText(int sx, int sy, uint mask, int rad) {
	TileIndex tile = TileVirtXY(_thd.pos.x, _thd.pos.y);
	AcceptedCargo accepts;
	if (tile < MapSize()) {
		GetAcceptanceAroundTiles(accepts, tile, _thd.size.x / TILE_SIZE, _thd.size.y / TILE_SIZE , rad);
		DrawStationCoverageText(accepts, sx, sy, mask);
	}
}

void CheckRedrawStationCoverage(const Window *w)
{
	if (_thd.dirty & 1) {
		_thd.dirty &= ~1;
		SetWindowDirty(w);
	}
}


void UnclickSomeWindowButtons(Window *w, uint32 mask)
{
	uint32 x = w->click_state & mask;
	uint i = 0;

	w->click_state ^= x;
	do {
		if (x & 1) InvalidateWidget(w, i);
	} while (i++, x >>= 1);
}


void UnclickWindowButtons(Window *w)
{
	UnclickSomeWindowButtons(w, (uint32)-1);
}


void SetVScrollCount(Window *w, int num)
{
	w->vscroll.count = num;
	num -= w->vscroll.cap;
	if (num < 0) num = 0;
	if (num < w->vscroll.pos) w->vscroll.pos = num;
}

void SetVScroll2Count(Window *w, int num)
{
	w->vscroll2.count = num;
	num -= w->vscroll2.cap;
	if (num < 0) num = 0;
	if (num < w->vscroll2.pos) w->vscroll2.pos = num;
}

void SetHScrollCount(Window *w, int num)
{
	w->hscroll.count = num;
	num -= w->hscroll.cap;
	if (num < 0) num = 0;
	if (num < w->hscroll.pos) w->hscroll.pos = num;
}

static void DelChar(Textbuf *tb)
{
	tb->width -= GetCharacterWidth(FS_NORMAL, (byte)tb->buf[tb->caretpos]);
	memmove(tb->buf + tb->caretpos, tb->buf + tb->caretpos + 1, tb->length - tb->caretpos);
	tb->length--;
}

/**
 * Delete a character from a textbuffer, either with 'Delete' or 'Backspace'
 * The character is delete from the position the caret is at
 * @param tb @Textbuf type to be changed
 * @param delmode Type of deletion, either @WKC_BACKSPACE or @WKC_DELETE
 * @return Return true on successfull change of Textbuf, or false otherwise
 */
bool DeleteTextBufferChar(Textbuf *tb, int delmode)
{
	if (delmode == WKC_BACKSPACE && tb->caretpos != 0) {
		tb->caretpos--;
		tb->caretxoffs -= GetCharacterWidth(FS_NORMAL, (byte)tb->buf[tb->caretpos]);

		DelChar(tb);
		return true;
	} else if (delmode == WKC_DELETE && tb->caretpos < tb->length) {
		DelChar(tb);
		return true;
	}

	return false;
}

/**
 * Delete every character in the textbuffer
 * @param tb @Textbuf buffer to be emptied
 */
void DeleteTextBufferAll(Textbuf *tb)
{
	memset(tb->buf, 0, tb->maxlength);
	tb->length = tb->width = 0;
	tb->caretpos = tb->caretxoffs = 0;
}

/**
 * Insert a character to a textbuffer. If maxwidth of the Textbuf is zero,
 * we don't care about the visual-length but only about the physical
 * length of the string
 * @param tb @Textbuf type to be changed
 * @param key Character to be inserted
 * @return Return true on successfull change of Textbuf, or false otherwise
 */
bool InsertTextBufferChar(Textbuf *tb, byte key)
{
	const byte charwidth = GetCharacterWidth(FS_NORMAL, key);
	if (tb->length < (tb->maxlength - 1) && (tb->maxwidth == 0 || tb->width + charwidth <= tb->maxwidth)) {
		memmove(tb->buf + tb->caretpos + 1, tb->buf + tb->caretpos, (tb->length - tb->caretpos) + 1);
		tb->buf[tb->caretpos] = key;
		tb->length++;
		tb->width += charwidth;

		tb->caretpos++;
		tb->caretxoffs += charwidth;
		return true;
	}
	return false;
}

/**
 * Handle text navigation with arrow keys left/right.
 * This defines where the caret will blink and the next characer interaction will occur
 * @param tb @Textbuf type where navigation occurs
 * @param navmode Direction in which navigation occurs @WKC_LEFT, @WKC_RIGHT, @WKC_END, @WKC_HOME
 * @return Return true on successfull change of Textbuf, or false otherwise
 */
bool MoveTextBufferPos(Textbuf *tb, int navmode)
{
	switch (navmode) {
	case WKC_LEFT:
		if (tb->caretpos != 0) {
			tb->caretpos--;
			tb->caretxoffs -= GetCharacterWidth(FS_NORMAL, (byte)tb->buf[tb->caretpos]);
			return true;
		}
		break;
	case WKC_RIGHT:
		if (tb->caretpos < tb->length) {
			tb->caretxoffs += GetCharacterWidth(FS_NORMAL, (byte)tb->buf[tb->caretpos]);
			tb->caretpos++;
			return true;
		}
		break;
	case WKC_HOME:
		tb->caretpos = 0;
		tb->caretxoffs = 0;
		return true;
	case WKC_END:
		tb->caretpos = tb->length;
		tb->caretxoffs = tb->width;
		return true;
	}

	return false;
}

/**
 * Update @Textbuf type with its actual physical character and screenlength
 * Get the count of characters in the string as well as the width in pixels.
 * Useful when copying in a larger amount of text at once
 * @param tb @Textbuf type which length is calculated
 */
void UpdateTextBufferSize(Textbuf *tb)
{
	const char *buf;

	tb->length = 0;
	tb->width = 0;

	for (buf = tb->buf; *buf != '\0' && tb->length < (tb->maxlength - 1); buf++) {
		tb->length++;
		tb->width += GetCharacterWidth(FS_NORMAL, (byte)*buf);
	}

	tb->caretpos = tb->length;
	tb->caretxoffs = tb->width;
}

int HandleEditBoxKey(Window *w, querystr_d *string, int wid, WindowEvent *e, CharSetFilter afilter)
{
	e->we.keypress.cont = false;

	switch (e->we.keypress.keycode) {
	case WKC_ESC: return 2;
	case WKC_RETURN: case WKC_NUM_ENTER: return 1;
	case (WKC_CTRL | 'V'):
		if (InsertTextBufferClipboard(&string->text))
			InvalidateWidget(w, wid);
		break;
	case (WKC_CTRL | 'U'):
		DeleteTextBufferAll(&string->text);
		InvalidateWidget(w, wid);
		break;
	case WKC_BACKSPACE: case WKC_DELETE:
		if (DeleteTextBufferChar(&string->text, e->we.keypress.keycode))
			InvalidateWidget(w, wid);
		break;
	case WKC_LEFT: case WKC_RIGHT: case WKC_END: case WKC_HOME:
		if (MoveTextBufferPos(&string->text, e->we.keypress.keycode))
			InvalidateWidget(w, wid);
		break;
	default:
		if (IsValidAsciiChar(e->we.keypress.ascii, afilter)) {
			if (InsertTextBufferChar(&string->text, e->we.keypress.ascii))
				InvalidateWidget(w, wid);
		} else { // key wasn't caught. Continue only if standard entry specified
			e->we.keypress.cont = (afilter == CS_ALPHANUMERAL);
		}
	}

	return 0;
}

bool HandleCaret(Textbuf *tb)
{
	/* caret changed? */
	bool b = !!(_caret_timer & 0x20);

	if (b != tb->caret) {
		tb->caret = b;
		return true;
	}
	return false;
}

void HandleEditBox(Window *w, querystr_d *string, int wid)
{
	if (HandleCaret(&string->text)) InvalidateWidget(w, wid);
}

void DrawEditBox(Window *w, querystr_d *string, int wid)
{
	const Widget *wi = w->widget + wid;
	const Textbuf *tb = &string->text;

	GfxFillRect(wi->left+1, wi->top+1, wi->right-1, wi->bottom-1, 215);
	DoDrawString(tb->buf, wi->left+2, wi->top+1, 8);
	if (tb->caret) DoDrawString("_", wi->left + 2 + tb->caretxoffs, wi->top + 1, 12);
}

static void QueryStringWndProc(Window *w, WindowEvent *e)
{
	static bool closed = false;
	switch (e->event) {
	case WE_CREATE:
		SETBIT(_no_scroll, SCROLL_EDIT);
		closed = false;
		break;

	case WE_PAINT:
		SetDParam(0, WP(w,querystr_d).caption);
		DrawWindowWidgets(w);

		DrawEditBox(w, &WP(w,querystr_d), 5);
		break;

	case WE_CLICK:
		switch (e->we.click.widget) {
		case 3: DeleteWindow(w); break;
		case 4:
press_ok:;
			if (WP(w, querystr_d).orig != NULL &&
					strcmp(WP(w, querystr_d).text.buf, WP(w, querystr_d).orig) == 0) {
				DeleteWindow(w);
			} else {
				char *buf = WP(w,querystr_d).text.buf;
				WindowClass wnd_class = WP(w,querystr_d).wnd_class;
				WindowNumber wnd_num = WP(w,querystr_d).wnd_num;
				Window *parent;

				// Mask the edit-box as closed, so we don't send out a CANCEL
				closed = true;

				DeleteWindow(w);

				parent = FindWindowById(wnd_class, wnd_num);
				if (parent != NULL) {
					WindowEvent e;
					e.event = WE_ON_EDIT_TEXT;
					e.we.edittext.str = buf;
					parent->wndproc(parent, &e);
				}
			}
			break;
		}
		break;

	case WE_MOUSELOOP: {
		if (!FindWindowById(WP(w,querystr_d).wnd_class, WP(w,querystr_d).wnd_num)) {
			DeleteWindow(w);
			return;
		}
		HandleEditBox(w, &WP(w, querystr_d), 5);
	} break;

	case WE_KEYPRESS: {
		switch (HandleEditBoxKey(w, &WP(w, querystr_d), 5, e, WP(w, querystr_d).afilter)) {
		case 1: // Return
			goto press_ok;
		case 2: // Escape
			DeleteWindow(w);
			break;
		}
	} break;

	case WE_DESTROY:
		// If the window is not closed yet, it means it still needs to send a CANCEL
		if (!closed) {
			Window *parent = FindWindowById(WP(w,querystr_d).wnd_class, WP(w,querystr_d).wnd_num);
			if (parent != NULL) {
				WindowEvent e;
				e.event = WE_ON_EDIT_TEXT_CANCEL;
				parent->wndproc(parent, &e);
			}
		}
		CLRBIT(_no_scroll, SCROLL_EDIT);
		break;
	}
}

static const Widget _query_string_widgets[] = {
{   WWT_CLOSEBOX,   RESIZE_NONE,    14,     0,    10,     0,    13, STR_00C5,        STR_018B_CLOSE_WINDOW},
{    WWT_CAPTION,   RESIZE_NONE,    14,    11,   259,     0,    13, STR_012D,        STR_NULL},
{     WWT_IMGBTN,   RESIZE_NONE,    14,     0,   259,    14,    29, 0x0,             STR_NULL},
{    WWT_TEXTBTN,   RESIZE_NONE,    14,     0,   129,    30,    41, STR_012E_CANCEL, STR_NULL},
{    WWT_TEXTBTN,   RESIZE_NONE,    14,   130,   259,    30,    41, STR_012F_OK,     STR_NULL},
{     WWT_IMGBTN,   RESIZE_NONE,    14,     2,   257,    16,    27, 0x0,             STR_NULL},
{   WIDGETS_END},
};

static const WindowDesc _query_string_desc = {
	190, 219, 260, 42,
	WC_QUERY_STRING,0,
	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
	_query_string_widgets,
	QueryStringWndProc
};

static char _edit_str_buf[64];
static char _orig_str_buf[lengthof(_edit_str_buf)];

void ShowQueryString(StringID str, StringID caption, uint maxlen, uint maxwidth, WindowClass window_class, WindowNumber window_number, CharSetFilter afilter)
{
	Window *w;
	uint realmaxlen = maxlen & ~0x1000;

	assert(realmaxlen < lengthof(_edit_str_buf));

	DeleteWindowById(WC_QUERY_STRING, 0);
	DeleteWindowById(WC_SAVELOAD, 0);

	w = AllocateWindowDesc(&_query_string_desc);

	GetString(_edit_str_buf, str);
	_edit_str_buf[realmaxlen-1] = '\0';

	if (maxlen & 0x1000) {
		WP(w, querystr_d).orig = NULL;
	} else {
		strcpy(_orig_str_buf, _edit_str_buf);
		WP(w, querystr_d).orig = _orig_str_buf;
	}

	w->click_state = 1 << 5;
	WP(w, querystr_d).caption = caption;
	WP(w, querystr_d).wnd_class = window_class;
	WP(w, querystr_d).wnd_num = window_number;
	WP(w, querystr_d).text.caret = false;
	WP(w, querystr_d).text.maxlength = realmaxlen;
	WP(w, querystr_d).text.maxwidth = maxwidth;
	WP(w, querystr_d).text.buf = _edit_str_buf;
	WP(w, querystr_d).afilter = afilter;
	UpdateTextBufferSize(&WP(w, querystr_d).text);
}

static void QueryWndProc(Window *w, WindowEvent *e)
{
	switch (e->event) {
	case WE_PAINT:
		SetDParam(0, WP(w, query_d).caption);
		DrawWindowWidgets(w);

		DrawStringMultiCenter(90, 38, WP(w, query_d).message, 178);
		break;

	case WE_CLICK:
		switch (e->we.click.widget) {
		case 3:
		case 4:
			WP(w, query_d).calledback = true;
			if (WP(w, query_d).ok_cancel_callback != NULL) WP(w, query_d).ok_cancel_callback(e->we.click.widget == 4);
			DeleteWindow(w);
			break;
		}
		break;

	case WE_MOUSELOOP:
		if (!FindWindowById(WP(w, query_d).wnd_class, WP(w, query_d).wnd_num)) DeleteWindow(w);
		break;

	case WE_DESTROY:
		if (!WP(w, query_d).calledback && WP(w, query_d).ok_cancel_callback != NULL) WP(w, query_d).ok_cancel_callback(false);
		break;
	}
}

static const Widget _query_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE,  4,   0,  10,   0,  13, STR_00C5,        STR_018B_CLOSE_WINDOW},
{  WWT_CAPTION, RESIZE_NONE,  4,  11, 179,   0,  13, STR_012D,        STR_NULL},
{   WWT_IMGBTN, RESIZE_NONE,  4,   0, 179,  14,  91, 0x0,             STR_NULL},
{  WWT_TEXTBTN, RESIZE_NONE, 12,  25,  84,  72,  83, STR_012E_CANCEL, STR_NULL},
{  WWT_TEXTBTN, RESIZE_NONE, 12,  95, 154,  72,  83, STR_012F_OK,     STR_NULL},
{  WIDGETS_END },
};

static const WindowDesc _query_desc = {
	WDP_CENTER, WDP_CENTER, 180, 92,
	WC_OK_CANCEL_QUERY, 0,
	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
	_query_widgets,
	QueryWndProc
};

void ShowQuery(StringID caption, StringID message, void (*ok_cancel_callback)(bool ok_clicked), WindowClass window_class, WindowNumber window_number)
{
	Window *w;

	DeleteWindowById(WC_OK_CANCEL_QUERY, 0);

	w = AllocateWindowDesc(&_query_desc);

	w->click_state = 1 << 5;
	WP(w, query_d).caption            = caption;
	WP(w, query_d).message            = message;
	WP(w, query_d).wnd_class          = window_class;
	WP(w, query_d).wnd_num            = window_number;
	WP(w, query_d).ok_cancel_callback = ok_cancel_callback;
	WP(w, query_d).calledback         = false;
}


static const Widget _load_dialog_1_widgets[] = {
{   WWT_CLOSEBOX,   RESIZE_NONE,    14,     0,    10,     0,    13, STR_00C5,           STR_018B_CLOSE_WINDOW},
{    WWT_CAPTION,  RESIZE_RIGHT,    14,    11,   256,     0,    13, STR_4001_LOAD_GAME, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PUSHTXTBTN,   RESIZE_NONE,    14,     0,   127,    14,    25, STR_SORT_BY_NAME,   STR_SORT_ORDER_TIP},
{ WWT_PUSHTXTBTN,   RESIZE_NONE,    14,   128,   256,    14,    25, STR_SORT_BY_DATE,   STR_SORT_ORDER_TIP},
{     WWT_IMGBTN,  RESIZE_RIGHT,    14,     0,   256,    26,    47, 0x0,                STR_NULL},
{     WWT_IMGBTN,     RESIZE_RB,    14,     0,   256,    48,   293, 0x0,                STR_NULL},
{ WWT_PUSHIMGBTN,     RESIZE_LR,    14,   245,   256,    48,    59, SPR_HOUSE_ICON,     STR_SAVELOAD_HOME_BUTTON},
{          WWT_6,     RESIZE_RB,    14,     2,   243,    50,   291, 0x0,                STR_400A_LIST_OF_DRIVES_DIRECTORIES},
{  WWT_SCROLLBAR,    RESIZE_LRB,    14,   245,   256,    60,   281, 0x0,                STR_0190_SCROLL_BAR_SCROLLS_LIST},
{  WWT_RESIZEBOX,   RESIZE_LRTB,    14,   245,   256,   282,   293, 0x0,                STR_RESIZE_BUTTON},
{   WIDGETS_END},
};

static const Widget _load_dialog_2_widgets[] = {
{   WWT_CLOSEBOX,   RESIZE_NONE,    14,     0,    10,     0,    13, STR_00C5,               STR_018B_CLOSE_WINDOW},
{    WWT_CAPTION,  RESIZE_RIGHT,    14,    11,   256,     0,    13, STR_0298_LOAD_SCENARIO, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PUSHTXTBTN,   RESIZE_NONE,    14,     0,   127,    14,    25, STR_SORT_BY_NAME,       STR_SORT_ORDER_TIP},
{ WWT_PUSHTXTBTN,   RESIZE_NONE,    14,   128,   256,    14,    25, STR_SORT_BY_DATE,       STR_SORT_ORDER_TIP},
{     WWT_IMGBTN,  RESIZE_RIGHT,    14,     0,   256,    26,    47, 0x0,                    STR_NULL},
{     WWT_IMGBTN,     RESIZE_RB,    14,     0,   256,    48,   293, 0x0,                    STR_NULL},
{ WWT_PUSHIMGBTN,     RESIZE_LR,    14,   245,   256,    48,    59, SPR_HOUSE_ICON,         STR_SAVELOAD_HOME_BUTTON},
{          WWT_6,     RESIZE_RB,    14,     2,   243,    50,   291, 0x0,                    STR_400A_LIST_OF_DRIVES_DIRECTORIES},
{  WWT_SCROLLBAR,    RESIZE_LRB,    14,   245,   256,    60,   281, 0x0,                    STR_0190_SCROLL_BAR_SCROLLS_LIST},
{  WWT_RESIZEBOX,   RESIZE_LRTB,    14,   245,   256,   282,   293, 0x0,                    STR_RESIZE_BUTTON},
{   WIDGETS_END},
};

static const Widget _load_dialog_3_widgets[] = {
{   WWT_CLOSEBOX,   RESIZE_NONE,    14,     0,    10,     0,    13,  STR_00C5,                STR_018B_CLOSE_WINDOW},
{    WWT_CAPTION,  RESIZE_RIGHT,    14,    11,   256,     0,    13,  STR_4011_LOAD_HEIGHTMAP, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PUSHTXTBTN,   RESIZE_NONE,    14,     0,   127,    14,    25,  STR_SORT_BY_NAME,        STR_SORT_ORDER_TIP},
{ WWT_PUSHTXTBTN,   RESIZE_NONE,    14,   128,   256,    14,    25,  STR_SORT_BY_DATE,        STR_SORT_ORDER_TIP},
{     WWT_IMGBTN,  RESIZE_RIGHT,    14,     0,   256,    26,    47,  0x0,                     STR_NULL},
{     WWT_IMGBTN,     RESIZE_RB,    14,     0,   256,    48,   293,  0x0,                     STR_NULL},
{ WWT_PUSHIMGBTN,     RESIZE_LR,    14,   245,   256,    48,    59,  SPR_HOUSE_ICON,          STR_SAVELOAD_HOME_BUTTON},
{          WWT_6,     RESIZE_RB,    14,     2,   243,    50,   291,  0x0,                     STR_400A_LIST_OF_DRIVES_DIRECTORIES},
{  WWT_SCROLLBAR,    RESIZE_LRB,    14,   245,   256,    60,   281,  0x0,                     STR_0190_SCROLL_BAR_SCROLLS_LIST},
{  WWT_RESIZEBOX,   RESIZE_LRTB,    14,   245,   256,   282,   293,  0x0,                     STR_RESIZE_BUTTON},
{   WIDGETS_END},
};

static const Widget _save_dialog_widgets[] = {
{   WWT_CLOSEBOX,   RESIZE_NONE,    14,     0,    10,     0,    13, STR_00C5,           STR_018B_CLOSE_WINDOW},
{    WWT_CAPTION,  RESIZE_RIGHT,    14,    11,   256,     0,    13, STR_4000_SAVE_GAME, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PUSHTXTBTN,   RESIZE_NONE,    14,     0,   127,    14,    25, STR_SORT_BY_NAME,   STR_SORT_ORDER_TIP},
{ WWT_PUSHTXTBTN,   RESIZE_NONE,    14,   128,   256,    14,    25, STR_SORT_BY_DATE,   STR_SORT_ORDER_TIP},
{     WWT_IMGBTN,  RESIZE_RIGHT,    14,     0,   256,    26,    47, 0x0,                STR_NULL},
{     WWT_IMGBTN,     RESIZE_RB,    14,     0,   256,    48,   291, 0x0,                STR_NULL},
{ WWT_PUSHIMGBTN,     RESIZE_LR,    14,   245,   256,    48,    59, SPR_HOUSE_ICON,     STR_SAVELOAD_HOME_BUTTON},
{          WWT_6,     RESIZE_RB,    14,     2,   243,    50,   290, 0x0,                STR_400A_LIST_OF_DRIVES_DIRECTORIES},
{  WWT_SCROLLBAR,    RESIZE_LRB,    14,   245,   256,    60,   291, 0x0,                STR_0190_SCROLL_BAR_SCROLLS_LIST},
{     WWT_IMGBTN,    RESIZE_RTB,    14,     0,   256,   292,   307, 0x0,                STR_NULL},
{     WWT_IMGBTN,    RESIZE_RTB,    14,     2,   254,   294,   305, 0x0,                STR_400B_CURRENTLY_SELECTED_NAME},
{ WWT_PUSHTXTBTN,     RESIZE_TB,    14,     0,   127,   308,   319, STR_4003_DELETE,    STR_400C_DELETE_THE_CURRENTLY_SELECTED},
{ WWT_PUSHTXTBTN,     RESIZE_TB,    14,   128,   244,   308,   319, STR_4002_SAVE,      STR_400D_SAVE_THE_CURRENT_GAME_USING},
{  WWT_RESIZEBOX,   RESIZE_LRTB,    14,   245,   256,   308,   319, 0x0,                STR_RESIZE_BUTTON},
{   WIDGETS_END},
};

static const Widget _save_dialog_scen_widgets[] = {
{   WWT_CLOSEBOX,   RESIZE_NONE,    14,     0,    10,     0,    13, STR_00C5,               STR_018B_CLOSE_WINDOW},
{    WWT_CAPTION,  RESIZE_RIGHT,    14,    11,   256,     0,    13, STR_0299_SAVE_SCENARIO, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PUSHTXTBTN,   RESIZE_NONE,    14,     0,   127,    14,    25, STR_SORT_BY_NAME,       STR_SORT_ORDER_TIP},
{ WWT_PUSHTXTBTN,   RESIZE_NONE,    14,   128,   256,    14,    25, STR_SORT_BY_DATE,       STR_SORT_ORDER_TIP},
{     WWT_IMGBTN,  RESIZE_RIGHT,    14,     0,   256,    26,    47, 0x0,                    STR_NULL},
{     WWT_IMGBTN,     RESIZE_RB,    14,     0,   256,    48,   291, 0x0,                    STR_NULL},
{ WWT_PUSHIMGBTN,     RESIZE_LR,    14,   245,   256,    48,    59, SPR_HOUSE_ICON,         STR_SAVELOAD_HOME_BUTTON},
{          WWT_6,     RESIZE_RB,    14,     2,   243,    50,   290, 0x0,                    STR_400A_LIST_OF_DRIVES_DIRECTORIES},
{  WWT_SCROLLBAR,    RESIZE_LRB,    14,   245,   256,    60,   291, 0x0,                    STR_0190_SCROLL_BAR_SCROLLS_LIST},
{     WWT_IMGBTN,    RESIZE_RTB,    14,     0,   256,   292,   307, 0x0,                    STR_NULL},
{     WWT_IMGBTN,    RESIZE_RTB,    14,     2,   254,   294,   305, 0x0,                    STR_400B_CURRENTLY_SELECTED_NAME},
{ WWT_PUSHTXTBTN,     RESIZE_TB,    14,     0,   127,   308,   319, STR_4003_DELETE,        STR_400C_DELETE_THE_CURRENTLY_SELECTED},
{ WWT_PUSHTXTBTN,     RESIZE_TB,    14,   128,   244,   308,   319, STR_4002_SAVE,          STR_400D_SAVE_THE_CURRENT_GAME_USING},
{  WWT_RESIZEBOX,   RESIZE_LRTB,    14,   245,   256,   308,   319, 0x0,                    STR_RESIZE_BUTTON},
{   WIDGETS_END},
};

// Colors for fios types
const byte _fios_colors[] = {13, 9, 9, 6, 5, 6, 5, 6, 6, 8};

void BuildFileList(void)
{
	_fios_path_changed = true;
	FiosFreeSavegameList();

	switch (_saveload_mode) {
		case SLD_NEW_GAME:
		case SLD_LOAD_SCENARIO:
		case SLD_SAVE_SCENARIO:
			_fios_list = FiosGetScenarioList(_saveload_mode); break;
		case SLD_LOAD_HEIGHTMAP:
			_fios_list = FiosGetHeightmapList(_saveload_mode); break;

		default: _fios_list = FiosGetSavegameList(_saveload_mode); break;
	}
}

static void DrawFiosTexts(uint maxw)
{
	static const char *path = NULL;
	static StringID str = STR_4006_UNABLE_TO_READ_DRIVE;
	static uint32 tot = 0;

	if (_fios_path_changed) {
		str = FiosGetDescText(&path, &tot);
		_fios_path_changed = false;
	}

	if (str != STR_4006_UNABLE_TO_READ_DRIVE) SetDParam(0, tot);
	DrawString(2, 37, str, 0);
	DoDrawStringTruncated(path, 2, 27, 16, maxw);
}

static void MakeSortedSaveGameList(void)
{
	uint sort_start = 0;
	uint sort_end = 0;
	uint s_amount;
	int i;

	/* Directories are always above the files (FIOS_TYPE_DIR)
	 * Drives (A:\ (windows only) are always under the files (FIOS_TYPE_DRIVE)
	 * Only sort savegames/scenarios, not directories
	 */
	for (i = 0; i < _fios_num; i++) {
		switch (_fios_list[i].type) {
			case FIOS_TYPE_DIR:    sort_start++; break;
			case FIOS_TYPE_PARENT: sort_start++; break;
			case FIOS_TYPE_DRIVE:  sort_end++;   break;
		}
	}

	s_amount = _fios_num - sort_start - sort_end;
	if (s_amount > 0)
		qsort(_fios_list + sort_start, s_amount, sizeof(FiosItem), compare_FiosItems);
}

static void GenerateFileName(void)
{
	/* Check if we are not a specatator who wants to generate a name..
	    Let's use the name of player #0 for now. */
	const Player *p = GetPlayer(_local_player < MAX_PLAYERS ? _local_player : 0);

	SetDParam(0, p->name_1);
	SetDParam(1, p->name_2);
	SetDParam(2, _date);
	GetString(_edit_str_buf, STR_4004);
}

extern void StartupEngines(void);

static void SaveLoadDlgWndProc(Window *w, WindowEvent *e)
{
	static FiosItem o_dir;

	switch (e->event) {
	case WE_CREATE: { /* Set up OPENTTD button */
		o_dir.type = FIOS_TYPE_DIRECT;
		switch (_saveload_mode) {
			case SLD_SAVE_GAME:
			case SLD_LOAD_GAME:
				ttd_strlcpy(&o_dir.name[0], _path.save_dir, sizeof(o_dir.name));
				break;

			case SLD_SAVE_SCENARIO:
			case SLD_LOAD_SCENARIO:
				ttd_strlcpy(&o_dir.name[0], _path.scenario_dir, sizeof(o_dir.name));
				break;

			case SLD_LOAD_HEIGHTMAP:
				ttd_strlcpy(&o_dir.name[0], _path.heightmap_dir, sizeof(o_dir.name));
				break;

			default:
				ttd_strlcpy(&o_dir.name[0], _path.personal_dir, sizeof(o_dir.name));
		}
		break;
		}

	case WE_PAINT: {
		int pos;
		int y;

		SetVScrollCount(w, _fios_num);
		DrawWindowWidgets(w);
		DrawFiosTexts(w->width);

		if (_savegame_sort_dirty) {
			_savegame_sort_dirty = false;
			MakeSortedSaveGameList();
		}

		GfxFillRect(w->widget[7].left + 1, w->widget[7].top + 1, w->widget[7].right, w->widget[7].bottom, 0xD7);
		DoDrawString(
			_savegame_sort_order & SORT_DESCENDING ? DOWNARROW : UPARROW,
			_savegame_sort_order & SORT_BY_NAME ? w->widget[2].right - 9 : w->widget[3].right - 9,
			15, 16
		);

		y = w->widget[7].top + 1;
		for (pos = w->vscroll.pos; pos < _fios_num; pos++) {
			const FiosItem *item = _fios_list + pos;

			DoDrawStringTruncated(item->title, 4, y, _fios_colors[item->type], w->width - 18);
			y += 10;
			if (y >= w->vscroll.cap * 10 + w->widget[7].top + 1) break;
		}

		if (_saveload_mode == SLD_SAVE_GAME || _saveload_mode == SLD_SAVE_SCENARIO) {
			DrawEditBox(w, &WP(w,querystr_d), 10);
		}
		break;
	}

	case WE_CLICK:
		switch (e->we.click.widget) {
		case 2: /* Sort save names by name */
			_savegame_sort_order = (_savegame_sort_order == SORT_BY_NAME) ?
				SORT_BY_NAME | SORT_DESCENDING : SORT_BY_NAME;
			_savegame_sort_dirty = true;
			SetWindowDirty(w);
			break;

		case 3: /* Sort save names by date */
			_savegame_sort_order = (_savegame_sort_order == SORT_BY_DATE) ?
				SORT_BY_DATE | SORT_DESCENDING : SORT_BY_DATE;
			_savegame_sort_dirty = true;
			SetWindowDirty(w);
			break;

		case 6: /* OpenTTD 'button', jumps to OpenTTD directory */
			FiosBrowseTo(&o_dir);
			SetWindowDirty(w);
			BuildFileList();
			break;

		case 7: { /* Click the listbox */
			int y = (e->we.click.pt.y - w->widget[e->we.click.widget].top - 1) / 10;
			char *name;
			const FiosItem *file;

			if (y < 0 || (y += w->vscroll.pos) >= w->vscroll.count) return;

			file = _fios_list + y;

			name = FiosBrowseTo(file);
			if (name != NULL) {
				if (_saveload_mode == SLD_LOAD_GAME || _saveload_mode == SLD_LOAD_SCENARIO) {
					_switch_mode = (_game_mode == GM_EDITOR) ? SM_LOAD_SCENARIO : SM_LOAD;

					SetFiosType(file->type);
					ttd_strlcpy(_file_to_saveload.name, name, sizeof(_file_to_saveload.name));
					ttd_strlcpy(_file_to_saveload.title, file->title, sizeof(_file_to_saveload.title));

					DeleteWindow(w);
				} else if (_saveload_mode == SLD_LOAD_HEIGHTMAP) {
					SetFiosType(file->type);
					ttd_strlcpy(_file_to_saveload.name, name, sizeof(_file_to_saveload.name));
					ttd_strlcpy(_file_to_saveload.title, file->title, sizeof(_file_to_saveload.title));

					DeleteWindow(w);
					ShowHeightmapLoad();
				} else {
					// SLD_SAVE_GAME, SLD_SAVE_SCENARIO copy clicked name to editbox
					ttd_strlcpy(WP(w, querystr_d).text.buf, file->title, WP(w, querystr_d).text.maxlength);
					UpdateTextBufferSize(&WP(w, querystr_d).text);
					InvalidateWidget(w, 10);
				}
			} else {
				// Changed directory, need repaint.
				SetWindowDirty(w);
				BuildFileList();
			}
			break;
		}

		case 11: case 12: /* Delete, Save game */
			break;
		}
		break;
	case WE_MOUSELOOP:
		HandleEditBox(w, &WP(w, querystr_d), 10);
		break;
	case WE_KEYPRESS:
		if (e->we.keypress.keycode == WKC_ESC) {
			DeleteWindow(w);
			return;
		}

		if (_saveload_mode == SLD_SAVE_GAME || _saveload_mode == SLD_SAVE_SCENARIO) {
			if (HandleEditBoxKey(w, &WP(w, querystr_d), 10, e, CS_ALPHANUMERAL) == 1) /* Press Enter */
					HandleButtonClick(w, 12);
		}
		break;
	case WE_TIMEOUT:
		if (HASBIT(w->click_state, 11)) { /* Delete button clicked */
			if (!FiosDelete(OTTD2FS(WP(w,querystr_d).text.buf))) {
				ShowErrorMessage(INVALID_STRING_ID, STR_4008_UNABLE_TO_DELETE_FILE, 0, 0);
			} else {
				BuildFileList();
				/* Reset file name to current date on successfull delete */
				if (_saveload_mode == SLD_SAVE_GAME) GenerateFileName();
			}

			UpdateTextBufferSize(&WP(w, querystr_d).text);
			SetWindowDirty(w);
		} else if (HASBIT(w->click_state, 12)) { /* Save button clicked */
			_switch_mode = SM_SAVE;
			FiosMakeSavegameName(_file_to_saveload.name, WP(w,querystr_d).text.buf, sizeof(_file_to_saveload.name));

			/* In the editor set up the vehicle engines correctly (date might have changed) */
			if (_game_mode == GM_EDITOR) StartupEngines();
		}
		break;
	case WE_DESTROY:
		// pause is only used in single-player, non-editor mode, non menu mode
		if (!_networking && _game_mode != GM_EDITOR && _game_mode != GM_MENU) {
			DoCommandP(0, 0, 0, NULL, CMD_PAUSE);
		}
		FiosFreeSavegameList();
		CLRBIT(_no_scroll, SCROLL_SAVE);
		break;
	case WE_RESIZE: {
		/* Widget 2 and 3 have to go with halve speed, make it so obiwan */
		uint diff = e->we.sizing.diff.x / 2;
		w->widget[2].right += diff;
		w->widget[3].left  += diff;
		w->widget[3].right += e->we.sizing.diff.x;

		/* Same for widget 11 and 12 in save-dialog */
		if (_saveload_mode == SLD_SAVE_GAME || _saveload_mode == SLD_SAVE_SCENARIO) {
			w->widget[11].right += diff;
			w->widget[12].left  += diff;
			w->widget[12].right += e->we.sizing.diff.x;
		}

		w->vscroll.cap += e->we.sizing.diff.y / 10;
		} break;
	}
}

static const WindowDesc _load_dialog_desc = {
	WDP_CENTER, WDP_CENTER, 257, 294,
	WC_SAVELOAD,0,
	WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_STD_BTN | WDF_UNCLICK_BUTTONS | WDF_RESIZABLE,
	_load_dialog_1_widgets,
	SaveLoadDlgWndProc,
};

static const WindowDesc _load_dialog_scen_desc = {
	WDP_CENTER, WDP_CENTER, 257, 294,
	WC_SAVELOAD,0,
	WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_STD_BTN | WDF_UNCLICK_BUTTONS | WDF_RESIZABLE,
	_load_dialog_2_widgets,
	SaveLoadDlgWndProc,
};

static const WindowDesc _save_dialog_desc = {
	WDP_CENTER, WDP_CENTER, 257, 320,
	WC_SAVELOAD,0,
	WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_STD_BTN | WDF_UNCLICK_BUTTONS | WDF_RESIZABLE,
	_save_dialog_widgets,
	SaveLoadDlgWndProc,
};

static const WindowDesc _save_dialog_scen_desc = {
	WDP_CENTER, WDP_CENTER, 257, 320,
	WC_SAVELOAD,0,
	WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_STD_BTN | WDF_UNCLICK_BUTTONS | WDF_RESIZABLE,
	_save_dialog_scen_widgets,
	SaveLoadDlgWndProc,
};

static const WindowDesc _load_dialog_heightmap_desc = {
	WDP_CENTER, WDP_CENTER, 257, 294,
	WC_SAVELOAD,0,
	WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_STD_BTN | WDF_UNCLICK_BUTTONS | WDF_RESIZABLE,
	_load_dialog_3_widgets,
	SaveLoadDlgWndProc,
};

static const WindowDesc * const _saveload_dialogs[] = {
	&_load_dialog_desc,
	&_load_dialog_scen_desc,
	&_save_dialog_desc,
	&_save_dialog_scen_desc,
	&_load_dialog_heightmap_desc,
};

void ShowSaveLoadDialog(int mode)
{
	Window *w;

	SetObjectToPlace(SPR_CURSOR_ZZZ, 0, 0, 0);
	DeleteWindowById(WC_QUERY_STRING, 0);
	DeleteWindowById(WC_SAVELOAD, 0);

	_saveload_mode = mode;
	SETBIT(_no_scroll, SCROLL_SAVE);

	switch (mode) {
		case SLD_SAVE_GAME:     GenerateFileName(); break;
		case SLD_SAVE_SCENARIO: strcpy(_edit_str_buf, "UNNAMED"); break;
	}

	w = AllocateWindowDesc(_saveload_dialogs[mode]);
	w->vscroll.cap = 24;
	w->resize.step_width = 2;
	w->resize.step_height = 10;
	w->resize.height = w->height - 14 * 10; // Minimum of 10 items
	SETBIT(w->click_state, 7);
	WP(w,querystr_d).text.caret = false;
	WP(w,querystr_d).text.maxlength = lengthof(_edit_str_buf);
	WP(w,querystr_d).text.maxwidth = 240;
	WP(w,querystr_d).text.buf = _edit_str_buf;
	UpdateTextBufferSize(&WP(w, querystr_d).text);

	// pause is only used in single-player, non-editor mode, non-menu mode. It
	// will be unpaused in the WE_DESTROY event handler.
	if (_game_mode != GM_MENU && !_networking && _game_mode != GM_EDITOR) {
		DoCommandP(0, 1, 0, NULL, CMD_PAUSE);
	}

	BuildFileList();

	ResetObjectToPlace();
}

void RedrawAutosave(void)
{
	SetWindowDirty(FindWindowById(WC_STATUS_BAR, 0));
}

void SetFiosType(const byte fiostype)
{
	switch (fiostype) {
		case FIOS_TYPE_FILE:
		case FIOS_TYPE_SCENARIO:
			_file_to_saveload.mode = SL_LOAD;
			break;

		case FIOS_TYPE_OLDFILE:
		case FIOS_TYPE_OLD_SCENARIO:
			_file_to_saveload.mode = SL_OLD_LOAD;
			break;

#ifdef WITH_PNG
		case FIOS_TYPE_PNG:
			_file_to_saveload.mode = SL_PNG;
			break;
#endif /* WITH_PNG */

		case FIOS_TYPE_BMP:
			_file_to_saveload.mode = SL_BMP;
			break;

		default:
			_file_to_saveload.mode = SL_INVALID;
			break;
	}
}

static int32 ClickMoneyCheat(int32 p1, int32 p2)
{
		DoCommandP(0, -10000000, 0, NULL, CMD_MONEY_CHEAT);
		return true;
}

// p1 player to set to, p2 is -1 or +1 (down/up)
static int32 ClickChangePlayerCheat(int32 p1, int32 p2)
{
	while (p1 >= 0 && p1 < MAX_PLAYERS) {
		if (_players[p1].is_active) {
			_local_player = p1;
			MarkWholeScreenDirty();
			return _local_player;
		}
		p1 += p2;
	}

	return _local_player;
}

// p1 -1 or +1 (down/up)
static int32 ClickChangeClimateCheat(int32 p1, int32 p2)
{
	if (p1 == -1) p1 = 3;
	if (p1 ==  4) p1 = 0;
	_opt.landscape = p1;
	GfxLoadSprites();
	MarkWholeScreenDirty();
	return _opt.landscape;
}

extern void EnginesMonthlyLoop(void);

// p2 1 (increase) or -1 (decrease)
static int32 ClickChangeDateCheat(int32 p1, int32 p2)
{
	YearMonthDay ymd;
	ConvertDateToYMD(_date, &ymd);

	if ((ymd.year == MIN_YEAR && p2 == -1) || (ymd.year == MAX_YEAR && p2 == 1)) return _cur_year;

	SetDate(ConvertYMDToDate(_cur_year + p2, ymd.month, ymd.day));
	EnginesMonthlyLoop();
	SetWindowDirty(FindWindowById(WC_STATUS_BAR, 0));
	return _cur_year;
}

static int32 ClickAllowConvrail(int32 p1, int32 p2)
{
	Vehicle *v;
	SB(_railtypes[RAILTYPE_ELECTRIC].powered_railtypes, RAILTYPE_RAIL, 1, p1);

	FOR_ALL_VEHICLES(v) {
		if (v->type == VEH_Train && IsFrontEngine(v)) TrainConsistChanged(v);
	}
	return p1;
}


typedef int32 CheckButtonClick(int32, int32);

enum ce_flags {CE_CLICK = 1 << 0};

typedef byte ce_flags;

typedef struct CheatEntry {
	VarType type;          // type of selector
	ce_flags flags;        // selector flags
	StringID str;          // string with descriptive text
	void *variable;        // pointer to the variable
	bool *been_used;       // has this cheat been used before?
	CheckButtonClick *proc;// procedure
	int16 min, max;        // range for spinbox setting
} CheatEntry;

static const CheatEntry _cheats_ui[] = {
	{SLE_BOOL,CE_CLICK, STR_CHEAT_MONEY,          &_cheats.money.value,           &_cheats.money.been_used,           &ClickMoneyCheat,         0,  0},
	{SLE_UINT8,      0, STR_CHEAT_CHANGE_PLAYER,  &_local_player,                 &_cheats.switch_player.been_used,   &ClickChangePlayerCheat,  0, 11},
	{SLE_BOOL,       0, STR_CHEAT_EXTRA_DYNAMITE, &_cheats.magic_bulldozer.value, &_cheats.magic_bulldozer.been_used, NULL,                     0,  0},
	{SLE_BOOL,       0, STR_CHEAT_CROSSINGTUNNELS,&_cheats.crossing_tunnels.value,&_cheats.crossing_tunnels.been_used,NULL,                     0,  0},
	{SLE_BOOL,       0, STR_CHEAT_BUILD_IN_PAUSE, &_cheats.build_in_pause.value,  &_cheats.build_in_pause.been_used,  NULL,                     0,  0},
	{SLE_BOOL,       0, STR_CHEAT_NO_JETCRASH,    &_cheats.no_jetcrash.value,     &_cheats.no_jetcrash.been_used,     NULL,                     0,  0},
	{SLE_BOOL,       0, STR_CHEAT_SETUP_PROD,     &_cheats.setup_prod.value,      &_cheats.setup_prod.been_used,      NULL,                     0,  0},
	{SLE_UINT8,      0, STR_CHEAT_SWITCH_CLIMATE, &_opt.landscape,                &_cheats.switch_climate.been_used,  &ClickChangeClimateCheat,-1,  4},
	{SLE_INT32,      0, STR_CHEAT_CHANGE_DATE,    &_cur_year,                     &_cheats.change_date.been_used,     &ClickChangeDateCheat,   -1,  1},
	{SLE_BOOL,       0, STR_CHEAT_ALLOW_CONVRAIL, &_cheats.elrail.value,          &_cheats.elrail.been_used,          &ClickAllowConvrail,      0,  0},
};


static const Widget _cheat_widgets[] = {
{   WWT_CLOSEBOX,   RESIZE_NONE,    14,     0,    10,     0,    13, STR_00C5,   STR_018B_CLOSE_WINDOW},
{    WWT_CAPTION,   RESIZE_NONE,    14,    11,   399,     0,    13, STR_CHEATS, STR_018C_WINDOW_TITLE_DRAG_THIS},
{      WWT_PANEL,   RESIZE_NONE,    14,     0,   399,    14,   169, 0x0,        STR_NULL},
{     WWT_IMGBTN,   RESIZE_NONE,    14,     0,   399,    14,   169, 0x0,        STR_CHEATS_TIP},
{   WIDGETS_END},
};

extern void DrawPlayerIcon(PlayerID pid, int x, int y);

static void CheatsWndProc(Window *w, WindowEvent *e)
{
	switch (e->event) {
	case WE_PAINT: {
		int clk = WP(w,def_d).data_1;
		int x, y;
		int i;

		DrawWindowWidgets(w);

		DrawStringMultiCenter(200, 25, STR_CHEATS_WARNING, 350);

		x = 0;
		y = 45;

		for (i = 0; i != lengthof(_cheats_ui); i++) {
			const CheatEntry *ce = &_cheats_ui[i];

			DrawSprite((*ce->been_used) ? SPR_BOX_CHECKED : SPR_BOX_EMPTY, x + 5, y + 2);

			switch (ce->type) {
			case SLE_BOOL: {
				bool on = (*(bool*)ce->variable);

				if (ce->flags & CE_CLICK) {
					DrawFrameRect(x + 20, y + 1, x + 30 + 9, y + 9, 0, (clk - (i * 2) == 1) ? FR_LOWERED : 0);
					if (i == 0) { // XXX - hack/hack for first element which is increase money. Told ya it's a mess
						SetDParam64(0, 10000000);
					} else {
						SetDParam(0, false);
					}
				} else {
					DrawFrameRect(x + 20, y + 1, x + 30 + 9, y + 9, on ? 6 : 4, on ? FR_LOWERED : 0);
					SetDParam(0, on ? STR_CONFIG_PATCHES_ON : STR_CONFIG_PATCHES_OFF);
				}
			} break;
			default: {
				int32 val = (int32)ReadValue(ce->variable, ce->type);
				char buf[512];

				/* Draw [<][>] boxes for settings of an integer-type */
				DrawArrowButtons(x + 20, y, 3, clk - (i * 2), true, true);

				switch (ce->str) {
				/* Display date for change date cheat */
				case STR_CHEAT_CHANGE_DATE: SetDParam(0, _date); break;
				/* Draw colored flag for change player cheat */
				case STR_CHEAT_CHANGE_PLAYER:
					SetDParam(0, val);
					GetString(buf, STR_CHEAT_CHANGE_PLAYER);
					DrawPlayerIcon(_current_player, 60 + GetStringBoundingBox(buf).width, y + 2);
					break;
				/* Set correct string for switch climate cheat */
				case STR_CHEAT_SWITCH_CLIMATE: val += STR_TEMPERATE_LANDSCAPE;
				/* Fallthrough */
				default: SetDParam(0, val);
				}
			} break;
			}

			DrawString(50, y + 1, ce->str, 0);

			y += 12;
		}
		break;
	}

	case WE_CLICK: {
			const CheatEntry *ce;
			uint btn = (e->we.click.pt.y - 46) / 12;
			int32 value, oldvalue;
			uint x = e->we.click.pt.x;

			// not clicking a button?
			if (!IS_INT_INSIDE(x, 20, 40) || btn >= lengthof(_cheats_ui)) break;

			ce = &_cheats_ui[btn];
			oldvalue = value = (int32)ReadValue(ce->variable, ce->type);

			*ce->been_used = true;

			switch (ce->type) {
			case SLE_BOOL:
				if (ce->flags & CE_CLICK) WP(w,def_d).data_1 = btn * 2 + 1;
				value ^= 1;
				if (ce->proc != NULL) ce->proc(value, 0);
				break;
			default: {
				/* Add a dynamic step-size to the scroller. In a maximum of
				 * 50-steps you should be able to get from min to max */
				uint16 step = ((ce->max - ce->min) / 20);
				if (step == 0) step = 1;

				/* Increase or decrease the value and clamp it to extremes */
				value += (x >= 30) ? step : -step;
				clamp(value, ce->min, ce->max);

				// take whatever the function returns
				value = ce->proc(value, (x >= 30) ? 1 : -1);

				if (value != oldvalue) {
					WP(w,def_d).data_1 = btn * 2 + 1 + ((x >= 30) ? 1 : 0);
				}
			} break;
			}

			if (value != oldvalue) {
				WriteValue(ce->variable, ce->type, (int64)value);
				SetWindowDirty(w);
			}

			w->flags4 |= 5 << WF_TIMEOUT_SHL;

			SetWindowDirty(w);
		}
		break;
	case WE_TIMEOUT:
		WP(w,def_d).data_1 = 0;
		SetWindowDirty(w);
		break;
	}
}

static const WindowDesc _cheats_desc = {
	240, 22, 400, 170,
	WC_CHEATS,0,
	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
	_cheat_widgets,
	CheatsWndProc
};


void ShowCheatWindow(void)
{
	Window *w;

	DeleteWindowById(WC_CHEATS, 0);
	w = AllocateWindowDesc(&_cheats_desc);

	if (w != NULL) SetWindowDirty(w);
}

/** Resize the widgets in a window
 * @param *w Window to resize in
 * @param *resizearray Bytearray of the same length as the window contains widgets. Each byte tells how to move the widget of the same index using the flags in resize_window_widgets.h
 * @param length Length of the bytearray
 * @param horizontal Tells how far to the right the widgets should be moved (note: negative moves left)
 * @param vertical Tells how far down the widgets should be moved (note: negative moves up)
*/
void ResizeWindowWidgets(Window *w, const byte *resizearray, int16 length, byte horizontal, int16 vertical)
{
	byte i;

	for (i = 0; i < length; i++) {
		if (resizearray[i] & WIDGET_DEFINE_MOVE_LEFT)   w->widget[i].left   += horizontal;
		if (resizearray[i] & WIDGET_DEFINE_MOVE_RIGHT)  w->widget[i].right  += horizontal;
		if (resizearray[i] & WIDGET_DEFINE_MOVE_TOP)    w->widget[i].top    += vertical;
		if (resizearray[i] & WIDGET_DEFINE_MOVE_BOTTOM) w->widget[i].bottom += vertical;
	}
}