Files @ r18753:19e74c935c2d
Branch filter:

Location: cpp/openttd-patchpack/source/src/newgrf_gui.cpp

truebrain
(svn r23611) -Add: run the begin of the script already while generating, and don't sleep on DoCommand while doing so
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
/* $Id$ */

/*
 * This file is part of OpenTTD.
 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
 */

/** @file newgrf_gui.cpp GUI to change NewGRF settings. */

#include "stdafx.h"
#include "error.h"
#include "gui.h"
#include "newgrf.h"
#include "strings_func.h"
#include "window_func.h"
#include "gamelog.h"
#include "settings_type.h"
#include "settings_func.h"
#include "widgets/dropdown_type.h"
#include "network/network.h"
#include "network/network_content.h"
#include "sortlist_type.h"
#include "querystring_gui.h"
#include "core/geometry_func.hpp"
#include "newgrf_text.h"
#include "fileio_func.h"
#include "fontcache.h"

#include "widgets/newgrf_widget.h"

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

/**
 * Show the first NewGRF error we can find.
 */
void ShowNewGRFError()
{
	/* Do not show errors when entering the main screen */
	if (_game_mode == GM_MENU) return;

	for (const GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
		/* We only want to show fatal errors */
		if (c->error == NULL || c->error->severity != STR_NEWGRF_ERROR_MSG_FATAL) continue;

		SetDParam   (0, c->error->custom_message == NULL ? c->error->message : STR_JUST_RAW_STRING);
		SetDParamStr(1, c->error->custom_message);
		SetDParam   (2, STR_JUST_RAW_STRING);
		SetDParamStr(3, c->filename);
		SetDParam   (4, STR_JUST_RAW_STRING);
		SetDParamStr(5, c->error->data);
		for (uint i = 0; i < c->error->num_params; i++) {
			SetDParam(6 + i, c->error->param_value[i]);
		}
		ShowErrorMessage(STR_NEWGRF_ERROR_FATAL_POPUP, INVALID_STRING_ID, WL_CRITICAL);
		break;
	}
}

static void ShowNewGRFInfo(const GRFConfig *c, uint x, uint y, uint right, uint bottom, bool show_params)
{
	if (c->error != NULL) {
		char message[512];
		SetDParamStr(0, c->error->custom_message); // is skipped by built-in messages
		SetDParam   (1, STR_JUST_RAW_STRING);
		SetDParamStr(2, c->filename);
		SetDParam   (3, STR_JUST_RAW_STRING);
		SetDParamStr(4, c->error->data);
		for (uint i = 0; i < c->error->num_params; i++) {
			SetDParam(5 + i, c->error->param_value[i]);
		}
		GetString(message, c->error->custom_message == NULL ? c->error->message : STR_JUST_RAW_STRING, lastof(message));

		SetDParamStr(0, message);
		y = DrawStringMultiLine(x, right, y, bottom, c->error->severity);
	}

	/* Draw filename or not if it is not known (GRF sent over internet) */
	if (c->filename != NULL) {
		SetDParamStr(0, c->filename);
		y = DrawStringMultiLine(x, right, y, bottom, STR_NEWGRF_SETTINGS_FILENAME);
	}

	/* Prepare and draw GRF ID */
	char buff[256];
	snprintf(buff, lengthof(buff), "%08X", BSWAP32(c->ident.grfid));
	SetDParamStr(0, buff);
	y = DrawStringMultiLine(x, right, y, bottom, STR_NEWGRF_SETTINGS_GRF_ID);

	if ((_settings_client.gui.newgrf_developer_tools || _settings_client.gui.newgrf_show_old_versions) && c->version != 0) {
		SetDParam(0, c->version);
		y = DrawStringMultiLine(x, right, y, bottom, STR_NEWGRF_SETTINGS_VERSION);
	}
	if ((_settings_client.gui.newgrf_developer_tools || _settings_client.gui.newgrf_show_old_versions) && c->min_loadable_version != 0) {
		SetDParam(0, c->min_loadable_version);
		y = DrawStringMultiLine(x, right, y, bottom, STR_NEWGRF_SETTINGS_MIN_VERSION);
	}

	/* Prepare and draw MD5 sum */
	md5sumToString(buff, lastof(buff), c->ident.md5sum);
	SetDParamStr(0, buff);
	y = DrawStringMultiLine(x, right, y, bottom, STR_NEWGRF_SETTINGS_MD5SUM);

	/* Show GRF parameter list */
	if (show_params) {
		if (c->num_params > 0) {
			GRFBuildParamList(buff, c, lastof(buff));
			SetDParam(0, STR_JUST_RAW_STRING);
			SetDParamStr(1, buff);
		} else {
			SetDParam(0, STR_LAND_AREA_INFORMATION_LOCAL_AUTHORITY_NONE);
		}
		y = DrawStringMultiLine(x, right, y, bottom, STR_NEWGRF_SETTINGS_PARAMETER);

		/* Draw the palette of the NewGRF */
		if (c->palette & GRFP_BLT_32BPP) {
			SetDParamStr(0, (c->palette & GRFP_USE_WINDOWS) ? "Windows / 32 bpp" : "DOS / 32 bpp");
		} else {
			SetDParamStr(0, (c->palette & GRFP_USE_WINDOWS) ? "Windows" : "DOS");
		}
		y = DrawStringMultiLine(x, right, y, bottom, STR_NEWGRF_SETTINGS_PALETTE);
	}

	/* Show flags */
	if (c->status == GCS_NOT_FOUND)       y = DrawStringMultiLine(x, right, y, bottom, STR_NEWGRF_SETTINGS_NOT_FOUND);
	if (c->status == GCS_DISABLED)        y = DrawStringMultiLine(x, right, y, bottom, STR_NEWGRF_SETTINGS_DISABLED);
	if (HasBit(c->flags, GCF_INVALID))    y = DrawStringMultiLine(x, right, y, bottom, STR_NEWGRF_SETTINGS_INCOMPATIBLE);
	if (HasBit(c->flags, GCF_COMPATIBLE)) y = DrawStringMultiLine(x, right, y, bottom, STR_NEWGRF_COMPATIBLE_LOADED);

	/* Draw GRF info if it exists */
	if (!StrEmpty(c->GetDescription())) {
		SetDParam(0, STR_JUST_RAW_STRING);
		SetDParamStr(1, c->GetDescription());
		y = DrawStringMultiLine(x, right, y, bottom, STR_BLACK_STRING);
	} else {
		y = DrawStringMultiLine(x, right, y, bottom, STR_NEWGRF_SETTINGS_NO_INFO);
	}
}

/**
 * Window for setting the parameters of a NewGRF.
 */
struct NewGRFParametersWindow : public Window {
	static GRFParameterInfo dummy_parameter_info; ///< Dummy info in case a newgrf didn't provide info about some parameter.
	GRFConfig *grf_config; ///< Set the parameters of this GRFConfig.
	uint clicked_button;   ///< The row in which a button was clicked or UINT_MAX.
	bool clicked_increase; ///< True if the increase button was clicked, false for the decrease button.
	int timeout;           ///< How long before we unpress the last-pressed button?
	uint clicked_row;      ///< The selected parameter
	int line_height;       ///< Height of a row in the matrix widget.
	Scrollbar *vscroll;
	bool action14present;  ///< True if action14 information is present.

	NewGRFParametersWindow(const WindowDesc *desc, GRFConfig *c) : Window(),
		grf_config(c),
		clicked_button(UINT_MAX),
		timeout(0),
		clicked_row(UINT_MAX)
	{
		this->action14present = (c->num_valid_params != lengthof(c->param) || c->param_info.Length() != 0);

		this->CreateNestedTree(desc);
		this->vscroll = this->GetScrollbar(WID_NP_SCROLLBAR);
		this->GetWidget<NWidgetStacked>(WID_NP_SHOW_NUMPAR)->SetDisplayedPlane(this->action14present ? SZSP_HORIZONTAL : 0);
		this->GetWidget<NWidgetStacked>(WID_NP_SHOW_DESCRIPTION)->SetDisplayedPlane(this->action14present ? 0 : SZSP_HORIZONTAL);
		this->FinishInitNested(desc);  // Initializes 'this->line_height' as side effect.

		this->InvalidateData();
	}

	/**
	 * Get a dummy parameter-info object with default information.
	 * @param nr The param number that should be changed.
	 * @return GRFParameterInfo with dummy information about the given parameter.
	 */
	static GRFParameterInfo *GetDummyParameterInfo(uint nr)
	{
		dummy_parameter_info.param_nr = nr;
		return &dummy_parameter_info;
	}

	virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
	{
		switch (widget) {
			case WID_NP_NUMPAR_DEC:
			case WID_NP_NUMPAR_INC: {
				size->width = size->height = FONT_HEIGHT_NORMAL;
				break;
			}

			case WID_NP_NUMPAR: {
				SetDParam(0, 999);
				Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
				d.width += padding.width;
				d.height += padding.height;
				*size = maxdim(*size, d);
				break;
			}

			case WID_NP_BACKGROUND:
				this->line_height = FONT_HEIGHT_NORMAL + WD_MATRIX_TOP + WD_MATRIX_BOTTOM;

				resize->width = 1;
				resize->height = this->line_height;
				size->height = GB(this->GetWidget<NWidgetCore>(widget)->widget_data, MAT_ROW_START, MAT_ROW_BITS) * this->line_height;
				break;

			case WID_NP_DESCRIPTION:
				size->height = max<uint>(size->height, FONT_HEIGHT_NORMAL * 4 + WD_TEXTPANEL_TOP + WD_TEXTPANEL_BOTTOM);
				break;
		}
	}

	virtual void SetStringParameters(int widget) const
	{
		switch (widget) {
			case WID_NP_NUMPAR:
				SetDParam(0, this->vscroll->GetCount());
				break;
		}
	}

	virtual void DrawWidget(const Rect &r, int widget) const
	{
		if (widget == WID_NP_DESCRIPTION) {
			const GRFParameterInfo *par_info = (this->clicked_row < this->grf_config->param_info.Length()) ? this->grf_config->param_info[this->clicked_row] : NULL;
			if (par_info == NULL) return;
			const char *desc = GetGRFStringFromGRFText(par_info->desc);
			if (desc == NULL) return;
			DrawStringMultiLine(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_TEXTPANEL_TOP, r.bottom - WD_TEXTPANEL_BOTTOM, desc, TC_BLACK);
			return;
		} else if (widget != WID_NP_BACKGROUND) {
			return;
		}

		bool rtl = _current_text_dir == TD_RTL;
		uint buttons_left = rtl ? r.right - 23 : r.left + 4;
		uint text_left    = r.left + (rtl ? WD_FRAMERECT_LEFT : 28);
		uint text_right   = r.right - (rtl ? 28 : WD_FRAMERECT_RIGHT);

		int y = r.top;
		for (uint i = this->vscroll->GetPosition(); this->vscroll->IsVisible(i) && i < this->vscroll->GetCount(); i++) {
			GRFParameterInfo *par_info = (i < this->grf_config->param_info.Length()) ? this->grf_config->param_info[i] : NULL;
			if (par_info == NULL) par_info = GetDummyParameterInfo(i);
			uint32 current_value = par_info->GetValue(this->grf_config);
			bool selected = (i == this->clicked_row);

			if (par_info->type == PTYPE_BOOL) {
				DrawFrameRect(buttons_left, y  + 2, buttons_left + 19, y + 10, (current_value != 0) ? COLOUR_GREEN : COLOUR_RED, (current_value != 0) ? FR_LOWERED : FR_NONE);
				SetDParam(2, par_info->GetValue(this->grf_config) == 0 ? STR_CONFIG_SETTING_OFF : STR_CONFIG_SETTING_ON);
			} else if (par_info->type == PTYPE_UINT_ENUM) {
				DrawArrowButtons(buttons_left, y + 2, COLOUR_YELLOW, (this->clicked_button == i) ? 1 + (this->clicked_increase != rtl) : 0, current_value > par_info->min_value, current_value < par_info->max_value);
				SetDParam(2, STR_JUST_INT);
				SetDParam(3, current_value);
				if (par_info->value_names.Contains(current_value)) {
					const char *label = GetGRFStringFromGRFText(par_info->value_names.Find(current_value)->second);
					if (label != NULL) {
						SetDParam(2, STR_JUST_RAW_STRING);
						SetDParamStr(3, label);
					}
				}
			}

			const char *name = GetGRFStringFromGRFText(par_info->name);
			if (name != NULL) {
				SetDParam(0, STR_JUST_RAW_STRING);
				SetDParamStr(1, name);
			} else {
				SetDParam(0, STR_NEWGRF_PARAMETERS_DEFAULT_NAME);
				SetDParam(1, i + 1);
			}

			DrawString(text_left, text_right, y + WD_MATRIX_TOP, STR_NEWGRF_PARAMETERS_SETTING, selected ? TC_WHITE : TC_LIGHT_BLUE);
			y += this->line_height;
		}
	}

	virtual void OnClick(Point pt, int widget, int click_count)
	{
		switch (widget) {
			case WID_NP_NUMPAR_DEC:
				if (!this->action14present && this->grf_config->num_params > 0) {
					this->grf_config->num_params--;
					this->InvalidateData();
					SetWindowDirty(WC_GAME_OPTIONS, WN_GAME_OPTIONS_NEWGRF_STATE);
				}
				break;

			case WID_NP_NUMPAR_INC: {
				GRFConfig *c = this->grf_config;
				if (!this->action14present && c->num_params < c->num_valid_params) {
					c->param[c->num_params++] = 0;
					this->InvalidateData();
					SetWindowDirty(WC_GAME_OPTIONS, WN_GAME_OPTIONS_NEWGRF_STATE);
				}
				break;
			}

			case WID_NP_BACKGROUND: {
				uint num = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NP_BACKGROUND);
				if (num >= this->vscroll->GetCount()) break;
				if (this->clicked_row != num) {
					DeleteChildWindows(WC_QUERY_STRING);
					this->clicked_row = num;
				}

				const NWidgetBase *wid = this->GetWidget<NWidgetBase>(WID_NP_BACKGROUND);
				int x = pt.x - wid->pos_x;
				if (_current_text_dir == TD_RTL) x = wid->current_x - x;
				x -= 4;

				GRFParameterInfo *par_info = (num < this->grf_config->param_info.Length()) ? this->grf_config->param_info[num] : NULL;
				if (par_info == NULL) par_info = GetDummyParameterInfo(num);

				/* One of the arrows is clicked */
				if (IsInsideMM(x, 0, 21)) {
					uint32 val = par_info->GetValue(this->grf_config);
					uint32 old_val = val;
					if (par_info->type == PTYPE_BOOL) {
						val = !val;
					} else {
						if (x >= 10) {
							/* Increase button clicked */
							if (val < par_info->max_value) val++;
							this->clicked_increase = true;
						} else {
							/* Decrease button clicked */
							if (val > par_info->min_value) val--;
							this->clicked_increase = false;
						}
					}
					if (val != old_val) {
						par_info->SetValue(this->grf_config, val);

						this->clicked_button = num;
						this->timeout = 5;
					}
				} else if (par_info->type == PTYPE_UINT_ENUM && click_count >= 2) {
					/* Display a query box so users can enter a custom value. */
					SetDParam(0, this->grf_config->param[num]);
					ShowQueryString(STR_JUST_INT, STR_CONFIG_SETTING_QUERY_CAPTION, 10, this, CS_NUMERAL, QSF_NONE);
				}
				this->SetDirty();
				break;
			}

			case WID_NP_RESET:
				this->grf_config->SetParameterDefaults();
				this->InvalidateData();
				SetWindowDirty(WC_GAME_OPTIONS, WN_GAME_OPTIONS_NEWGRF_STATE);
				break;

			case WID_NP_ACCEPT:
				delete this;
				break;
		}
	}

	virtual void OnQueryTextFinished(char *str)
	{
		if (StrEmpty(str)) return;
		int32 value = atoi(str);
		GRFParameterInfo *par_info = ((uint)this->clicked_row < this->grf_config->param_info.Length()) ? this->grf_config->param_info[this->clicked_row] : NULL;
		if (par_info == NULL) par_info = GetDummyParameterInfo(this->clicked_row);
		uint32 val = Clamp<uint32>(value, par_info->min_value, par_info->max_value);
		par_info->SetValue(this->grf_config, val);
		this->SetDirty();
	}

	virtual void OnResize()
	{
		NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_NP_BACKGROUND);
		this->vscroll->SetCapacity(nwi->current_y / this->line_height);
		nwi->widget_data = (this->vscroll->GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
	}

	/**
	 * Some data on this window has become invalid.
	 * @param data Information about the changed data.
	 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
	 */
	virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
	{
		if (!gui_scope) return;
		if (!this->action14present) {
			this->SetWidgetDisabledState(WID_NP_NUMPAR_DEC, this->grf_config->num_params == 0);
			this->SetWidgetDisabledState(WID_NP_NUMPAR_INC, this->grf_config->num_params >= this->grf_config->num_valid_params);
		}

		this->vscroll->SetCount(this->action14present ? this->grf_config->num_valid_params : this->grf_config->num_params);
		if (this->clicked_row != UINT_MAX && this->clicked_row >= this->vscroll->GetCount()) {
			this->clicked_row = UINT_MAX;
			DeleteChildWindows(WC_QUERY_STRING);
		}
	}

	virtual void OnTick()
	{
		if (--this->timeout == 0) {
			this->clicked_button = UINT_MAX;
			this->SetDirty();
		}
	}
};
GRFParameterInfo NewGRFParametersWindow::dummy_parameter_info(0);


static const NWidgetPart _nested_newgrf_parameter_widgets[] = {
	NWidget(NWID_HORIZONTAL),
		NWidget(WWT_CLOSEBOX, COLOUR_MAUVE),
		NWidget(WWT_CAPTION, COLOUR_MAUVE), SetDataTip(STR_NEWGRF_PARAMETERS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
	EndContainer(),
	NWidget(NWID_SELECTION, INVALID_COLOUR, WID_NP_SHOW_NUMPAR),
		NWidget(WWT_PANEL, COLOUR_MAUVE), SetResize(1, 0), SetFill(1, 0), SetPIP(4, 0, 4),
			NWidget(NWID_HORIZONTAL), SetPIP(4, 0, 4),
				NWidget(WWT_PUSHARROWBTN, COLOUR_YELLOW, WID_NP_NUMPAR_DEC), SetMinimalSize(12, 12), SetDataTip(AWV_DECREASE, STR_NULL),
				NWidget(WWT_PUSHARROWBTN, COLOUR_YELLOW, WID_NP_NUMPAR_INC), SetMinimalSize(12, 12), SetDataTip(AWV_INCREASE, STR_NULL),
				NWidget(WWT_TEXT, COLOUR_MAUVE, WID_NP_NUMPAR), SetResize(1, 0), SetFill(1, 0), SetPadding(0, 0, 0, 4), SetDataTip(STR_NEWGRF_PARAMETERS_NUM_PARAM, STR_NULL),
			EndContainer(),
		EndContainer(),
	EndContainer(),
	NWidget(NWID_HORIZONTAL),
		NWidget(WWT_MATRIX, COLOUR_MAUVE, WID_NP_BACKGROUND), SetMinimalSize(188, 182), SetResize(1, 1), SetFill(1, 0), SetDataTip(0x501, STR_NULL), SetScrollbar(WID_NP_SCROLLBAR),
		NWidget(NWID_VSCROLLBAR, COLOUR_MAUVE, WID_NP_SCROLLBAR),
	EndContainer(),
	NWidget(NWID_SELECTION, INVALID_COLOUR, WID_NP_SHOW_DESCRIPTION),
		NWidget(WWT_PANEL, COLOUR_MAUVE, WID_NP_DESCRIPTION), SetResize(1, 0), SetFill(1, 0),
		EndContainer(),
	EndContainer(),
	NWidget(NWID_HORIZONTAL),
		NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
			NWidget(WWT_PUSHTXTBTN, COLOUR_MAUVE, WID_NP_ACCEPT), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_NEWGRF_PARAMETERS_CLOSE, STR_NULL),
			NWidget(WWT_PUSHTXTBTN, COLOUR_MAUVE, WID_NP_RESET), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_NEWGRF_PARAMETERS_RESET, STR_NEWGRF_PARAMETERS_RESET_TOOLTIP),
		EndContainer(),
		NWidget(WWT_RESIZEBOX, COLOUR_MAUVE),
	EndContainer(),
};

/** Window definition for the change grf parameters window */
static const WindowDesc _newgrf_parameters_desc(
	WDP_CENTER, 500, 208,
	WC_GRF_PARAMETERS, WC_NONE,
	WDF_UNCLICK_BUTTONS,
	_nested_newgrf_parameter_widgets, lengthof(_nested_newgrf_parameter_widgets)
);

void OpenGRFParameterWindow(GRFConfig *c)
{
	DeleteWindowByClass(WC_GRF_PARAMETERS);
	new NewGRFParametersWindow(&_newgrf_parameters_desc, c);
}

/** Window for displaying the textfile of a NewGRF. */
struct NewGRFTextfileWindow : public Window, MissingGlyphSearcher {
	const GRFConfig *grf_config;         ///< View the textfile of this GRFConfig.
	TextfileType file_type;              ///< Type of textfile to view.
	int line_height;                     ///< Height of a line in the display widget.
	Scrollbar *vscroll;                  ///< Vertical scrollbar.
	Scrollbar *hscroll;                  ///< Horizontal scrollbar.
	char *text;                          ///< Lines of text from the NewGRF's textfile.
	SmallVector<const char *, 64> lines; ///< #text, split into lines in a table with lines.
	uint max_length;                     ///< The longest line in the textfile (in pixels).

	static const int TOP_SPACING    = WD_FRAMETEXT_TOP;    ///< Additional spacing at the top of the #WID_NT_BACKGROUND widget.
	static const int BOTTOM_SPACING = WD_FRAMETEXT_BOTTOM; ///< Additional spacing at the bottom of the #WID_NT_BACKGROUND widget.

	NewGRFTextfileWindow(const WindowDesc *desc, const GRFConfig *c, TextfileType file_type) : Window(), grf_config(c), file_type(file_type)
	{
		this->CreateNestedTree(desc);
		this->GetWidget<NWidgetCore>(WID_NT_CAPTION)->SetDataTip(STR_NEWGRF_README_CAPTION + file_type, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS);
		this->vscroll = this->GetScrollbar(WID_NT_VSCROLLBAR);
		this->hscroll = this->GetScrollbar(WID_NT_HSCROLLBAR);
		this->FinishInitNested(desc);

		this->LoadTextfile();
	}

	~NewGRFTextfileWindow()
	{
		free(this->text);
	}

	virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
	{
		switch (widget) {
			case WID_NT_BACKGROUND:
				this->line_height = FONT_HEIGHT_MONO + 2;
				resize->height = this->line_height;

				size->height = 4 * resize->height + TOP_SPACING + BOTTOM_SPACING; // At least 4 lines are visible.
				size->width = max(200u, size->width); // At least 200 pixels wide.
				break;
		}
	}

	virtual void SetStringParameters(int widget) const
	{
		if (widget == WID_NT_CAPTION) SetDParamStr(0, this->grf_config->GetName());
	}

	virtual void DrawWidget(const Rect &r, int widget) const
	{
		if (widget != WID_NT_BACKGROUND) return;

		int width = r.right - r.left + 1 - WD_BEVEL_LEFT - WD_BEVEL_RIGHT;
		int height = r.bottom - r.top + 1 - WD_BEVEL_LEFT - WD_BEVEL_RIGHT;

		DrawPixelInfo new_dpi;
		if (!FillDrawPixelInfo(&new_dpi, r.left + WD_BEVEL_LEFT, r.top, width, height)) return;
		DrawPixelInfo *old_dpi = _cur_dpi;
		_cur_dpi = &new_dpi;

		int left, right;
		if (_current_text_dir == TD_RTL) {
			left = width + WD_BEVEL_RIGHT - WD_FRAMETEXT_RIGHT - this->hscroll->GetCount();
			right = width + WD_BEVEL_RIGHT - WD_FRAMETEXT_RIGHT - 1 + this->hscroll->GetPosition();
		} else {
			left = WD_FRAMETEXT_LEFT - WD_BEVEL_LEFT - this->hscroll->GetPosition();
			right = WD_FRAMETEXT_LEFT - WD_BEVEL_LEFT + this->hscroll->GetCount() - 1;
		}
		int top = TOP_SPACING;
		for (uint i = 0; i < this->vscroll->GetCapacity() && i + this->vscroll->GetPosition() < this->lines.Length(); i++) {
			DrawString(left, right, top + i * this->line_height, this->lines[i + this->vscroll->GetPosition()], TC_WHITE, SA_LEFT, false, FS_MONO);
		}

		_cur_dpi = old_dpi;
	}

	virtual void OnResize()
	{
		this->vscroll->SetCapacityFromWidget(this, WID_NT_BACKGROUND, TOP_SPACING + BOTTOM_SPACING);
		this->hscroll->SetCapacityFromWidget(this, WID_NT_BACKGROUND);
	}

private:
	uint search_iterator; ///< Iterator for the font check search.

	/* virtual */ void Reset()
	{
		this->search_iterator = 0;
	}

	FontSize DefaultSize()
	{
		return FS_MONO;
	}

	const char *NextString()
	{
		if (this->search_iterator >= this->lines.Length()) return NULL;

		return this->lines[this->search_iterator++];
	}

	/* virtual */ bool Monospace()
	{
		return true;
	}

	/* virtual */ void SetFontNames(FreeTypeSettings *settings, const char *font_name)
	{
#ifdef WITH_FREETYPE
		strecpy(settings->mono_font, font_name, lastof(settings->mono_font));
#endif /* WITH_FREETYPE */
	}

	/**
	 * Load the NewGRF's textfile text from file, and setup #lines, #max_length, and both scrollbars.
	 */
	void LoadTextfile()
	{
		this->lines.Clear();

		/* Does GRF have a file of the demanded type? */
		const char *textfile = this->grf_config->GetTextfile(file_type);
		if (textfile == NULL) return;

		/* Get text from file */
		size_t filesize;
		FILE *handle = FioFOpenFile(textfile, "rb", NEWGRF_DIR, &filesize);
		if (handle == NULL) return;

		this->text = ReallocT(this->text, filesize + 1);
		size_t read = fread(this->text, 1, filesize, handle);
		fclose(handle);

		if (read != filesize) return;

		this->text[filesize] = '\0';

		/* Replace tabs and line feeds with a space since str_validate removes those. */
		for (char *p = this->text; *p != '\0'; p++) {
			if (*p == '\t' || *p == '\r') *p = ' ';
		}

		/* Check for the byte-order-mark, and skip it if needed. */
		char *p = this->text + (strncmp("\xEF\xBB\xBF", this->text, 3) == 0 ? 3 : 0);

		/* Make sure the string is a valid UTF-8 sequence. */
		str_validate(p, this->text + filesize, SVS_REPLACE_WITH_QUESTION_MARK | SVS_ALLOW_NEWLINE);

		/* Split the string on newlines. */
		*this->lines.Append() = p;
		for (; *p != '\0'; p++) {
			if (*p == '\n') {
				*p = '\0';
				*this->lines.Append() = p + 1;
			}
		}

		CheckForMissingGlyphs(true, this);

		/* Initialize scrollbars */
		this->vscroll->SetCount(this->lines.Length());

		this->max_length = 0;
		for (uint i = 0; i < this->lines.Length(); i++) {
			this->max_length = max(this->max_length, GetStringBoundingBox(this->lines[i], FS_MONO).width);
		}
		this->hscroll->SetCount(this->max_length + WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT);
		this->hscroll->SetStepSize(10); // Speed up horizontal scrollbar
	}
};

static const NWidgetPart _nested_newgrf_textfile_widgets[] = {
	NWidget(NWID_HORIZONTAL),
		NWidget(WWT_CLOSEBOX, COLOUR_MAUVE),
		NWidget(WWT_CAPTION, COLOUR_MAUVE, WID_NT_CAPTION), SetDataTip(STR_NULL, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
	EndContainer(),
	NWidget(NWID_HORIZONTAL),
		NWidget(WWT_PANEL, COLOUR_MAUVE, WID_NT_BACKGROUND), SetMinimalSize(200, 125), SetResize(1, 12), SetScrollbar(WID_NT_VSCROLLBAR),
		EndContainer(),
		NWidget(NWID_VERTICAL),
			NWidget(NWID_VSCROLLBAR, COLOUR_MAUVE, WID_NT_VSCROLLBAR),
		EndContainer(),
	EndContainer(),
	NWidget(NWID_HORIZONTAL),
		NWidget(NWID_HSCROLLBAR, COLOUR_MAUVE, WID_NT_HSCROLLBAR),
		NWidget(WWT_RESIZEBOX, COLOUR_MAUVE),
	EndContainer(),
};

/** Window definition for the grf textfile window */
static const WindowDesc _newgrf_textfile_desc(
	WDP_CENTER, 630, 460,
	WC_NEWGRF_TEXTFILE, WC_NONE,
	WDF_UNCLICK_BUTTONS,
	_nested_newgrf_textfile_widgets, lengthof(_nested_newgrf_textfile_widgets)
);

void ShowNewGRFTextfileWindow(const GRFConfig *c, TextfileType file_type)
{
	DeleteWindowByClass(WC_NEWGRF_TEXTFILE);
	new NewGRFTextfileWindow(&_newgrf_textfile_desc, c, file_type);
}

static GRFPresetList _grf_preset_list;

class DropDownListPresetItem : public DropDownListItem {
public:
	DropDownListPresetItem(int result) : DropDownListItem(result, false) {}

	virtual ~DropDownListPresetItem() {}

	bool Selectable() const
	{
		return true;
	}

	void Draw(int left, int right, int top, int bottom, bool sel, int bg_colour) const
	{
		DrawString(left + 2, right + 2, top, _grf_preset_list[this->result], sel ? TC_WHITE : TC_BLACK);
	}
};

static void NewGRFConfirmationCallback(Window *w, bool confirmed);

/**
 * Window for showing NewGRF files
 */
struct NewGRFWindow : public QueryStringBaseWindow, NewGRFScanCallback {
	typedef GUIList<const GRFConfig *> GUIGRFConfigList;

	static const uint EDITBOX_MAX_SIZE   =  50;

	static Listing   last_sorting;   ///< Default sorting of #GUIGRFConfigList.
	static Filtering last_filtering; ///< Default filtering of #GUIGRFConfigList.
	static GUIGRFConfigList::SortFunction   * const sorter_funcs[]; ///< Sort functions of the #GUIGRFConfigList.
	static GUIGRFConfigList::FilterFunction * const filter_funcs[]; ///< Filter functions of the #GUIGRFConfigList.

	GUIGRFConfigList avails;    ///< Available (non-active) grfs.
	const GRFConfig *avail_sel; ///< Currently selected available grf. \c NULL is none is selected.
	int avail_pos;              ///< Index of #avail_sel if existing, else \c -1.

	GRFConfig *actives;         ///< Temporary active grf list to which changes are made.
	GRFConfig *active_sel;      ///< Selected active grf item.

	GRFConfig **orig_list;      ///< List active grfs in the game. Used as initial value, may be updated by the window.
	bool editable;              ///< Is the window editable?
	bool show_params;           ///< Are the grf-parameters shown in the info-panel?
	bool execute;               ///< On pressing 'apply changes' are grf changes applied immediately, or only list is updated.
	int preset;                 ///< Selected preset.

	Scrollbar *vscroll;
	Scrollbar *vscroll2;

	NewGRFWindow(const WindowDesc *desc, bool editable, bool show_params, bool execute, GRFConfig **orig_list) : QueryStringBaseWindow(EDITBOX_MAX_SIZE)
	{
		this->avail_sel   = NULL;
		this->avail_pos   = -1;
		this->active_sel  = NULL;
		this->actives     = NULL;
		this->orig_list   = orig_list;
		this->editable    = editable;
		this->execute     = execute;
		this->show_params = show_params;
		this->preset      = -1;

		CopyGRFConfigList(&this->actives, *orig_list, false);
		GetGRFPresetList(&_grf_preset_list);

		this->CreateNestedTree(desc);
		this->vscroll = this->GetScrollbar(WID_NS_SCROLLBAR);
		this->vscroll2 = this->GetScrollbar(WID_NS_SCROLL2BAR);

		this->GetWidget<NWidgetStacked>(WID_NS_SHOW_REMOVE)->SetDisplayedPlane(this->editable ? 0 : 1);
		this->GetWidget<NWidgetStacked>(WID_NS_SHOW_APPLY)->SetDisplayedPlane(this->editable ? 0 : SZSP_HORIZONTAL);
		this->FinishInitNested(desc, WN_GAME_OPTIONS_NEWGRF_STATE);

		InitializeTextBuffer(&this->text, this->edit_str_buf, this->edit_str_size);
		this->SetFocusedWidget(WID_NS_FILTER);

		this->avails.SetListing(this->last_sorting);
		this->avails.SetFiltering(this->last_filtering);
		this->avails.SetSortFuncs(this->sorter_funcs);
		this->avails.SetFilterFuncs(this->filter_funcs);
		this->avails.ForceRebuild();

		this->OnInvalidateData(GOID_NEWGRF_LIST_EDITED);
	}

	~NewGRFWindow()
	{
		DeleteWindowByClass(WC_GRF_PARAMETERS);
		DeleteWindowByClass(WC_NEWGRF_TEXTFILE);

		if (this->editable && !this->execute) {
			CopyGRFConfigList(this->orig_list, this->actives, true);
			ResetGRFConfig(false);
			ReloadNewGRFData();
		}

		/* Remove the temporary copy of grf-list used in window */
		ClearGRFConfigList(&this->actives);
		_grf_preset_list.Clear();
	}

	virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
	{
		switch (widget) {
			case WID_NS_FILE_LIST:
			{
				Dimension d = maxdim(GetSpriteSize(SPR_SQUARE), GetSpriteSize(SPR_WARNING_SIGN));
				resize->height = max(d.height + 2U, FONT_HEIGHT_NORMAL + 2U);
				size->height = max(size->height, WD_FRAMERECT_TOP + 6 * resize->height + WD_FRAMERECT_BOTTOM);
				break;
			}

			case WID_NS_AVAIL_LIST:
				resize->height = max(12, FONT_HEIGHT_NORMAL + 2);
				size->height = max(size->height, WD_FRAMERECT_TOP + 8 * resize->height + WD_FRAMERECT_BOTTOM);
				break;

			case WID_NS_NEWGRF_INFO_TITLE: {
				Dimension dim = GetStringBoundingBox(STR_NEWGRF_SETTINGS_INFO_TITLE);
				size->height = max(size->height, dim.height + WD_FRAMETEXT_TOP + WD_FRAMETEXT_BOTTOM);
				size->width  = max(size->width,  dim.width  + WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT);
				break;
			}

			case WID_NS_NEWGRF_INFO:
				size->height = max(size->height, WD_FRAMERECT_TOP + 10 * FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM + padding.height + 2);
				break;

			case WID_NS_PRESET_LIST: {
				Dimension d = GetStringBoundingBox(STR_NUM_CUSTOM);
				for (uint i = 0; i < _grf_preset_list.Length(); i++) {
					if (_grf_preset_list[i] != NULL) {
						SetDParamStr(0, _grf_preset_list[i]);
						d = maxdim(d, GetStringBoundingBox(STR_JUST_RAW_STRING));
					}
				}
				d.width += padding.width;
				*size = maxdim(d, *size);
				break;
			}

			case WID_NS_CONTENT_DOWNLOAD:
			case WID_NS_CONTENT_DOWNLOAD2: {
				Dimension d = GetStringBoundingBox(STR_NEWGRF_SETTINGS_FIND_MISSING_CONTENT_BUTTON);
				*size = maxdim(d, GetStringBoundingBox(STR_INTRO_ONLINE_CONTENT));
				size->width  += padding.width;
				size->height += padding.height;
				break;
			}
		}
	}

	virtual void OnResize()
	{
		this->vscroll->SetCapacityFromWidget(this, WID_NS_FILE_LIST);
		this->vscroll2->SetCapacityFromWidget(this, WID_NS_AVAIL_LIST);
	}

	virtual void SetStringParameters(int widget) const
	{
		switch (widget) {
			case WID_NS_PRESET_LIST:
				if (this->preset == -1) {
					SetDParam(0, STR_NUM_CUSTOM);
				} else {
					SetDParam(0, STR_JUST_RAW_STRING);
					SetDParamStr(1, _grf_preset_list[this->preset]);
				}
				break;
		}
	}

	virtual void OnPaint()
	{
		this->DrawWidgets();
		if (this->editable) this->DrawEditBox(WID_NS_FILTER);
	}

	/**
	 * Pick the palette for the sprite of the grf to display.
	 * @param c grf to display.
	 * @return Palette for the sprite.
	 */
	FORCEINLINE PaletteID GetPalette(const GRFConfig *c) const
	{
		PaletteID pal;

		/* Pick a colour */
		switch (c->status) {
			case GCS_NOT_FOUND:
			case GCS_DISABLED:
				pal = PALETTE_TO_RED;
				break;
			case GCS_ACTIVATED:
				pal = PALETTE_TO_GREEN;
				break;
			default:
				pal = PALETTE_TO_BLUE;
				break;
		}

		/* Do not show a "not-failure" colour when it actually failed to load */
		if (pal != PALETTE_TO_RED) {
			if (HasBit(c->flags, GCF_STATIC)) {
				pal = PALETTE_TO_GREY;
			} else if (HasBit(c->flags, GCF_COMPATIBLE)) {
				pal = PALETTE_TO_ORANGE;
			}
		}

		return pal;
	}

	virtual void DrawWidget(const Rect &r, int widget) const
	{
		switch (widget) {
			case WID_NS_FILE_LIST: {
				GfxFillRect(r.left + 1, r.top + 1, r.right - 1, r.bottom - 1, PC_BLACK);

				uint step_height = this->GetWidget<NWidgetBase>(WID_NS_FILE_LIST)->resize_y;
				uint y = r.top + WD_FRAMERECT_TOP;
				Dimension square = GetSpriteSize(SPR_SQUARE);
				Dimension warning = GetSpriteSize(SPR_WARNING_SIGN);
				int square_offset_y = (step_height - square.height) / 2;
				int warning_offset_y = (step_height - warning.height) / 2;
				int offset_y = (step_height - FONT_HEIGHT_NORMAL) / 2;

				bool rtl = _current_text_dir == TD_RTL;
				uint text_left    = rtl ? r.left + WD_FRAMERECT_LEFT : r.left + square.width + 15;
				uint text_right   = rtl ? r.right - square.width - 15 : r.right - WD_FRAMERECT_RIGHT;
				uint square_left  = rtl ? r.right - square.width - 5 : r.left + 5;
				uint warning_left = rtl ? r.right - square.width - warning.width - 10 : r.left + square.width + 10;

				int i = 0;
				for (const GRFConfig *c = this->actives; c != NULL; c = c->next, i++) {
					if (this->vscroll->IsVisible(i)) {
						const char *text = c->GetName();
						bool h = (this->active_sel == c);
						PaletteID pal = this->GetPalette(c);

						if (h) GfxFillRect(r.left + 1, y, r.right - 1, y + step_height - 1, PC_DARK_BLUE);
						DrawSprite(SPR_SQUARE, pal, square_left, y + square_offset_y);
						if (c->error != NULL) DrawSprite(SPR_WARNING_SIGN, 0, warning_left, y + warning_offset_y);
						uint txtoffset = c->error == NULL ? 0 : warning.width;
						DrawString(text_left + (rtl ? 0 : txtoffset), text_right - (rtl ? txtoffset : 0), y + offset_y, text, h ? TC_WHITE : TC_ORANGE);
						y += step_height;
					}
				}
				break;
			}

			case WID_NS_AVAIL_LIST: {
				GfxFillRect(r.left + 1, r.top + 1, r.right - 1, r.bottom - 1, PC_BLACK);

				uint step_height = this->GetWidget<NWidgetBase>(WID_NS_AVAIL_LIST)->resize_y;
				int offset_y = (step_height - FONT_HEIGHT_NORMAL) / 2;
				uint y = r.top + WD_FRAMERECT_TOP;
				uint min_index = this->vscroll2->GetPosition();
				uint max_index = min(min_index + this->vscroll2->GetCapacity(), this->avails.Length());

				for (uint i = min_index; i < max_index; i++) {
					const GRFConfig *c = this->avails[i];
					bool h = (c == this->avail_sel);
					const char *text = c->GetName();

					if (h) GfxFillRect(r.left + 1, y, r.right - 1, y + step_height - 1, PC_DARK_BLUE);
					DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y + offset_y, text, h ? TC_WHITE : TC_SILVER);
					y += step_height;
				}
				break;
			}

			case WID_NS_NEWGRF_INFO_TITLE:
				/* Create the nice grayish rectangle at the details top. */
				GfxFillRect(r.left + 1, r.top + 1, r.right - 1, r.bottom - 1, PC_DARK_BLUE);
				DrawString(r.left, r.right, (r.top + r.bottom - FONT_HEIGHT_NORMAL) / 2, STR_NEWGRF_SETTINGS_INFO_TITLE, TC_FROMSTRING, SA_HOR_CENTER);
				break;

			case WID_NS_NEWGRF_INFO: {
				const GRFConfig *selected = this->active_sel;
				if (selected == NULL) selected = this->avail_sel;
				if (selected != NULL) {
					ShowNewGRFInfo(selected, r.left + WD_FRAMERECT_LEFT, r.top + WD_FRAMERECT_TOP, r.right - WD_FRAMERECT_RIGHT, r.bottom - WD_FRAMERECT_BOTTOM, this->show_params);
				}
				break;
			}
		}
	}

	virtual void OnClick(Point pt, int widget, int click_count)
	{
		if (widget >= WID_NS_NEWGRF_TEXTFILE && widget < WID_NS_NEWGRF_TEXTFILE + TFT_END) {
			if (this->active_sel == NULL && this->avail_sel == NULL) return;

			ShowNewGRFTextfileWindow(this->active_sel != NULL ? this->active_sel : this->avail_sel, (TextfileType)(widget - WID_NS_NEWGRF_TEXTFILE));
			return;
		}

		switch (widget) {
			case WID_NS_PRESET_LIST: {
				DropDownList *list = new DropDownList();

				/* Add 'None' option for clearing list */
				list->push_back(new DropDownListStringItem(STR_NONE, -1, false));

				for (uint i = 0; i < _grf_preset_list.Length(); i++) {
					if (_grf_preset_list[i] != NULL) {
						list->push_back(new DropDownListPresetItem(i));
					}
				}

				this->DeleteChildWindows(WC_QUERY_STRING); // Remove the parameter query window
				ShowDropDownList(this, list, this->preset, WID_NS_PRESET_LIST);
				break;
			}

			case WID_NS_OPEN_URL: {
				const GRFConfig *c = (this->avail_sel == NULL) ? this->active_sel : this->avail_sel;

				extern void OpenBrowser(const char *url);
				OpenBrowser(c->GetURL());
				break;
			}

			case WID_NS_PRESET_SAVE:
				ShowQueryString(STR_EMPTY, STR_NEWGRF_SETTINGS_PRESET_SAVE_QUERY, 32, this, CS_ALPHANUMERAL, QSF_NONE);
				break;

			case WID_NS_PRESET_DELETE:
				if (this->preset == -1) return;

				DeleteGRFPresetFromConfig(_grf_preset_list[this->preset]);
				GetGRFPresetList(&_grf_preset_list);
				this->preset = -1;
				this->InvalidateData();
				this->DeleteChildWindows(WC_QUERY_STRING); // Remove the parameter query window
				break;

			case WID_NS_MOVE_UP: { // Move GRF up
				if (this->active_sel == NULL || !this->editable) break;

				int pos = 0;
				for (GRFConfig **pc = &this->actives; *pc != NULL; pc = &(*pc)->next, pos++) {
					GRFConfig *c = *pc;
					if (c->next == this->active_sel) {
						c->next = this->active_sel->next;
						this->active_sel->next = c;
						*pc = this->active_sel;
						break;
					}
				}
				this->vscroll->ScrollTowards(pos);
				this->preset = -1;
				this->InvalidateData();
				break;
			}

			case WID_NS_MOVE_DOWN: { // Move GRF down
				if (this->active_sel == NULL || !this->editable) break;

				int pos = 1; // Start at 1 as we swap the selected newgrf with the next one
				for (GRFConfig **pc = &this->actives; *pc != NULL; pc = &(*pc)->next, pos++) {
					GRFConfig *c = *pc;
					if (c == this->active_sel) {
						*pc = c->next;
						c->next = c->next->next;
						(*pc)->next = c;
						break;
					}
				}
				this->vscroll->ScrollTowards(pos);
				this->preset = -1;
				this->InvalidateData();
				break;
			}

			case WID_NS_FILE_LIST: { // Select an active GRF.
				uint i = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NS_FILE_LIST);

				GRFConfig *c;
				for (c = this->actives; c != NULL && i > 0; c = c->next, i--) {}

				if (this->active_sel != c) DeleteWindowByClass(WC_GRF_PARAMETERS);
				this->active_sel = c;
				this->avail_sel = NULL;
				this->avail_pos = -1;

				this->InvalidateData();
				if (click_count == 1) break;
				/* FALL THROUGH, with double click. */
			}

			case WID_NS_REMOVE: { // Remove GRF
				if (this->active_sel == NULL || !this->editable) break;
				DeleteWindowByClass(WC_GRF_PARAMETERS);

				/* Choose the next GRF file to be the selected file. */
				GRFConfig *newsel = this->active_sel->next;
				for (GRFConfig **pc = &this->actives; *pc != NULL; pc = &(*pc)->next) {
					GRFConfig *c = *pc;
					/* If the new selection is empty (i.e. we're deleting the last item
					 * in the list, pick the file just before the selected file */
					if (newsel == NULL && c->next == this->active_sel) newsel = c;

					if (c == this->active_sel) {
						*pc = c->next;
						delete c;
						break;
					}
				}

				this->active_sel = newsel;
				this->preset = -1;
				this->avail_pos = -1;
				this->avail_sel = NULL;
				this->avails.ForceRebuild();
				this->InvalidateData(GOID_NEWGRF_LIST_EDITED);
				break;
			}

			case WID_NS_AVAIL_LIST: { // Select a non-active GRF.
				uint i = this->vscroll2->GetScrolledRowFromWidget(pt.y, this, WID_NS_AVAIL_LIST);
				this->active_sel = NULL;
				DeleteWindowByClass(WC_GRF_PARAMETERS);
				if (i < this->avails.Length()) {
					this->avail_sel = this->avails[i];
					this->avail_pos = i;
				}
				this->InvalidateData();
				if (click_count == 1) break;
				/* FALL THROUGH, with double click. */
			}

			case WID_NS_ADD: {
				if (this->avail_sel == NULL || !this->editable || HasBit(this->avail_sel->flags, GCF_INVALID)) break;

				GRFConfig **list;
				/* Find last entry in the list, checking for duplicate grfid on the way */
				for (list = &this->actives; *list != NULL; list = &(*list)->next) {
					if ((*list)->ident.grfid == this->avail_sel->ident.grfid) {
						ShowErrorMessage(STR_NEWGRF_DUPLICATE_GRFID, INVALID_STRING_ID, WL_INFO);
						return;
					}
				}

				GRFConfig *c = new GRFConfig(*this->avail_sel); // Copy GRF details from scanned list.
				c->SetParameterDefaults();
				*list = c; // Append GRF config to configuration list.

				/* Select next (or previous, if last one) item in the list. */
				int new_pos = this->avail_pos + 1;
				if (new_pos >= (int)this->avails.Length()) new_pos = this->avail_pos - 1;
				this->avail_pos = new_pos;
				if (new_pos >= 0) this->avail_sel = this->avails[new_pos];

				this->avails.ForceRebuild();
				this->InvalidateData(GOID_NEWGRF_LIST_EDITED);
				break;
			}

			case WID_NS_APPLY_CHANGES: // Apply changes made to GRF list
				if (!this->editable) break;
				if (this->execute) {
					ShowQuery(
						STR_NEWGRF_POPUP_CAUTION_CAPTION,
						STR_NEWGRF_CONFIRMATION_TEXT,
						this,
						NewGRFConfirmationCallback
					);
				} else {
					CopyGRFConfigList(this->orig_list, this->actives, true);
					ResetGRFConfig(false);
					ReloadNewGRFData();
				}
				this->DeleteChildWindows(WC_QUERY_STRING); // Remove the parameter query window
				break;

			case WID_NS_SET_PARAMETERS: { // Edit parameters
				if (this->active_sel == NULL || !this->editable || !this->show_params || this->active_sel->num_valid_params == 0) break;

				OpenGRFParameterWindow(this->active_sel);
				break;
			}

			case WID_NS_TOGGLE_PALETTE:
				if (this->active_sel != NULL || !this->editable) {
					this->active_sel->palette ^= GRFP_USE_MASK;
					this->SetDirty();
				}
				break;

			case WID_NS_CONTENT_DOWNLOAD:
			case WID_NS_CONTENT_DOWNLOAD2:
				if (!_network_available) {
					ShowErrorMessage(STR_NETWORK_ERROR_NOTAVAILABLE, INVALID_STRING_ID, WL_ERROR);
				} else {
#if defined(ENABLE_NETWORK)
					this->DeleteChildWindows(WC_QUERY_STRING); // Remove the parameter query window

					ShowMissingContentWindow(this->actives);
#endif
				}
				break;

			case WID_NS_RESCAN_FILES:
			case WID_NS_RESCAN_FILES2:
				ScanNewGRFFiles(this);
				break;
		}
	}

	virtual void OnNewGRFsScanned()
	{
		this->avail_sel = NULL;
		this->avail_pos = -1;
		this->avails.ForceRebuild();
		this->DeleteChildWindows(WC_QUERY_STRING);  // Remove the parameter query window
		this->DeleteChildWindows(WC_NEWGRF_TEXTFILE); // Remove the view textfile window
	}

	virtual void OnDropdownSelect(int widget, int index)
	{
		if (!this->editable) return;

		ClearGRFConfigList(&this->actives);
		this->preset = index;

		if (index != -1) {
			this->actives = LoadGRFPresetFromConfig(_grf_preset_list[index]);
		}
		this->avails.ForceRebuild();

		DeleteWindowByClass(WC_GRF_PARAMETERS);
		this->active_sel = NULL;
		this->InvalidateData(GOID_NEWGRF_PRESET_LOADED);
	}

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

		SaveGRFPresetToConfig(str, this->actives);
		GetGRFPresetList(&_grf_preset_list);

		/* Switch to this preset */
		for (uint i = 0; i < _grf_preset_list.Length(); i++) {
			if (_grf_preset_list[i] != NULL && strcmp(_grf_preset_list[i], str) == 0) {
				this->preset = i;
				break;
			}
		}

		this->InvalidateData();
	}

	/**
	 * Some data on this window has become invalid.
	 * @param data Information about the changed data. @see GameOptionsInvalidationData
	 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
	 */
	virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
	{
		if (!gui_scope) return;
		switch (data) {
			default:
				/* Nothing important to do */
				break;

			case GOID_NEWGRF_RESCANNED:
				/* Search the list for items that are now found and mark them as such. */
				for (GRFConfig **l = &this->actives; *l != NULL; l = &(*l)->next) {
					GRFConfig *c = *l;
					bool compatible = HasBit(c->flags, GCF_COMPATIBLE);
					if (c->status != GCS_NOT_FOUND && !compatible) continue;

					const GRFConfig *f = FindGRFConfig(c->ident.grfid, FGCM_EXACT, compatible ? c->original_md5sum : c->ident.md5sum);
					if (f == NULL || HasBit(f->flags, GCF_INVALID)) continue;

					*l = new GRFConfig(*f);
					(*l)->next = c->next;

					if (active_sel == c) active_sel = *l;

					delete c;
				}

				this->avails.ForceRebuild();
				/* FALL THROUGH */
			case GOID_NEWGRF_LIST_EDITED:
				this->preset = -1;
				/* FALL THROUGH */
			case GOID_NEWGRF_PRESET_LOADED: {
				/* Update scrollbars */
				int i = 0;
				for (const GRFConfig *c = this->actives; c != NULL; c = c->next, i++) {}

				this->vscroll->SetCapacityFromWidget(this, WID_NS_FILE_LIST);
				this->vscroll->SetCount(i);

				this->vscroll2->SetCapacityFromWidget(this, WID_NS_AVAIL_LIST);
				if (this->avail_pos >= 0) this->vscroll2->ScrollTowards(this->avail_pos);
				break;
			}
		}

		this->BuildAvailables();

		this->SetWidgetsDisabledState(!this->editable,
			WID_NS_PRESET_LIST,
			WID_NS_APPLY_CHANGES,
			WID_NS_TOGGLE_PALETTE,
			WIDGET_LIST_END
		);
		this->SetWidgetDisabledState(WID_NS_ADD, !this->editable || this->avail_sel == NULL || HasBit(this->avail_sel->flags, GCF_INVALID));

		bool disable_all = this->active_sel == NULL || !this->editable;
		this->SetWidgetsDisabledState(disable_all,
			WID_NS_REMOVE,
			WID_NS_MOVE_UP,
			WID_NS_MOVE_DOWN,
			WIDGET_LIST_END
		);

		const GRFConfig *c = (this->avail_sel == NULL) ? this->active_sel : this->avail_sel;
		for (TextfileType tft = TFT_BEGIN; tft < TFT_END; tft++) {
			this->SetWidgetDisabledState(WID_NS_NEWGRF_TEXTFILE + tft, c == NULL || c->GetTextfile(tft) == NULL);
		}
		this->SetWidgetDisabledState(WID_NS_OPEN_URL, c == NULL || StrEmpty(c->GetURL()));

		this->SetWidgetDisabledState(WID_NS_SET_PARAMETERS, !this->show_params || disable_all || this->active_sel->num_valid_params == 0);
		this->SetWidgetDisabledState(WID_NS_TOGGLE_PALETTE, disable_all);

		if (!disable_all) {
			/* All widgets are now enabled, so disable widgets we can't use */
			if (this->active_sel == this->actives)    this->DisableWidget(WID_NS_MOVE_UP);
			if (this->active_sel->next == NULL)       this->DisableWidget(WID_NS_MOVE_DOWN);
			if (this->active_sel->IsOpenTTDBaseGRF()) this->DisableWidget(WID_NS_REMOVE);
		}

		this->SetWidgetDisabledState(WID_NS_PRESET_DELETE, this->preset == -1);

		bool has_missing = false;
		bool has_compatible = false;
		for (const GRFConfig *c = this->actives; !has_missing && c != NULL; c = c->next) {
			has_missing    |= c->status == GCS_NOT_FOUND;
			has_compatible |= HasBit(c->flags, GCF_COMPATIBLE);
		}
		uint16 widget_data;
		StringID tool_tip;
		if (has_missing || has_compatible) {
			widget_data = STR_NEWGRF_SETTINGS_FIND_MISSING_CONTENT_BUTTON;
			tool_tip    = STR_NEWGRF_SETTINGS_FIND_MISSING_CONTENT_TOOLTIP;
		} else {
			widget_data = STR_INTRO_ONLINE_CONTENT;
			tool_tip    = STR_INTRO_TOOLTIP_ONLINE_CONTENT;
		}
		this->GetWidget<NWidgetCore>(WID_NS_CONTENT_DOWNLOAD)->widget_data  = widget_data;
		this->GetWidget<NWidgetCore>(WID_NS_CONTENT_DOWNLOAD)->tool_tip     = tool_tip;
		this->GetWidget<NWidgetCore>(WID_NS_CONTENT_DOWNLOAD2)->widget_data = widget_data;
		this->GetWidget<NWidgetCore>(WID_NS_CONTENT_DOWNLOAD2)->tool_tip    = tool_tip;

		this->SetWidgetDisabledState(WID_NS_PRESET_SAVE, has_missing);
	}

	virtual void OnMouseLoop()
	{
		if (this->editable) this->HandleEditBox(WID_NS_FILTER);
	}

	virtual EventState OnKeyPress(uint16 key, uint16 keycode)
	{
		if (!this->editable) return ES_NOT_HANDLED;

		switch (keycode) {
			case WKC_UP:
				/* scroll up by one */
				if (this->avail_pos > 0) this->avail_pos--;
				break;

			case WKC_DOWN:
				/* scroll down by one */
				if (this->avail_pos < (int)this->avails.Length() - 1) this->avail_pos++;
				break;

			case WKC_PAGEUP:
				/* scroll up a page */
				this->avail_pos = (this->avail_pos < this->vscroll2->GetCapacity()) ? 0 : this->avail_pos - this->vscroll2->GetCapacity();
				break;

			case WKC_PAGEDOWN:
				/* scroll down a page */
				this->avail_pos = min(this->avail_pos + this->vscroll2->GetCapacity(), (int)this->avails.Length() - 1);
				break;

			case WKC_HOME:
				/* jump to beginning */
				this->avail_pos = 0;
				break;

			case WKC_END:
				/* jump to end */
				this->avail_pos = this->avails.Length() - 1;
				break;

			default: {
				/* Handle editbox input */
				EventState state = ES_NOT_HANDLED;
				if (this->HandleEditBoxKey(WID_NS_FILTER, key, keycode, state) == HEBR_EDITING) {
					this->OnOSKInput(WID_NS_FILTER);
				}
				return state;
			}
		}

		if (this->avails.Length() == 0) this->avail_pos = -1;
		if (this->avail_pos >= 0) {
			this->avail_sel = this->avails[this->avail_pos];
			this->vscroll2->ScrollTowards(this->avail_pos);
			this->InvalidateData(0);
		}

		return ES_HANDLED;
	}

	virtual void OnOSKInput(int wid)
	{
		if (!this->editable) return;

		this->avails.SetFilterState(!StrEmpty(this->edit_str_buf));
		this->avails.ForceRebuild();
		this->InvalidateData(0);
	}

private:
	/** Sort grfs by name. */
	static int CDECL NameSorter(const GRFConfig * const *a, const GRFConfig * const *b)
	{
		int i = strnatcmp((*a)->GetName(), (*b)->GetName()); // Sort by name (natural sorting).
		if (i != 0) return i;

		i = (*a)->version - (*b)->version;
		if (i != 0) return i;

		return memcmp((*a)->ident.md5sum, (*b)->ident.md5sum, lengthof((*b)->ident.md5sum));
	}

	/** Filter grfs by tags/name */
	static bool CDECL TagNameFilter(const GRFConfig * const *a, const char *filter_string)
	{
		if (strcasestr((*a)->GetName(), filter_string) != NULL) return true;
		if ((*a)->filename != NULL && strcasestr((*a)->filename, filter_string) != NULL) return true;
		if ((*a)->GetDescription() != NULL && strcasestr((*a)->GetDescription(), filter_string) != NULL) return true;
		return false;
	}

	void BuildAvailables()
	{
		if (!this->avails.NeedRebuild()) return;

		this->avails.Clear();

		for (const GRFConfig *c = _all_grfs; c != NULL; c = c->next) {
			bool found = false;
			for (const GRFConfig *grf = this->actives; grf != NULL && !found; grf = grf->next) found = grf->ident.HasGrfIdentifier(c->ident.grfid, c->ident.md5sum);
			if (found) continue;

			if (_settings_client.gui.newgrf_show_old_versions) {
				*this->avails.Append() = c;
			} else {
				const GRFConfig *best = FindGRFConfig(c->ident.grfid, HasBit(c->flags, GCF_INVALID) ? FGCM_NEWEST : FGCM_NEWEST_VALID);
				/*
				 * If the best version is 0, then all NewGRF with this GRF ID
				 * have version 0, so for backward compatability reasons we
				 * want to show them all.
				 * If we are the best version, then we definitely want to
				 * show that NewGRF!.
				 */
				if (best->version == 0 || best->ident.HasGrfIdentifier(c->ident.grfid, c->ident.md5sum)) {
					*this->avails.Append() = c;
				}
			}
		}

		this->avails.Filter(this->edit_str_buf);
		this->avails.Compact();
		this->avails.RebuildDone();
		this->avails.Sort();

		if (this->avail_sel != NULL) {
			this->avail_pos = this->avails.FindIndex(this->avail_sel);
			if (this->avail_pos < 0) this->avail_sel = NULL;
		}

		this->vscroll2->SetCount(this->avails.Length()); // Update the scrollbar
	}
};

#if defined(ENABLE_NETWORK)
/**
 * Show the content list window with all missing grfs from the given list.
 * @param list The list of grfs to check for missings / not exactly matching ones.
 */
void ShowMissingContentWindow(const GRFConfig *list)
{
	/* Only show the things in the current list, or everything when nothing's selected */
	ContentVector cv;
	for (const GRFConfig *c = list; c != NULL; c = c->next) {
		if (c->status != GCS_NOT_FOUND && !HasBit(c->flags, GCF_COMPATIBLE)) continue;

		ContentInfo *ci = new ContentInfo();
		ci->type = CONTENT_TYPE_NEWGRF;
		ci->state = ContentInfo::DOES_NOT_EXIST;
		ttd_strlcpy(ci->name, c->GetName(), lengthof(ci->name));
		ci->unique_id = BSWAP32(c->ident.grfid);
		memcpy(ci->md5sum, HasBit(c->flags, GCF_COMPATIBLE) ? c->original_md5sum : c->ident.md5sum, sizeof(ci->md5sum));
		*cv.Append() = ci;
	}
	ShowNetworkContentListWindow(cv.Length() == 0 ? NULL : &cv, CONTENT_TYPE_NEWGRF);
}
#endif

Listing NewGRFWindow::last_sorting     = {false, 0};
Filtering NewGRFWindow::last_filtering = {false, 0};

NewGRFWindow::GUIGRFConfigList::SortFunction * const NewGRFWindow::sorter_funcs[] = {
	&NameSorter,
};

NewGRFWindow::GUIGRFConfigList::FilterFunction * const NewGRFWindow::filter_funcs[] = {
	&TagNameFilter,
};

/**
 * Custom nested widget container for the NewGRF gui.
 * Depending on the space in the gui, it uses either
 * - two column mode, put the #acs and the #avs underneath each other and the #info next to it, or
 * - three column mode, put the #avs, #acs, and #info each in its own column.
 */
class NWidgetNewGRFDisplay : public NWidgetContainer {
public:
	static const uint INTER_LIST_SPACING;      ///< Empty vertical space between both lists in the 2 column mode.
	static const uint INTER_COLUMN_SPACING;    ///< Empty horizontal space between two columns.
	static const uint MAX_EXTRA_INFO_WIDTH;    ///< Maximal additional width given to the panel.
	static const uint MIN_EXTRA_FOR_3_COLUMNS; ///< Minimal additional width needed before switching to 3 columns.

	NWidgetBase *avs; ///< Widget with the available grfs list and buttons.
	NWidgetBase *acs; ///< Widget with the active grfs list and buttons.
	NWidgetBase *inf; ///< Info panel.
	bool editable;    ///< Editable status of the parent NewGRF window (if \c false, drop all widgets that make the window editable).

	NWidgetNewGRFDisplay(NWidgetBase *avs, NWidgetBase *acs, NWidgetBase *inf) : NWidgetContainer(NWID_HORIZONTAL)
	{
		this->avs = avs;
		this->acs = acs;
		this->inf = inf;

		this->Add(this->avs);
		this->Add(this->acs);
		this->Add(this->inf);

		this->editable = true; // Temporary setting, 'real' value is set in SetupSmallestSize().
	}

	virtual void SetupSmallestSize(Window *w, bool init_array)
	{
		/* Copy state flag from the window. */
		assert(dynamic_cast<NewGRFWindow *>(w) != NULL);
		NewGRFWindow *ngw = (NewGRFWindow *)w;
		this->editable = ngw->editable;

		this->avs->SetupSmallestSize(w, init_array);
		this->acs->SetupSmallestSize(w, init_array);
		this->inf->SetupSmallestSize(w, init_array);

		uint min_avs_width = this->avs->smallest_x + this->avs->padding_left + this->avs->padding_right;
		uint min_acs_width = this->acs->smallest_x + this->acs->padding_left + this->acs->padding_right;
		uint min_inf_width = this->inf->smallest_x + this->inf->padding_left + this->inf->padding_right;

		uint min_avs_height = this->avs->smallest_y + this->avs->padding_top + this->avs->padding_bottom;
		uint min_acs_height = this->acs->smallest_y + this->acs->padding_top + this->acs->padding_bottom;
		uint min_inf_height = this->inf->smallest_y + this->inf->padding_top + this->inf->padding_bottom;

		/* Smallest window is in two column mode. */
		this->smallest_x = max(min_avs_width, min_acs_width) + INTER_COLUMN_SPACING + min_inf_width;
		this->smallest_y = max(min_inf_height, min_acs_height + INTER_LIST_SPACING + min_avs_height);

		/* Filling. */
		this->fill_x = LeastCommonMultiple(this->avs->fill_x, this->acs->fill_x);
		if (this->inf->fill_x > 0 && (this->fill_x == 0 || this->fill_x > this->inf->fill_x)) this->fill_x = this->inf->fill_x;

		this->fill_y = this->avs->fill_y;
		if (this->acs->fill_y > 0 && (this->fill_y == 0 || this->fill_y > this->acs->fill_y)) this->fill_y = this->acs->fill_y;
		this->fill_y = LeastCommonMultiple(this->fill_y, this->inf->fill_y);

		/* Resizing. */
		this->resize_x = LeastCommonMultiple(this->avs->resize_x, this->acs->resize_x);
		if (this->inf->resize_x > 0 && (this->resize_x == 0 || this->resize_x > this->inf->resize_x)) this->resize_x = this->inf->resize_x;

		this->resize_y = this->avs->resize_y;
		if (this->acs->resize_y > 0 && (this->resize_y == 0 || this->resize_y > this->acs->resize_y)) this->resize_y = this->acs->resize_y;
		this->resize_y = LeastCommonMultiple(this->resize_y, this->inf->resize_y);

		/* Make sure the height suits the 3 column (resp. not-editable) format; the 2 column format can easily fill space between the lists */
		this->smallest_y = ComputeMaxSize(min_acs_height, this->smallest_y + this->resize_y - 1, this->resize_y);
	}

	virtual void AssignSizePosition(SizingType sizing, uint x, uint y, uint given_width, uint given_height, bool rtl)
	{
		this->StoreSizePosition(sizing, x, y, given_width, given_height);

		uint min_avs_width = this->avs->smallest_x + this->avs->padding_left + this->avs->padding_right;
		uint min_acs_width = this->acs->smallest_x + this->acs->padding_left + this->acs->padding_right;
		uint min_inf_width = this->inf->smallest_x + this->inf->padding_left + this->inf->padding_right;

		uint min_list_width = max(min_avs_width, min_acs_width); // Smallest width of the lists such that they have equal width (incl padding).
		uint avs_extra_width = min_list_width - min_avs_width;   // Additional width needed for avs to reach min_list_width.
		uint acs_extra_width = min_list_width - min_acs_width;   // Additional width needed for acs to reach min_list_width.

		/* Use 2 or 3 colmuns? */
		uint min_three_columns = min_avs_width + min_acs_width + min_inf_width + 2 * INTER_COLUMN_SPACING;
		uint min_two_columns   = min_list_width + min_inf_width + INTER_COLUMN_SPACING;
		bool use_three_columns = this->editable && (min_three_columns + MIN_EXTRA_FOR_3_COLUMNS <= given_width);

		/* Info panel is a seperate column in both modes. Compute its width first. */
		uint extra_width, inf_width;
		if (use_three_columns) {
			extra_width = given_width - min_three_columns;
			inf_width = min(MAX_EXTRA_INFO_WIDTH, extra_width / 2);
		} else {
			extra_width = given_width - min_two_columns;
			inf_width = min(MAX_EXTRA_INFO_WIDTH, extra_width / 2);
		}
		inf_width = ComputeMaxSize(this->inf->smallest_x, this->inf->smallest_x + inf_width, this->inf->GetHorizontalStepSize(sizing));
		extra_width -= inf_width - this->inf->smallest_x;

		uint inf_height = ComputeMaxSize(this->inf->smallest_y, given_height, this->inf->GetVerticalStepSize(sizing));

		if (use_three_columns) {
			/* Three column display, first make both lists equally wide, then divide whatever is left between both lists.
			 * Only keep track of what avs gets, all other space goes to acs. */
			uint avs_width = min(avs_extra_width, extra_width);
			extra_width -= avs_width;
			extra_width -= min(acs_extra_width, extra_width);
			avs_width += extra_width / 2;

			avs_width = ComputeMaxSize(this->avs->smallest_x, this->avs->smallest_x + avs_width, this->avs->GetHorizontalStepSize(sizing));

			uint acs_width = given_width - // Remaining space, including horizontal padding.
					inf_width - this->inf->padding_left - this->inf->padding_right -
					avs_width - this->avs->padding_left - this->avs->padding_right - 2 * INTER_COLUMN_SPACING;
			acs_width = ComputeMaxSize(min_acs_width, acs_width, this->acs->GetHorizontalStepSize(sizing)) -
					this->acs->padding_left - this->acs->padding_right;

			/* Never use fill_y on these; the minimal size is choosen, so that the 3 column view looks nice */
			uint avs_height = ComputeMaxSize(this->avs->smallest_y, given_height, this->avs->resize_y);
			uint acs_height = ComputeMaxSize(this->acs->smallest_y, given_height, this->acs->resize_y);

			/* Assign size and position to the childs. */
			if (rtl) {
				x += this->inf->padding_left;
				this->inf->AssignSizePosition(sizing, x, y + this->inf->padding_top, inf_width, inf_height, rtl);
				x += inf_width + this->inf->padding_right + INTER_COLUMN_SPACING;
			} else {
				x += this->avs->padding_left;
				this->avs->AssignSizePosition(sizing, x, y + this->avs->padding_top, avs_width, avs_height, rtl);
				x += avs_width + this->avs->padding_right + INTER_COLUMN_SPACING;
			}

			x += this->acs->padding_left;
			this->acs->AssignSizePosition(sizing, x, y + this->acs->padding_top, acs_width, acs_height, rtl);
			x += acs_width + this->acs->padding_right + INTER_COLUMN_SPACING;

			if (rtl) {
				x += this->avs->padding_left;
				this->avs->AssignSizePosition(sizing, x, y + this->avs->padding_top, avs_width, avs_height, rtl);
			} else {
				x += this->inf->padding_left;
				this->inf->AssignSizePosition(sizing, x, y + this->inf->padding_top, inf_width, inf_height, rtl);
			}
		} else {
			/* Two columns, all space in extra_width goes to both lists. Since the lists are underneath each other,
			 * the column is min_list_width wide at least. */
			uint avs_width = ComputeMaxSize(this->avs->smallest_x, this->avs->smallest_x + avs_extra_width + extra_width,
					this->avs->GetHorizontalStepSize(sizing));
			uint acs_width = ComputeMaxSize(this->acs->smallest_x, this->acs->smallest_x + acs_extra_width + extra_width,
					this->acs->GetHorizontalStepSize(sizing));

			uint min_avs_height = (!this->editable) ? 0 : this->avs->smallest_y + this->avs->padding_top + this->avs->padding_bottom + INTER_LIST_SPACING;
			uint min_acs_height = this->acs->smallest_y + this->acs->padding_top + this->acs->padding_bottom;
			uint extra_height = given_height - min_acs_height - min_avs_height;

			/* Never use fill_y on these; instead use the INTER_LIST_SPACING as filler */
			uint avs_height = ComputeMaxSize(this->avs->smallest_y, this->avs->smallest_y + extra_height / 2, this->avs->resize_y);
			if (this->editable) extra_height -= avs_height - this->avs->smallest_y;
			uint acs_height = ComputeMaxSize(this->acs->smallest_y, this->acs->smallest_y + extra_height, this->acs->resize_y);

			/* Assign size and position to the childs. */
			if (rtl) {
				x += this->inf->padding_left;
				this->inf->AssignSizePosition(sizing, x, y + this->inf->padding_top, inf_width, inf_height, rtl);
				x += inf_width + this->inf->padding_right + INTER_COLUMN_SPACING;

				this->acs->AssignSizePosition(sizing, x + this->acs->padding_left, y + this->acs->padding_top, acs_width, acs_height, rtl);
				if (this->editable) {
					this->avs->AssignSizePosition(sizing, x + this->avs->padding_left, y + given_height - avs_height - this->avs->padding_bottom, avs_width, avs_height, rtl);
				} else {
					this->avs->AssignSizePosition(sizing, 0, 0, this->avs->smallest_x, this->avs->smallest_y, rtl);
				}
			} else {
				this->acs->AssignSizePosition(sizing, x + this->acs->padding_left, y + this->acs->padding_top, acs_width, acs_height, rtl);
				if (this->editable) {
					this->avs->AssignSizePosition(sizing, x + this->avs->padding_left, y + given_height - avs_height - this->avs->padding_bottom, avs_width, avs_height, rtl);
				} else {
					this->avs->AssignSizePosition(sizing, 0, 0, this->avs->smallest_x, this->avs->smallest_y, rtl);
				}
				uint dx = this->acs->current_x + this->acs->padding_left + this->acs->padding_right;
				if (this->editable) {
					dx = max(dx, this->avs->current_x + this->avs->padding_left + this->avs->padding_right);
				}
				x += dx + INTER_COLUMN_SPACING + this->inf->padding_left;
				this->inf->AssignSizePosition(sizing, x, y + this->inf->padding_top, inf_width, inf_height, rtl);
			}
		}
	}

	virtual NWidgetCore *GetWidgetFromPos(int x, int y)
	{
		if (!IsInsideBS(x, this->pos_x, this->current_x) || !IsInsideBS(y, this->pos_y, this->current_y)) return NULL;

		NWidgetCore *nw = (this->editable) ? this->avs->GetWidgetFromPos(x, y) : NULL;
		if (nw == NULL) nw = this->acs->GetWidgetFromPos(x, y);
		if (nw == NULL) nw = this->inf->GetWidgetFromPos(x, y);
		return nw;
	}

	virtual void Draw(const Window *w)
	{
		if (this->editable) this->avs->Draw(w);
		this->acs->Draw(w);
		this->inf->Draw(w);
	}
};

const uint NWidgetNewGRFDisplay::INTER_LIST_SPACING      = WD_RESIZEBOX_WIDTH + 1;
const uint NWidgetNewGRFDisplay::INTER_COLUMN_SPACING    = WD_RESIZEBOX_WIDTH;
const uint NWidgetNewGRFDisplay::MAX_EXTRA_INFO_WIDTH    = 150;
const uint NWidgetNewGRFDisplay::MIN_EXTRA_FOR_3_COLUMNS = 50;

static const NWidgetPart _nested_newgrf_actives_widgets[] = {
	/* Left side, presets. */
	NWidget(NWID_HORIZONTAL),
		NWidget(WWT_TEXT, COLOUR_MAUVE), SetDataTip(STR_NEWGRF_SETTINGS_SELECT_PRESET, STR_NULL),
				SetPadding(0, WD_FRAMETEXT_RIGHT, 0, 0),
		NWidget(WWT_DROPDOWN, COLOUR_YELLOW, WID_NS_PRESET_LIST), SetFill(1, 0), SetResize(1, 0),
				SetDataTip(STR_JUST_STRING, STR_NEWGRF_SETTINGS_PRESET_LIST_TOOLTIP),
	EndContainer(),
	NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
		NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_PRESET_SAVE), SetFill(1, 0), SetResize(1, 0),
				SetDataTip(STR_NEWGRF_SETTINGS_PRESET_SAVE, STR_NEWGRF_SETTINGS_PRESET_SAVE_TOOLTIP),
		NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_PRESET_DELETE), SetFill(1, 0), SetResize(1, 0),
				SetDataTip(STR_NEWGRF_SETTINGS_PRESET_DELETE, STR_NEWGRF_SETTINGS_PRESET_DELETE_TOOLTIP),
	EndContainer(),

	NWidget(NWID_SPACER), SetMinimalSize(0, WD_RESIZEBOX_WIDTH), SetResize(1, 0), SetFill(1, 0),
	NWidget(WWT_PANEL, COLOUR_MAUVE),
		NWidget(WWT_LABEL, COLOUR_MAUVE), SetDataTip(STR_NEWGRF_SETTINGS_ACTIVE_LIST, STR_NULL),
				SetFill(1, 0), SetResize(1, 0), SetPadding(3, WD_FRAMETEXT_RIGHT, 0, WD_FRAMETEXT_LEFT),
		/* Left side, active grfs. */
		NWidget(NWID_HORIZONTAL), SetPadding(0, 2, 0, 2),
			NWidget(WWT_PANEL, COLOUR_MAUVE),
				NWidget(WWT_INSET, COLOUR_MAUVE, WID_NS_FILE_LIST), SetMinimalSize(100, 1), SetPadding(2, 2, 2, 2),
						SetFill(1, 1), SetResize(1, 1), SetScrollbar(WID_NS_SCROLLBAR), SetDataTip(STR_NULL, STR_NEWGRF_SETTINGS_FILE_TOOLTIP),
				EndContainer(),
			EndContainer(),
			NWidget(NWID_VSCROLLBAR, COLOUR_MAUVE, WID_NS_SCROLLBAR),
		EndContainer(),
		/* Buttons. */
		NWidget(NWID_SELECTION, INVALID_COLOUR, WID_NS_SHOW_REMOVE),
			NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPadding(2, 2, 2, 2), SetPIP(0, WD_RESIZEBOX_WIDTH, 0),
				NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_REMOVE), SetFill(1, 0), SetResize(1, 0),
						SetDataTip(STR_NEWGRF_SETTINGS_REMOVE, STR_NEWGRF_SETTINGS_REMOVE_TOOLTIP),
				NWidget(NWID_VERTICAL),
					NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_MOVE_UP), SetFill(1, 0), SetResize(1, 0),
							SetDataTip(STR_NEWGRF_SETTINGS_MOVEUP, STR_NEWGRF_SETTINGS_MOVEUP_TOOLTIP),
					NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_MOVE_DOWN), SetFill(1, 0), SetResize(1, 0),
							SetDataTip(STR_NEWGRF_SETTINGS_MOVEDOWN, STR_NEWGRF_SETTINGS_MOVEDOWN_TOOLTIP),
				EndContainer(),
			EndContainer(),

			NWidget(NWID_VERTICAL, NC_EQUALSIZE), SetPadding(2, 2, 2, 2),
				NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_RESCAN_FILES2), SetFill(1, 0), SetResize(1, 0),
						SetDataTip(STR_NEWGRF_SETTINGS_RESCAN_FILES, STR_NEWGRF_SETTINGS_RESCAN_FILES_TOOLTIP),
				NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_CONTENT_DOWNLOAD2), SetFill(1, 0), SetResize(1, 0),
						SetDataTip(STR_INTRO_ONLINE_CONTENT, STR_INTRO_TOOLTIP_ONLINE_CONTENT),
			EndContainer(),
		EndContainer(),
	EndContainer(),
};

static const NWidgetPart _nested_newgrf_availables_widgets[] = {
	NWidget(WWT_PANEL, COLOUR_MAUVE),
		NWidget(WWT_LABEL, COLOUR_MAUVE), SetDataTip(STR_NEWGRF_SETTINGS_INACTIVE_LIST, STR_NULL),
				SetFill(1, 0), SetResize(1, 0), SetPadding(3, WD_FRAMETEXT_RIGHT, 0, WD_FRAMETEXT_LEFT),
		/* Left side, available grfs, filter edit box. */
		NWidget(NWID_HORIZONTAL), SetPadding(WD_TEXTPANEL_TOP, 0, WD_TEXTPANEL_BOTTOM, 0),
				SetPIP(WD_FRAMETEXT_LEFT, WD_FRAMETEXT_RIGHT, WD_FRAMETEXT_RIGHT),
			NWidget(WWT_TEXT, COLOUR_MAUVE), SetFill(0, 1), SetDataTip(STR_NEWGRF_FILTER_TITLE, STR_NULL),
			NWidget(WWT_EDITBOX, COLOUR_MAUVE, WID_NS_FILTER), SetFill(1, 0), SetMinimalSize(50, 12), SetResize(1, 0),
					SetDataTip(STR_LIST_FILTER_OSKTITLE, STR_LIST_FILTER_TOOLTIP),
		EndContainer(),
		/* Left side, available grfs. */
		NWidget(NWID_HORIZONTAL), SetPadding(0, 2, 0, 2),
			NWidget(WWT_PANEL, COLOUR_MAUVE),
				NWidget(WWT_INSET, COLOUR_MAUVE, WID_NS_AVAIL_LIST), SetMinimalSize(100, 1), SetPadding(2, 2, 2, 2),
						SetFill(1, 1), SetResize(1, 1), SetScrollbar(WID_NS_SCROLL2BAR),
				EndContainer(),
			EndContainer(),
			NWidget(NWID_VSCROLLBAR, COLOUR_MAUVE, WID_NS_SCROLL2BAR),
		EndContainer(),
		/* Left side, available grfs, buttons. */
		NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPadding(2, 2, 2, 2), SetPIP(0, WD_RESIZEBOX_WIDTH, 0),
			NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_ADD), SetFill(1, 0), SetResize(1, 0),
					SetDataTip(STR_NEWGRF_SETTINGS_ADD, STR_NEWGRF_SETTINGS_ADD_FILE_TOOLTIP),
			NWidget(NWID_VERTICAL),
				NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_RESCAN_FILES), SetFill(1, 0), SetResize(1, 0),
						SetDataTip(STR_NEWGRF_SETTINGS_RESCAN_FILES, STR_NEWGRF_SETTINGS_RESCAN_FILES_TOOLTIP),
				NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_CONTENT_DOWNLOAD), SetFill(1, 0), SetResize(1, 0),
						SetDataTip(STR_INTRO_ONLINE_CONTENT, STR_INTRO_TOOLTIP_ONLINE_CONTENT),
			EndContainer(),
		EndContainer(),
	EndContainer(),
};

static const NWidgetPart _nested_newgrf_infopanel_widgets[] = {
	/* Right side, info panel. */
	NWidget(NWID_VERTICAL), SetPadding(0, 0, 2, 0),
		NWidget(WWT_PANEL, COLOUR_MAUVE), SetPadding(0, 0, 2, 0),
			NWidget(WWT_EMPTY, COLOUR_MAUVE, WID_NS_NEWGRF_INFO_TITLE), SetFill(1, 0), SetResize(1, 0),
			NWidget(WWT_EMPTY, COLOUR_MAUVE, WID_NS_NEWGRF_INFO), SetFill(1, 1), SetResize(1, 1), SetMinimalSize(150, 100),
		EndContainer(),
		NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_OPEN_URL), SetFill(1, 0), SetResize(1, 0),
				SetDataTip(STR_CONTENT_OPEN_URL, STR_CONTENT_OPEN_URL_TOOLTIP),
		NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_NEWGRF_TEXTFILE + TFT_README), SetFill(1, 0), SetResize(1, 0),
				SetDataTip(STR_NEWGRF_SETTINGS_VIEW_README, STR_NULL),
		NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
			NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_NEWGRF_TEXTFILE + TFT_CHANGELOG), SetFill(1, 0), SetResize(1, 0),
					SetDataTip(STR_NEWGRF_SETTINGS_VIEW_CHANGELOG, STR_NULL),
			NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_NEWGRF_TEXTFILE + TFT_LICENSE), SetFill(1, 0), SetResize(1, 0),
					SetDataTip(STR_NEWGRF_SETTINGS_VIEW_LICENSE, STR_NULL),
		EndContainer(),
	EndContainer(),
	NWidget(NWID_SELECTION, INVALID_COLOUR, WID_NS_SHOW_APPLY),
		/* Right side, buttons. */
		NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(0, WD_RESIZEBOX_WIDTH, 0),
			NWidget(NWID_VERTICAL),
				NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_SET_PARAMETERS), SetFill(1, 0), SetResize(1, 0),
						SetDataTip(STR_NEWGRF_SETTINGS_SET_PARAMETERS, STR_NULL),
				NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_TOGGLE_PALETTE), SetFill(1, 0), SetResize(1, 0),
						SetDataTip(STR_NEWGRF_SETTINGS_TOGGLE_PALETTE, STR_NEWGRF_SETTINGS_TOGGLE_PALETTE_TOOLTIP),
			EndContainer(),
			NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_APPLY_CHANGES), SetFill(1, 0), SetResize(1, 0),
					SetDataTip(STR_NEWGRF_SETTINGS_APPLY_CHANGES, STR_NULL),
		EndContainer(),
	EndContainer(),
};

/** Construct nested container widget for managing the lists and the info panel of the NewGRF GUI. */
NWidgetBase* NewGRFDisplay(int *biggest_index)
{
	NWidgetBase *avs = MakeNWidgets(_nested_newgrf_availables_widgets, lengthof(_nested_newgrf_availables_widgets), biggest_index, NULL);

	int biggest2;
	NWidgetBase *acs = MakeNWidgets(_nested_newgrf_actives_widgets, lengthof(_nested_newgrf_actives_widgets), &biggest2, NULL);
	*biggest_index = max(*biggest_index, biggest2);

	NWidgetBase *inf = MakeNWidgets(_nested_newgrf_infopanel_widgets, lengthof(_nested_newgrf_infopanel_widgets), &biggest2, NULL);
	*biggest_index = max(*biggest_index, biggest2);

	return new NWidgetNewGRFDisplay(avs, acs, inf);
}

/* Widget definition of the manage newgrfs window */
static const NWidgetPart _nested_newgrf_widgets[] = {
	NWidget(NWID_HORIZONTAL),
		NWidget(WWT_CLOSEBOX, COLOUR_MAUVE),
		NWidget(WWT_CAPTION, COLOUR_MAUVE), SetDataTip(STR_NEWGRF_SETTINGS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
	EndContainer(),
	NWidget(WWT_PANEL, COLOUR_MAUVE),
		NWidgetFunction(NewGRFDisplay), SetPadding(WD_RESIZEBOX_WIDTH, WD_RESIZEBOX_WIDTH, 2, WD_RESIZEBOX_WIDTH),
		/* Resize button. */
		NWidget(NWID_HORIZONTAL),
			NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
			NWidget(WWT_RESIZEBOX, COLOUR_MAUVE),
		EndContainer(),
	EndContainer(),
};

/* Window definition of the manage newgrfs window */
static const WindowDesc _newgrf_desc(
	WDP_CENTER, 300, 263,
	WC_GAME_OPTIONS, WC_NONE,
	WDF_UNCLICK_BUTTONS,
	_nested_newgrf_widgets, lengthof(_nested_newgrf_widgets)
);

/**
 * Callback function for the newgrf 'apply changes' confirmation window
 * @param w Window which is calling this callback
 * @param confirmed boolean value, true when yes was clicked, false otherwise
 */
static void NewGRFConfirmationCallback(Window *w, bool confirmed)
{
	if (confirmed) {
		DeleteWindowByClass(WC_GRF_PARAMETERS);
		NewGRFWindow *nw = dynamic_cast<NewGRFWindow*>(w);

		GamelogStartAction(GLAT_GRF);
		GamelogGRFUpdate(_grfconfig, nw->actives); // log GRF changes
		CopyGRFConfigList(nw->orig_list, nw->actives, false);
		ReloadNewGRFData();
		GamelogStopAction();

		/* Show new, updated list */
		GRFConfig *c;
		int i = 0;
		for (c = nw->actives; c != NULL && c != nw->active_sel; c = c->next, i++) {}
		CopyGRFConfigList(&nw->actives, *nw->orig_list, false);
		for (c = nw->actives; c != NULL && i > 0; c = c->next, i--) {}
		nw->active_sel = c;
		nw->avails.ForceRebuild();

		w->InvalidateData();

		ReInitAllWindows();
		DeleteWindowByClass(WC_BUILD_OBJECT);
	}
}



/**
 * Setup the NewGRF gui
 * @param editable allow the user to make changes to the grfconfig in the window
 * @param show_params show information about what parameters are set for the grf files
 * @param exec_changes if changes are made to the list (editable is true), apply these
 *        changes immediately or only update the list
 * @param config pointer to a linked-list of grfconfig's that will be shown
 */
void ShowNewGRFSettings(bool editable, bool show_params, bool exec_changes, GRFConfig **config)
{
	DeleteWindowByClass(WC_GAME_OPTIONS);
	new NewGRFWindow(&_newgrf_desc, editable, show_params, exec_changes, config);
}

/** Widgets for the progress window. */
static const NWidgetPart _nested_scan_progress_widgets[] = {
	NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_NEWGRF_SCAN_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
	NWidget(WWT_PANEL, COLOUR_GREY),
		NWidget(NWID_HORIZONTAL), SetPIP(20, 0, 20),
			NWidget(NWID_VERTICAL), SetPIP(11, 8, 11),
				NWidget(WWT_LABEL, INVALID_COLOUR), SetDataTip(STR_NEWGRF_SCAN_MESSAGE, STR_NULL), SetFill(1, 0),
				NWidget(WWT_EMPTY, INVALID_COLOUR, WID_SP_PROGRESS_BAR), SetFill(1, 0),
				NWidget(WWT_EMPTY, INVALID_COLOUR, WID_SP_PROGRESS_TEXT), SetFill(1, 0),
			EndContainer(),
		EndContainer(),
	EndContainer(),
};

/** Description of the widgets and other settings of the window. */
static const WindowDesc _scan_progress_desc(
	WDP_CENTER, 0, 0,
	WC_MODAL_PROGRESS, WC_NONE,
	WDF_UNCLICK_BUTTONS,
	_nested_scan_progress_widgets, lengthof(_nested_scan_progress_widgets)
);

/** Window for showing the progress of NewGRF scanning. */
struct ScanProgressWindow : public Window {
	char *last_name; ///< The name of the last 'seen' NewGRF.
	int scanned;     ///< The number of NewGRFs that we have seen.

	/** Create the window. */
	ScanProgressWindow() : Window(), last_name(NULL), scanned(0)
	{
		this->InitNested(&_scan_progress_desc, 1);
	}

	/** Free the last name buffer. */
	~ScanProgressWindow()
	{
		free(last_name);
	}

	virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
	{
		switch (widget) {
			case WID_SP_PROGRESS_BAR: {
				SetDParam(0, 100);
				*size = GetStringBoundingBox(STR_GENERATION_PROGRESS);
				/* We need some spacing for the 'border' */
				size->height += 8;
				size->width += 8;
				break;
			}

			case WID_SP_PROGRESS_TEXT:
				SetDParam(0, 9999);
				SetDParam(1, 9999);
				/* We really don't know the width. We could determine it by scanning the NewGRFs,
				 * but this is the status window for scanning them... */
				size->width = max(400U, GetStringBoundingBox(STR_NEWGRF_SCAN_STATUS).width);
				size->height = FONT_HEIGHT_NORMAL * 2 + WD_PAR_VSEP_NORMAL;
				break;
		}
	}

	virtual void DrawWidget(const Rect &r, int widget) const
	{
		switch (widget) {
			case WID_SP_PROGRESS_BAR: {
				/* Draw the % complete with a bar and a text */
				DrawFrameRect(r.left, r.top, r.right, r.bottom, COLOUR_GREY, FR_BORDERONLY);
				uint percent = scanned * 100 / max(1U, _settings_client.gui.last_newgrf_count);
				DrawFrameRect(r.left + 1, r.top + 1, (int)((r.right - r.left - 2) * percent / 100) + r.left + 1, r.bottom - 1, COLOUR_MAUVE, FR_NONE);
				SetDParam(0, percent);
				DrawString(r.left, r.right, r.top + 5, STR_GENERATION_PROGRESS, TC_FROMSTRING, SA_HOR_CENTER);
				break;
			}

			case WID_SP_PROGRESS_TEXT:
				SetDParam(0, this->scanned);
				SetDParam(1, _settings_client.gui.last_newgrf_count);
				DrawString(r.left, r.right, r.top, STR_NEWGRF_SCAN_STATUS, TC_FROMSTRING, SA_HOR_CENTER);

				DrawString(r.left, r.right, r.top + FONT_HEIGHT_NORMAL + WD_PAR_VSEP_NORMAL, this->last_name == NULL ? "" : this->last_name, TC_BLACK, SA_HOR_CENTER);
				break;
		}
	}

	/**
	 * Update the NewGRF scan status.
	 * @param num  The number of NewGRFs scanned so far.
	 * @param name The name of the last scanned NewGRF.
	 */
	void UpdateNewGRFScanStatus(uint num, const char *name)
	{
		free(this->last_name);
		if (name == NULL) {
			char buf[256];
			GetString(buf, STR_NEWGRF_SCAN_ARCHIVES, lastof(buf));
			this->last_name = strdup(buf);
		} else {
			this->last_name = strdup(name);
		}
		this->scanned = num;
		if (num > _settings_client.gui.last_newgrf_count) _settings_client.gui.last_newgrf_count = num;

		this->SetDirty();
	}
};

/**
 * Update the NewGRF scan status.
 * @param num  The number of NewGRFs scanned so far.
 * @param name The name of the last scanned NewGRF.
 */
void UpdateNewGRFScanStatus(uint num, const char *name)
{
	ScanProgressWindow *w  = dynamic_cast<ScanProgressWindow *>(FindWindowByClass(WC_MODAL_PROGRESS));
	if (w == NULL) w = new ScanProgressWindow();
	w->UpdateNewGRFScanStatus(num, name);
}