Files @ r13202:bd74049d778a
Branch filter:

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

frosch
(svn r17719) -Change: [NoAI] Make AIEngine:CanRefitCargo() not report refittability to Mail by default for aircraft. It is not necessarily true, and the special case of carrying both passenger&mail is better handled by AIs themself than by the API.
   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
/* $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 vehicle_gui.cpp The base GUI for all vehicles. */

#include "stdafx.h"
#include "openttd.h"
#include "debug.h"
#include "company_func.h"
#include "gui.h"
#include "window_gui.h"
#include "textbuf_gui.h"
#include "command_func.h"
#include "vehicle_gui.h"
#include "vehicle_gui_base.h"
#include "viewport_func.h"
#include "gfx_func.h"
#include "newgrf_engine.h"
#include "newgrf_text.h"
#include "waypoint_base.h"
#include "roadveh.h"
#include "train.h"
#include "aircraft.h"
#include "depot_base.h"
#include "group_gui.h"
#include "strings_func.h"
#include "window_func.h"
#include "vehicle_func.h"
#include "autoreplace_gui.h"
#include "string_func.h"
#include "widgets/dropdown_func.h"
#include "timetable.h"
#include "vehiclelist.h"
#include "articulated_vehicles.h"
#include "cargotype.h"

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

Sorting _sorting;

static GUIVehicleList::SortFunction VehicleNumberSorter;
static GUIVehicleList::SortFunction VehicleNameSorter;
static GUIVehicleList::SortFunction VehicleAgeSorter;
static GUIVehicleList::SortFunction VehicleProfitThisYearSorter;
static GUIVehicleList::SortFunction VehicleProfitLastYearSorter;
static GUIVehicleList::SortFunction VehicleCargoSorter;
static GUIVehicleList::SortFunction VehicleReliabilitySorter;
static GUIVehicleList::SortFunction VehicleMaxSpeedSorter;
static GUIVehicleList::SortFunction VehicleModelSorter;
static GUIVehicleList::SortFunction VehicleValueSorter;
static GUIVehicleList::SortFunction VehicleLengthSorter;
static GUIVehicleList::SortFunction VehicleTimeToLiveSorter;
static GUIVehicleList::SortFunction VehicleTimetableDelaySorter;

GUIVehicleList::SortFunction * const BaseVehicleListWindow::vehicle_sorter_funcs[] = {
	&VehicleNumberSorter,
	&VehicleNameSorter,
	&VehicleAgeSorter,
	&VehicleProfitThisYearSorter,
	&VehicleProfitLastYearSorter,
	&VehicleCargoSorter,
	&VehicleReliabilitySorter,
	&VehicleMaxSpeedSorter,
	&VehicleModelSorter,
	&VehicleValueSorter,
	&VehicleLengthSorter,
	&VehicleTimeToLiveSorter,
	&VehicleTimetableDelaySorter,
};

const StringID BaseVehicleListWindow::vehicle_sorter_names[] = {
	STR_SORT_BY_NUMBER,
	STR_SORT_BY_NAME,
	STR_SORT_BY_AGE,
	STR_SORT_BY_PROFIT_THIS_YEAR,
	STR_SORT_BY_PROFIT_LAST_YEAR,
	STR_SORT_BY_TOTAL_CAPACITY_PER_CARGOTYPE,
	STR_SORT_BY_RELIABILITY,
	STR_SORT_BY_MAX_SPEED,
	STR_SORT_BY_MODEL,
	STR_SORT_BY_VALUE,
	STR_SORT_BY_LENGTH,
	STR_SORT_BY_LIFE_TIME,
	STR_SORT_BY_TIMETABLE_DELAY,
	INVALID_STRING_ID
};

void BaseVehicleListWindow::BuildVehicleList(Owner owner, uint16 index, uint16 window_type)
{
	if (!this->vehicles.NeedRebuild()) return;

	DEBUG(misc, 3, "Building vehicle list for company %d at station %d", owner, index);

	GenerateVehicleSortList(&this->vehicles, this->vehicle_type, owner, index, window_type);

	this->vehicles.RebuildDone();
	this->vscroll.SetCount(this->vehicles.Length());
}

/* cached values for VehicleNameSorter to spare many GetString() calls */
static const Vehicle *_last_vehicle[2] = { NULL, NULL };

void BaseVehicleListWindow::SortVehicleList()
{
	if (this->vehicles.Sort()) return;

	/* invalidate cached values for name sorter - vehicle names could change */
	_last_vehicle[0] = _last_vehicle[1] = NULL;
}

void DepotSortList(VehicleList *list)
{
	if (list->Length() < 2) return;
	QSortT(list->Begin(), list->Length(), &VehicleNumberSorter);
}

/** draw the vehicle profit button in the vehicle list window. */
void DrawVehicleProfitButton(const Vehicle *v, int x, int y)
{
	SpriteID pal;

	/* draw profit-based coloured icons */
	if (v->age <= DAYS_IN_YEAR * 2) {
		pal = PALETTE_TO_GREY;
	} else if (v->GetDisplayProfitLastYear() < 0) {
		pal = PALETTE_TO_RED;
	} else if (v->GetDisplayProfitLastYear() < 10000) {
		pal = PALETTE_TO_YELLOW;
	} else {
		pal = PALETTE_TO_GREEN;
	}
	DrawSprite(SPR_BLOT, pal, x, y);
}

struct RefitOption {
	CargoID cargo;
	byte subtype;
	uint16 value;
	EngineID engine;
};

struct RefitList {
	uint num_lines;
	RefitOption *items;
};

static RefitList *BuildRefitList(const Vehicle *v)
{
	uint max_lines = 256;
	RefitOption *refit = CallocT<RefitOption>(max_lines);
	RefitList *list = CallocT<RefitList>(1);
	Vehicle *u = const_cast<Vehicle *>(v);
	uint num_lines = 0;
	uint i;

	do {
		uint32 cmask = EngInfo(u->engine_type)->refit_mask;
		byte callback_mask = EngInfo(u->engine_type)->callback_mask;

		/* Skip this engine if it has no capacity */
		if (u->cargo_cap == 0) continue;

		/* Loop through all cargos in the refit mask */
		for (CargoID cid = 0; cid < NUM_CARGO && num_lines < max_lines; cid++) {
			/* Skip cargo type if it's not listed */
			if (!HasBit(cmask, cid)) continue;

			/* Check the vehicle's callback mask for cargo suffixes */
			if (HasBit(callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) {
				/* Make a note of the original cargo type. It has to be
				 * changed to test the cargo & subtype... */
				CargoID temp_cargo = u->cargo_type;
				byte temp_subtype  = u->cargo_subtype;
				byte refit_cyc;

				u->cargo_type = cid;

				for (refit_cyc = 0; refit_cyc < 16 && num_lines < max_lines; refit_cyc++) {
					bool duplicate = false;
					uint16 callback;

					u->cargo_subtype = refit_cyc;
					callback = GetVehicleCallback(CBID_VEHICLE_CARGO_SUFFIX, 0, 0, u->engine_type, u);

					if (callback == 0xFF) callback = CALLBACK_FAILED;
					if (refit_cyc != 0 && callback == CALLBACK_FAILED) break;

					/* Check if this cargo and subtype combination are listed */
					for (i = 0; i < num_lines && !duplicate; i++) {
						if (refit[i].cargo == cid && refit[i].value == callback) duplicate = true;
					}

					if (duplicate) continue;

					refit[num_lines].cargo   = cid;
					refit[num_lines].subtype = refit_cyc;
					refit[num_lines].value   = callback;
					refit[num_lines].engine  = u->engine_type;
					num_lines++;
				}

				/* Reset the vehicle's cargo type */
				u->cargo_type    = temp_cargo;
				u->cargo_subtype = temp_subtype;
			} else {
				/* No cargo suffix callback -- use no subtype */
				bool duplicate = false;

				for (i = 0; i < num_lines && !duplicate; i++) {
					if (refit[i].cargo == cid && refit[i].value == CALLBACK_FAILED) duplicate = true;
				}

				if (!duplicate) {
					refit[num_lines].cargo   = cid;
					refit[num_lines].subtype = 0;
					refit[num_lines].value   = CALLBACK_FAILED;
					refit[num_lines].engine  = INVALID_ENGINE;
					num_lines++;
				}
			}
		}
	} while ((v->type == VEH_TRAIN || v->type == VEH_ROAD) && (u = u->Next()) != NULL && num_lines < max_lines);

	list->num_lines = num_lines;
	list->items = refit;

	return list;
}

/** Draw the list of available refit options for a consist.
 * Draw the list and highlight the selected refit option (if any)
 * @param *list first vehicle in consist to get the refit-options of
 * @param sel selected refit cargo-type in the window
 * @param pos position of the selected item in caller widow
 * @param rows number of rows(capacity) in caller window
 * @param delta step height in caller window
 * @param right the right most position to draw
 * @return the refit option that is hightlighted, NULL if none
 */
static RefitOption *DrawVehicleRefitWindow(const RefitList *list, int sel, uint pos, uint rows, uint delta, uint right)
{
	RefitOption *refit = list->items;
	RefitOption *selected = NULL;
	uint num_lines = list->num_lines;
	uint y = 31;
	uint i;

	/* Draw the list, and find the selected cargo (by its position in list) */
	for (i = 0; i < num_lines; i++) {
		TextColour colour = TC_BLACK;
		if (sel == 0) {
			selected = &refit[i];
			colour = TC_WHITE;
		}

		if (i >= pos && i < pos + rows) {
			/* Draw the cargo name */
			int last_x = DrawString(2, right, y, CargoSpec::Get(refit[i].cargo)->name, colour);

			/* If the callback succeeded, draw the cargo suffix */
			if (refit[i].value != CALLBACK_FAILED) {
				DrawString(last_x + 1, right, y, GetGRFStringID(GetEngineGRFID(refit[i].engine), 0xD000 + refit[i].value), colour);
			}
			y += delta;
		}

		sel--;
	}

	return selected;
}

/** Widget numbers of the vehicle refit window. */
enum VehicleRefitWidgets {
	VRW_CLOSEBOX,
	VRW_CAPTION,
	VRW_SELECTHEADER,
	VRW_MATRIX,
	VRW_SCROLLBAR,
	VRW_INFOPANEL,
	VRW_REFITBUTTON,
	VRW_RESIZEBOX,
};

struct RefitWindow : public Window {
	int sel;
	RefitOption *cargo;
	RefitList *list;
	uint length;
	VehicleOrderID order;

	RefitWindow(const WindowDesc *desc, const Vehicle *v, VehicleOrderID order) : Window(desc, v->index)
	{
		this->owner = v->owner;
		this->vscroll.SetCapacity(8);
		this->resize.step_height = 14;

		this->order = order;
		this->sel  = -1;
		this->list = BuildRefitList(v);
		if (v->type == VEH_TRAIN) this->length = CountVehiclesInChain(v);
		this->vscroll.SetCount(this->list->num_lines);

		this->widget[VRW_SELECTHEADER].tooltips = STR_REFIT_TRAIN_LIST_TOOLTIP + v->type;
		this->widget[VRW_MATRIX].tooltips       = STR_REFIT_TRAIN_LIST_TOOLTIP + v->type;
		this->widget[VRW_REFITBUTTON].data      = STR_REFIT_TRAIN_REFIT_BUTTON + v->type;
		this->widget[VRW_REFITBUTTON].tooltips  = STR_REFIT_TRAIN_REFIT_TOOLTIP + v->type;

		this->FindWindowPlacementAndResize(desc);
	}

	~RefitWindow()
	{
		free(this->list->items);
		free(this->list);
	}

	virtual void OnPaint()
	{
		Vehicle *v = Vehicle::Get(this->window_number);

		if (v->type == VEH_TRAIN) {
			uint length = CountVehiclesInChain(v);

			if (length != this->length) {
				/* Consist length has changed, so rebuild the refit list */
				free(this->list->items);
				free(this->list);
				this->list = BuildRefitList(v);
				this->length = length;
			}
		}

		this->vscroll.SetCount(this->list->num_lines);

		SetDParam(0, v->index);
		this->DrawWidgets();

		this->cargo = DrawVehicleRefitWindow(this->list, this->sel, this->vscroll.GetPosition(), this->vscroll.GetCapacity(), this->resize.step_height, this->width - 2);

		if (this->cargo != NULL) {
			CommandCost cost;

			cost = DoCommand(v->tile, v->index, this->cargo->cargo | this->cargo->subtype << 8,
							 DC_QUERY_COST, GetCmdRefitVeh(v->type));

			if (CmdSucceeded(cost)) {
				SetDParam(0, this->cargo->cargo);
				SetDParam(1, _returned_refit_capacity);
				SetDParam(2, cost.GetCost());
				DrawStringMultiLine(2, this->width - 2, this->widget[VRW_INFOPANEL].top + 1, this->widget[VRW_INFOPANEL].bottom, STR_REFIT_NEW_CAPACITY_COST_OF_REFIT);
			}
		}
	}

	virtual void OnClick(Point pt, int widget)
	{
		switch (widget) {
			case VRW_MATRIX: { // listbox
				int y = pt.y - this->widget[VRW_MATRIX].top;
				if (y >= 0) {
					this->sel = (y / (int)this->resize.step_height) + this->vscroll.GetPosition();
					this->SetDirty();
				}
				break;
			}

			case VRW_REFITBUTTON: // refit button
				if (this->cargo != NULL) {
					const Vehicle *v = Vehicle::Get(this->window_number);

					if (this->order == INVALID_VEH_ORDER_ID) {
						if (DoCommandP(v->tile, v->index, this->cargo->cargo | this->cargo->subtype << 8, GetCmdRefitVeh(v))) delete this;
					} else {
						if (DoCommandP(v->tile, v->index, this->cargo->cargo | this->cargo->subtype << 8 | this->order << 16, CMD_ORDER_REFIT)) delete this;
					}
				}
				break;
		}
	}

	virtual void OnResize(Point delta)
	{
		this->vscroll.UpdateCapacity(delta.y / (int)this->resize.step_height);
		this->widget[VRW_MATRIX].data = (this->vscroll.GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
	}
};

static const Widget _vehicle_refit_widgets[] = {
	{   WWT_CLOSEBOX,   RESIZE_NONE,  COLOUR_GREY,     0,    10,     0,    13, STR_BLACK_CROSS,   STR_TOOLTIP_CLOSE_WINDOW},             // VRW_CLOSEBOX
	{    WWT_CAPTION,   RESIZE_NONE,  COLOUR_GREY,    11,   239,     0,    13, STR_REFIT_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS},   // VRW_CAPTION
	{    WWT_TEXTBTN,   RESIZE_NONE,  COLOUR_GREY,     0,   239,    14,    27, STR_REFIT_TITLE,   STR_NULL},                             // VRW_SELECTHEADER
	{     WWT_MATRIX, RESIZE_BOTTOM,  COLOUR_GREY,     0,   227,    28,   139, 0x801,             STR_NULL},                             // VRW_MATRIX
	{  WWT_SCROLLBAR, RESIZE_BOTTOM,  COLOUR_GREY,   228,   239,    28,   139, 0x0,               STR_TOOLTIP_VSCROLL_BAR_SCROLLS_LIST}, // VRW_SCROLLBAR
	{      WWT_PANEL,     RESIZE_TB,  COLOUR_GREY,     0,   239,   140,   161, 0x0,               STR_NULL},                             // VRW_INFOPANEL
	{ WWT_PUSHTXTBTN,     RESIZE_TB,  COLOUR_GREY,     0,   227,   162,   173, 0x0,               STR_NULL},                             // VRW_REFITBUTTON
	{  WWT_RESIZEBOX,     RESIZE_TB,  COLOUR_GREY,   228,   239,   162,   173, 0x0,               STR_TOOLTIP_RESIZE},                    // VRW_RESIZEBOX
	{   WIDGETS_END},
};

static const NWidgetPart _nested_vehicle_refit_widgets[] = {
	NWidget(NWID_HORIZONTAL),
		NWidget(WWT_CLOSEBOX, COLOUR_GREY, VRW_CLOSEBOX),
		NWidget(WWT_CAPTION, COLOUR_GREY, VRW_CAPTION), SetDataTip(STR_REFIT_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
	EndContainer(),
	NWidget(WWT_TEXTBTN, COLOUR_GREY, VRW_SELECTHEADER), SetMinimalSize(240, 14), SetDataTip(STR_REFIT_TITLE, STR_NULL),
	/* Matrix + scrollbar. */
	NWidget(NWID_HORIZONTAL),
		NWidget(WWT_MATRIX, COLOUR_GREY, VRW_MATRIX), SetMinimalSize(228, 112), SetResize(0, 14), SetDataTip(0x801, STR_NULL),
		NWidget(WWT_SCROLLBAR, COLOUR_GREY, VRW_SCROLLBAR),
	EndContainer(),
	NWidget(WWT_PANEL, COLOUR_GREY, VRW_INFOPANEL), SetMinimalSize(240, 22), EndContainer(),
	NWidget(NWID_HORIZONTAL),
		NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, VRW_REFITBUTTON), SetMinimalSize(228, 12),
		NWidget(WWT_RESIZEBOX, COLOUR_GREY, VRW_RESIZEBOX),
	EndContainer(),
};

static const WindowDesc _vehicle_refit_desc(
	WDP_AUTO, WDP_AUTO, 240, 174, 240, 174,
	WC_VEHICLE_REFIT, WC_VEHICLE_VIEW,
	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_RESIZABLE | WDF_CONSTRUCTION,
	_vehicle_refit_widgets, _nested_vehicle_refit_widgets, lengthof(_nested_vehicle_refit_widgets)
);

/** Show the refit window for a vehicle
 * @param *v The vehicle to show the refit window for
 * @param order of the vehicle ( ? )
 * @param parent the parent window of the refit window
 */
void ShowVehicleRefitWindow(const Vehicle *v, VehicleOrderID order, Window *parent)
{
	DeleteWindowById(WC_VEHICLE_REFIT, v->index);
	RefitWindow *w = new RefitWindow(&_vehicle_refit_desc, v, order);
	w->parent = parent;
}

/** Display list of cargo types of the engine, for the purchase information window */
uint ShowRefitOptionsList(int left, int right, int y, EngineID engine)
{
	/* List of cargo types of this engine */
	uint32 cmask = GetUnionOfArticulatedRefitMasks(engine, Engine::Get(engine)->type, false);
	/* List of cargo types available in this climate */
	uint32 lmask = _cargo_mask;
	char string[512];
	char *b = string;

	/* Draw nothing if the engine is not refittable */
	if (CountBits(cmask) <= 1) return y;

	b = InlineString(b, STR_PURCHASE_INFO_REFITTABLE_TO);

	if (cmask == lmask) {
		/* Engine can be refitted to all types in this climate */
		b = InlineString(b, STR_PURCHASE_INFO_ALL_TYPES);
	} else {
		/* Check if we are able to refit to more cargo types and unable to. If
		 * so, invert the cargo types to list those that we can't refit to. */
		if (CountBits(cmask ^ lmask) < CountBits(cmask)) {
			cmask ^= lmask;
			b = InlineString(b, STR_PURCHASE_INFO_ALL_BUT);
		}

		bool first = true;

		/* Add each cargo type to the list */
		for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
			if (!HasBit(cmask, cid)) continue;

			if (b >= lastof(string) - (2 + 2 * 4)) break; // ", " and two calls to Utf8Encode()

			if (!first) b = strecpy(b, ", ", lastof(string));
			first = false;

			b = InlineString(b, CargoSpec::Get(cid)->name);
		}
	}

	/* Terminate and display the completed string */
	*b = '\0';

	/* Make sure we detect any buffer overflow */
	assert(b < endof(string));

	SetDParamStr(0, string);
	return DrawStringMultiLine(left, right, y, INT32_MAX, STR_JUST_RAW_STRING);
}

/** Get the cargo subtype text from NewGRF for the vehicle details window. */
StringID GetCargoSubtypeText(const Vehicle *v)
{
	if (HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) {
		uint16 cb = GetVehicleCallback(CBID_VEHICLE_CARGO_SUFFIX, 0, 0, v->engine_type, v);
		if (cb != CALLBACK_FAILED) {
			return GetGRFStringID(GetEngineGRFID(v->engine_type), 0xD000 + cb);
		}
	}
	return STR_EMPTY;
}

/** Sort vehicles by their number */
static int CDECL VehicleNumberSorter(const Vehicle * const *a, const Vehicle * const *b)
{
	return (*a)->unitnumber - (*b)->unitnumber;
}

/** Sort vehicles by their name */
static int CDECL VehicleNameSorter(const Vehicle * const *a, const Vehicle * const *b)
{
	static char last_name[2][64];

	if (*a != _last_vehicle[0]) {
		_last_vehicle[0] = *a;
		SetDParam(0, (*a)->index);
		GetString(last_name[0], STR_VEHICLE_NAME, lastof(last_name[0]));
	}

	if (*b != _last_vehicle[1]) {
		_last_vehicle[1] = *b;
		SetDParam(0, (*b)->index);
		GetString(last_name[1], STR_VEHICLE_NAME, lastof(last_name[1]));
	}

	int r = strcmp(last_name[0], last_name[1]);
	return (r != 0) ? r : VehicleNumberSorter(a, b);
}

/** Sort vehicles by their age */
static int CDECL VehicleAgeSorter(const Vehicle * const *a, const Vehicle * const *b)
{
	int r = (*a)->age - (*b)->age;
	return (r != 0) ? r : VehicleNumberSorter(a, b);
}

/** Sort vehicles by this year profit */
static int CDECL VehicleProfitThisYearSorter(const Vehicle * const *a, const Vehicle * const *b)
{
	int r = ClampToI32((*a)->GetDisplayProfitThisYear() - (*b)->GetDisplayProfitThisYear());
	return (r != 0) ? r : VehicleNumberSorter(a, b);
}

/** Sort vehicles by last year profit */
static int CDECL VehicleProfitLastYearSorter(const Vehicle * const *a, const Vehicle * const *b)
{
	int r = ClampToI32((*a)->GetDisplayProfitLastYear() - (*b)->GetDisplayProfitLastYear());
	return (r != 0) ? r : VehicleNumberSorter(a, b);
}

/** Sort vehicles by their cargo */
static int CDECL VehicleCargoSorter(const Vehicle * const *a, const Vehicle * const *b)
{
	const Vehicle *v;
	CargoArray diff;

	/* Append the cargo of the connected weagons */
	for (v = *a; v != NULL; v = v->Next()) diff[v->cargo_type] += v->cargo_cap;
	for (v = *b; v != NULL; v = v->Next()) diff[v->cargo_type] -= v->cargo_cap;

	int r = 0;
	for (CargoID i = 0; i < NUM_CARGO; i++) {
		r = diff[i];
		if (r != 0) break;
	}

	return (r != 0) ? r : VehicleNumberSorter(a, b);
}

/** Sort vehicles by their reliability */
static int CDECL VehicleReliabilitySorter(const Vehicle * const *a, const Vehicle * const *b)
{
	int r = (*a)->reliability - (*b)->reliability;
	return (r != 0) ? r : VehicleNumberSorter(a, b);
}

/** Sort vehicles by their max speed */
static int CDECL VehicleMaxSpeedSorter(const Vehicle * const *a, const Vehicle * const *b)
{
	int r = 0;
	if ((*a)->type == VEH_TRAIN && (*b)->type == VEH_TRAIN) {
		r = Train::From(*a)->tcache.cached_max_speed - Train::From(*b)->tcache.cached_max_speed;
	} else {
		r = (*a)->max_speed - (*b)->max_speed;
	}
	return (r != 0) ? r : VehicleNumberSorter(a, b);
}

/** Sort vehicles by model */
static int CDECL VehicleModelSorter(const Vehicle * const *a, const Vehicle * const *b)
{
	int r = (*a)->engine_type - (*b)->engine_type;
	return (r != 0) ? r : VehicleNumberSorter(a, b);
}

/** Sort vehciles by their value */
static int CDECL VehicleValueSorter(const Vehicle * const *a, const Vehicle * const *b)
{
	const Vehicle *u;
	Money diff = 0;

	for (u = *a; u != NULL; u = u->Next()) diff += u->value;
	for (u = *b; u != NULL; u = u->Next()) diff -= u->value;

	int r = ClampToI32(diff);
	return (r != 0) ? r : VehicleNumberSorter(a, b);
}

/** Sort vehicles by their length */
static int CDECL VehicleLengthSorter(const Vehicle * const *a, const Vehicle * const *b)
{
	int r = 0;
	switch ((*a)->type) {
		case VEH_TRAIN:
			r = Train::From(*a)->tcache.cached_total_length - Train::From(*b)->tcache.cached_total_length;
			break;

		case VEH_ROAD: {
			const RoadVehicle *u;
			for (u = RoadVehicle::From(*a); u != NULL; u = u->Next()) r += u->rcache.cached_veh_length;
			for (u = RoadVehicle::From(*b); u != NULL; u = u->Next()) r -= u->rcache.cached_veh_length;
		} break;

		default: NOT_REACHED();
	}
	return (r != 0) ? r : VehicleNumberSorter(a, b);
}

/** Sort vehicles by the time they can still live */
static int CDECL VehicleTimeToLiveSorter(const Vehicle * const *a, const Vehicle * const *b)
{
	int r = ClampToI32(((*a)->max_age - (*a)->age) - ((*b)->max_age - (*b)->age));
	return (r != 0) ? r : VehicleNumberSorter(a, b);
}

/** Sort vehicles by the timetable delay */
static int CDECL VehicleTimetableDelaySorter(const Vehicle * const *a, const Vehicle * const *b)
{
	int r = (*a)->lateness_counter - (*b)->lateness_counter;
	return (r != 0) ? r : VehicleNumberSorter(a, b);
}

void InitializeGUI()
{
	MemSetT(&_sorting, 0);
}

/**
 * Assign a vehicle window a new vehicle
 * @param window_class WindowClass to search for
 * @param from_index the old vehicle ID
 * @param to_index the new vehicle ID
 */
static inline void ChangeVehicleWindow(WindowClass window_class, VehicleID from_index, VehicleID to_index)
{
	Window *w = FindWindowById(window_class, from_index);
	if (w != NULL) {
		w->window_number = to_index;
		if (w->viewport != NULL) w->viewport->follow_vehicle = to_index;
		if (to_index != INVALID_VEHICLE) w->InvalidateData();
	}
}

/**
 * Report a change in vehicle IDs (due to autoreplace) to affected vehicle windows.
 * @param from_index the old vehicle ID
 * @param to_index the new vehicle ID
 */
void ChangeVehicleViewWindow(VehicleID from_index, VehicleID to_index)
{
	ChangeVehicleWindow(WC_VEHICLE_VIEW,      from_index, to_index);
	ChangeVehicleWindow(WC_VEHICLE_ORDERS,    from_index, to_index);
	ChangeVehicleWindow(WC_VEHICLE_REFIT,     from_index, to_index);
	ChangeVehicleWindow(WC_VEHICLE_DETAILS,   from_index, to_index);
	ChangeVehicleWindow(WC_VEHICLE_TIMETABLE, from_index, to_index);
}

enum VehicleListWindowWidgets {
	VLW_WIDGET_CLOSEBOX = 0,
	VLW_WIDGET_CAPTION,
	VLW_WIDGET_STICKY,
	VLW_WIDGET_SORT_ORDER,
	VLW_WIDGET_SORT_BY_PULLDOWN,
	VLW_WIDGET_EMPTY_TOP_RIGHT,
	VLW_WIDGET_LIST,
	VLW_WIDGET_SCROLLBAR,
	VLW_WIDGET_OTHER_COMPANY_FILLER,
	VLW_WIDGET_AVAILABLE_VEHICLES,
	VLW_WIDGET_MANAGE_VEHICLES_DROPDOWN,
	VLW_WIDGET_STOP_ALL,
	VLW_WIDGET_START_ALL,
	VLW_WIDGET_EMPTY_BOTTOM_RIGHT,
	VLW_WIDGET_RESIZE,
};

static const Widget _vehicle_list_widgets[] = {
	{   WWT_CLOSEBOX,   RESIZE_NONE,  COLOUR_GREY,     0,    10,     0,    13, STR_BLACK_CROSS,      STR_TOOLTIP_CLOSE_WINDOW},
	{    WWT_CAPTION,  RESIZE_RIGHT,  COLOUR_GREY,    11,   247,     0,    13, 0x0,                  STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS},
	{  WWT_STICKYBOX,     RESIZE_LR,  COLOUR_GREY,   248,   259,     0,    13, 0x0,                  STR_TOOLTIP_STICKY},
	{ WWT_PUSHTXTBTN,   RESIZE_NONE,  COLOUR_GREY,     0,    80,    14,    25, STR_BUTTON_SORT_BY,          STR_TOOLTIP_SORT_ORDER},
	{   WWT_DROPDOWN,   RESIZE_NONE,  COLOUR_GREY,    81,   247,    14,    25, 0x0,                  STR_TOOLTIP_SORT_CRITERIAP},
	{      WWT_PANEL,  RESIZE_RIGHT,  COLOUR_GREY,   248,   259,    14,    25, 0x0,                  STR_NULL},
	{     WWT_MATRIX,     RESIZE_RB,  COLOUR_GREY,     0,   247,    26,   181, 0x0,                  STR_NULL},
	{  WWT_SCROLLBAR,    RESIZE_LRB,  COLOUR_GREY,   248,   259,    26,   181, 0x0,                  STR_TOOLTIP_VSCROLL_BAR_SCROLLS_LIST},
	/* Widget to be shown for other companies hiding the following 6 widgets */
	{      WWT_PANEL,    RESIZE_RTB,  COLOUR_GREY,     0,   247,   182,   193, 0x0,                  STR_NULL},

	{ WWT_PUSHTXTBTN,     RESIZE_TB,  COLOUR_GREY,     0,   105,   182,   193, 0x0,                  STR_VEHICLE_LIST_AVAILABLE_ENGINES_TOOLTIP},
	{   WWT_DROPDOWN,     RESIZE_TB,  COLOUR_GREY,   106,   223,   182,   193, STR_VEHICLE_LIST_MANAGE_LIST,      STR_VEHICLE_LIST_MANAGE_LIST_TOOLTIP},

	{ WWT_PUSHIMGBTN,     RESIZE_TB,  COLOUR_GREY,   224,   235,   182,   193, SPR_FLAG_VEH_STOPPED, STR_VEHICLE_LIST_MASS_STOP_LIST_TOOLTIP},
	{ WWT_PUSHIMGBTN,     RESIZE_TB,  COLOUR_GREY,   236,   247,   182,   193, SPR_FLAG_VEH_RUNNING, STR_VEHICLE_LIST_MASS_START_LIST_TOOLTIP},
	{      WWT_PANEL,    RESIZE_RTB,  COLOUR_GREY,   248,   247,   182,   193, 0x0,                  STR_NULL},
	{  WWT_RESIZEBOX,   RESIZE_LRTB,  COLOUR_GREY,   248,   259,   182,   193, 0x0,                  STR_TOOLTIP_RESIZE},
	{   WIDGETS_END},
};

static const NWidgetPart _nested_vehicle_list[] = {
	NWidget(NWID_HORIZONTAL),
		NWidget(WWT_CLOSEBOX, COLOUR_GREY, VLW_WIDGET_CLOSEBOX),
		NWidget(WWT_CAPTION, COLOUR_GREY, VLW_WIDGET_CAPTION), SetMinimalSize(237, 14), SetDataTip(0x0, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
		NWidget(WWT_STICKYBOX, COLOUR_GREY, VLW_WIDGET_STICKY),
	EndContainer(),

	NWidget(NWID_HORIZONTAL),
		NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, VLW_WIDGET_SORT_ORDER), SetMinimalSize(81, 12), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
		NWidget(WWT_DROPDOWN, COLOUR_GREY, VLW_WIDGET_SORT_BY_PULLDOWN), SetMinimalSize(167, 12), SetDataTip(0x0, STR_TOOLTIP_SORT_CRITERIAP),
		NWidget(WWT_PANEL, COLOUR_GREY, VLW_WIDGET_EMPTY_TOP_RIGHT), SetMinimalSize(12, 12), SetResize(1, 0),
		EndContainer(),
	EndContainer(),

	NWidget(NWID_HORIZONTAL),
		NWidget(WWT_MATRIX, COLOUR_GREY, VLW_WIDGET_LIST), SetMinimalSize(248, 156), SetResize(1,1), // vertical resize step size will be modified
		NWidget(WWT_SCROLLBAR, COLOUR_GREY, VLW_WIDGET_SCROLLBAR), SetMinimalSize(12, 156),
	EndContainer(),

	/* Widget to be shown for other companies hiding the following 6 widgets */
	NWidget(NWID_HORIZONTAL),
		NWidget(WWT_PANEL, COLOUR_GREY, VLW_WIDGET_OTHER_COMPANY_FILLER),
			NWidget(NWID_HORIZONTAL),
				NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, VLW_WIDGET_AVAILABLE_VEHICLES), SetMinimalSize(106, 12),
								SetDataTip(0x0, STR_VEHICLE_LIST_AVAILABLE_ENGINES_TOOLTIP),
				NWidget(WWT_DROPDOWN, COLOUR_GREY, VLW_WIDGET_MANAGE_VEHICLES_DROPDOWN), SetMinimalSize(118, 12),
								SetDataTip(STR_VEHICLE_LIST_MANAGE_LIST, STR_VEHICLE_LIST_MANAGE_LIST_TOOLTIP),
				NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, VLW_WIDGET_STOP_ALL), SetMinimalSize(12, 12),
								SetDataTip(SPR_FLAG_VEH_STOPPED, STR_VEHICLE_LIST_MASS_STOP_LIST_TOOLTIP),
				NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, VLW_WIDGET_START_ALL), SetMinimalSize(12, 12),
								SetDataTip(SPR_FLAG_VEH_RUNNING, STR_VEHICLE_LIST_MASS_START_LIST_TOOLTIP),
				NWidget(WWT_PANEL, COLOUR_GREY, VLW_WIDGET_EMPTY_BOTTOM_RIGHT), SetMinimalSize(0, 12), SetResize(1, 0),
				EndContainer(),
			EndContainer(),
		EndContainer(),
		NWidget(WWT_RESIZEBOX, COLOUR_GREY, VLW_WIDGET_RESIZE),
	EndContainer(),
};

static void DrawSmallOrderList(const Vehicle *v, int left, int right, int y)
{
	const Order *order;
	int sel, i = 0;

	sel = v->cur_order_index;

	FOR_VEHICLE_ORDERS(v, order) {
		if (sel == 0) DrawString(left - 6, left, y, STR_TINY_RIGHT_ARROW, TC_BLACK);
		sel--;

		if (order->IsType(OT_GOTO_STATION)) {
			SetDParam(0, order->GetDestination());
			DrawString(left, right, y, STR_TINY_BLACK_STATION);

			y += 6;
			if (++i == 4) break;
		}
	}
}

/**
 * Draws an image of a vehicle chain
 * @param v Front vehicle
 * @param x x Position to start at
 * @param y y Position to draw at
 * @param selection Selected vehicle to draw a frame around
 * @param max_width Number of pixels space for drawing
 * @param skip Number of pixels to skip at the front (for scrolling)
 */
static void DrawVehicleImage(const Vehicle *v, int x, int y, VehicleID selection, int max_width, int skip)
{
	switch (v->type) {
		case VEH_TRAIN:    DrawTrainImage(Train::From(v), x, y, selection, max_width, skip); break;
		case VEH_ROAD:     DrawRoadVehImage(v, x, y, selection, max_width);     break;
		case VEH_SHIP:     DrawShipImage(v, x, y, selection);                   break;
		case VEH_AIRCRAFT: DrawAircraftImage(v, x, y, selection);               break;
		default: NOT_REACHED();
	}
}

/**
 * Draw all the vehicle list items.
 * @param selected_vehicle the vehicle that is to be selected
 */
void BaseVehicleListWindow::DrawVehicleListItems(VehicleID selected_vehicle)
{
	int left = this->widget[VLW_WIDGET_LIST].left + WD_MATRIX_LEFT;
	int right = this->widget[VLW_WIDGET_LIST].right - WD_MATRIX_RIGHT;
	int y = PLY_WND_PRC__OFFSET_TOP_WIDGET;
	uint max = min(this->vscroll.GetPosition() + this->vscroll.GetCapacity(), this->vehicles.Length());
	for (uint i = this->vscroll.GetPosition(); i < max; ++i) {
		const Vehicle *v = this->vehicles[i];
		StringID str;

		SetDParam(0, v->GetDisplayProfitThisYear());
		SetDParam(1, v->GetDisplayProfitLastYear());

		DrawVehicleImage(v, left + 19, y + 5, selected_vehicle, right - left + 1 - 19, 0);
		DrawString(left + 19, right, y + this->resize.step_height - 8, STR_VEHICLE_LIST_PROFIT_THIS_YEAR_LAST_YEAR);

		if (v->name != NULL) {
			/* The vehicle got a name so we will print it */
			SetDParam(0, v->index);
			DrawString(left + 19, right, y, STR_TINY_BLACK_VEHICLE);
		} else if (v->group_id != DEFAULT_GROUP) {
			/* The vehicle has no name, but is member of a group, so print group name */
			SetDParam(0, v->group_id);
			DrawString(left + 19, right, y, STR_TINY_GROUP, TC_BLACK);
		}

		if (this->resize.step_height == PLY_WND_PRC__SIZE_OF_ROW_BIG) DrawSmallOrderList(v, left + 138, right, y);

		if (v->IsInDepot()) {
			str = STR_BLUE_COMMA;
		} else {
			str = (v->age > v->max_age - DAYS_IN_LEAP_YEAR) ? STR_RED_COMMA : STR_BLACK_COMMA;
		}

		SetDParam(0, v->unitnumber);
		DrawString(left, right, y + 2, str);

		DrawVehicleProfitButton(v, left, y + 13);

		y += this->resize.step_height;
	}
}

/**
 * Window for the (old) vehicle listing.
 *
 * bitmask for w->window_number
 * 0-7 CompanyID (owner)
 * 8-10 window type (use flags in vehicle_gui.h)
 * 11-15 vehicle type (using VEH_, but can be compressed to fewer bytes if needed)
 * 16-31 StationID or OrderID depending on window type (bit 8-10)
 */
struct VehicleListWindow : public BaseVehicleListWindow {

	VehicleListWindow(const WindowDesc *desc, WindowNumber window_number) : BaseVehicleListWindow(desc, window_number)
	{
		uint16 window_type = this->window_number & VLW_MASK;
		CompanyID company = (CompanyID)GB(this->window_number, 0, 8);

		this->vehicle_type = (VehicleType)GB(this->window_number, 11, 5);
		this->owner = company;

		/* Set up the window widgets */
		this->widget[VLW_WIDGET_LIST].tooltips           = STR_VEHICLE_LIST_TRAIN_LIST_TOOLTIP + this->vehicle_type;
		this->widget[VLW_WIDGET_AVAILABLE_VEHICLES].data = STR_VEHICLE_LIST_AVAILABLE_TRAINS + this->vehicle_type;

		if (window_type == VLW_SHARED_ORDERS) {
			this->widget[VLW_WIDGET_CAPTION].data = STR_VEHICLE_LIST_SHARED_ORDERS_LIST_CAPTION;
		} else {
			this->widget[VLW_WIDGET_CAPTION].data = STR_VEHICLE_LIST_TRAIN_CAPTION + this->vehicle_type;
		}

		switch (this->vehicle_type) {
			case VEH_TRAIN:
				this->resize.step_width = 1;
				/* Fallthrough */
			case VEH_ROAD:
				this->vscroll.SetCapacity(6);
				this->resize.step_height = PLY_WND_PRC__SIZE_OF_ROW_SMALL;
				break;
			case VEH_SHIP:
			case VEH_AIRCRAFT:
				this->vscroll.SetCapacity(4);
				this->resize.step_height = PLY_WND_PRC__SIZE_OF_ROW_BIG;
				break;
			default: NOT_REACHED();
		}


		this->widget[VLW_WIDGET_LIST].data = (this->vscroll.GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);

		/* Set up sorting. Make the window-specific _sorting variable
		 * point to the correct global _sorting struct so we are freed
		 * from having conditionals during window operation */
		switch (this->vehicle_type) {
			case VEH_TRAIN:    this->sorting = &_sorting.train; break;
			case VEH_ROAD:     this->sorting = &_sorting.roadveh; break;
			case VEH_SHIP:     this->sorting = &_sorting.ship; break;
			case VEH_AIRCRAFT: this->sorting = &_sorting.aircraft; break;
			default: NOT_REACHED();
		}

		this->vehicles.SetListing(*this->sorting);
		this->vehicles.ForceRebuild();
		this->vehicles.NeedResort();

		this->FindWindowPlacementAndResize(desc);
		if (this->vehicle_type == VEH_TRAIN) ResizeWindow(this, 65, 0);
	}

	~VehicleListWindow()
	{
		*this->sorting = this->vehicles.GetListing();
	}

	virtual void OnPaint()
	{
		const Owner owner = this->owner;
		const uint16 window_type = this->window_number & VLW_MASK;
		const uint16 index = GB(this->window_number, 16, 16);

		this->BuildVehicleList(owner, index, window_type);
		this->SortVehicleList();

		if (this->vehicles.Length() == 0) HideDropDownMenu(this);

		/* draw the widgets */
		switch (window_type) {
			case VLW_SHARED_ORDERS: // Shared Orders
				if (this->vehicles.Length() == 0) {
					/* We can't open this window without vehicles using this order
					 * and we should close the window when deleting the order      */
					NOT_REACHED();
				}
				SetDParam(0, this->vscroll.GetCount());
				break;

			case VLW_STANDARD: // Company Name
				SetDParam(0, STR_COMPANY_NAME);
				SetDParam(1, owner);
				SetDParam(2, this->vscroll.GetCount());
				break;

			case VLW_WAYPOINT_LIST:
				SetDParam(0, STR_WAYPOINT_NAME);
				SetDParam(1, index);
				SetDParam(2, this->vscroll.GetCount());
				break;

			case VLW_STATION_LIST: // Station Name
				SetDParam(0, STR_STATION_NAME);
				SetDParam(1, index);
				SetDParam(2, this->vscroll.GetCount());
				break;

			case VLW_DEPOT_LIST:
				SetDParam(0, STR_DEPOT_TRAIN_CAPTION + this->vehicle_type);
				if (this->vehicle_type == VEH_AIRCRAFT) {
					SetDParam(1, index); // Airport name
				} else {
					SetDParam(1, Depot::Get(index)->town_index);
				}
				SetDParam(2, this->vscroll.GetCount());
				break;
			default: NOT_REACHED();
		}

		/* Hide the widgets that we will not use in this window
		 * Some windows contains actions only fit for the owner */
		this->SetWidgetsHiddenState(this->owner != _local_company,
			VLW_WIDGET_AVAILABLE_VEHICLES,
			VLW_WIDGET_MANAGE_VEHICLES_DROPDOWN,
			VLW_WIDGET_STOP_ALL,
			VLW_WIDGET_START_ALL,
			VLW_WIDGET_EMPTY_BOTTOM_RIGHT,
			WIDGET_LIST_END);
		this->SetWidgetHiddenState(VLW_WIDGET_OTHER_COMPANY_FILLER, this->owner == _local_company);
		if (this->owner == _local_company) {
			this->SetWidgetDisabledState(VLW_WIDGET_AVAILABLE_VEHICLES, window_type != VLW_STANDARD);
			this->SetWidgetsDisabledState(this->vehicles.Length() == 0,
				VLW_WIDGET_MANAGE_VEHICLES_DROPDOWN,
				VLW_WIDGET_STOP_ALL,
				VLW_WIDGET_START_ALL,
				WIDGET_LIST_END);
		}


		/* Set text of sort by dropdown widget. */
		this->widget[VLW_WIDGET_SORT_BY_PULLDOWN].data = this->vehicle_sorter_names[this->vehicles.SortType()];

		this->DrawWidgets();

		/* draw arrow pointing up/down for ascending/descending sorting */
		this->DrawSortButtonState(VLW_WIDGET_SORT_ORDER, this->vehicles.IsDescSortOrder() ? SBS_DOWN : SBS_UP);

		this->DrawVehicleListItems(INVALID_VEHICLE);
	}

	virtual void OnClick(Point pt, int widget)
	{
		switch (widget) {
			case VLW_WIDGET_SORT_ORDER: // Flip sorting method ascending/descending
				this->vehicles.ToggleSortOrder();
				this->SetDirty();
				break;
			case VLW_WIDGET_SORT_BY_PULLDOWN:// Select sorting criteria dropdown menu
				ShowDropDownMenu(this, this->vehicle_sorter_names, this->vehicles.SortType(), VLW_WIDGET_SORT_BY_PULLDOWN, 0, (this->vehicle_type == VEH_TRAIN || this->vehicle_type == VEH_ROAD) ? 0 : (1 << 10));
				return;
			case VLW_WIDGET_LIST: { // Matrix to show vehicles
				uint32 id_v = (pt.y - PLY_WND_PRC__OFFSET_TOP_WIDGET) / this->resize.step_height;
				const Vehicle *v;

				if (id_v >= this->vscroll.GetCapacity()) return; // click out of bounds

				id_v += this->vscroll.GetPosition();

				if (id_v >= this->vehicles.Length()) return; // click out of list bound

				v = this->vehicles[id_v];

				ShowVehicleViewWindow(v);
			} break;

			case VLW_WIDGET_AVAILABLE_VEHICLES:
				ShowBuildVehicleWindow(INVALID_TILE, this->vehicle_type);
				break;

			case VLW_WIDGET_MANAGE_VEHICLES_DROPDOWN: {
				static StringID action_str[] = {
					STR_VEHICLE_LIST_REPLACE_VEHICLES,
					STR_VEHICLE_LIST_SEND_FOR_SERVICING,
					STR_NULL,
					INVALID_STRING_ID
				};

				static const StringID depot_name[] = {
					STR_VEHICLE_LIST_SEND_TRAIN_TO_DEPOT,
					STR_VEHICLE_LIST_SEND_ROAD_VEHICLE_TO_DEPOT,
					STR_VEHICLE_LIST_SEND_SHIP_TO_DEPOT,
					STR_VEHICLE_LIST_SEND_AIRCRAFT_TO_HANGAR
				};

				/* XXX - Substite string since the dropdown cannot handle dynamic strings */
				action_str[2] = depot_name[this->vehicle_type];
				ShowDropDownMenu(this, action_str, 0, VLW_WIDGET_MANAGE_VEHICLES_DROPDOWN, 0, (this->window_number & VLW_MASK) == VLW_STANDARD ? 0 : 1);
				break;
			}

			case VLW_WIDGET_STOP_ALL:
			case VLW_WIDGET_START_ALL:
				DoCommandP(0, GB(this->window_number, 16, 16), (this->window_number & VLW_MASK) | (1 << 6) | (widget == VLW_WIDGET_START_ALL ? (1 << 5) : 0) | this->vehicle_type, CMD_MASS_START_STOP);
				break;
		}
	}

	virtual void OnDropdownSelect(int widget, int index)
	{
		switch (widget) {
			case VLW_WIDGET_SORT_BY_PULLDOWN:
				this->vehicles.SetSortType(index);
				break;
			case VLW_WIDGET_MANAGE_VEHICLES_DROPDOWN:
				assert(this->vehicles.Length() != 0);

				switch (index) {
					case 0: // Replace window
						ShowReplaceGroupVehicleWindow(DEFAULT_GROUP, this->vehicle_type);
						break;
					case 1: // Send for servicing
						DoCommandP(0, GB(this->window_number, 16, 16) /* StationID or OrderID (depending on VLW) */,
							(this->window_number & VLW_MASK) | DEPOT_MASS_SEND | DEPOT_SERVICE,
							GetCmdSendToDepot(this->vehicle_type));
						break;
					case 2: // Send to Depots
						DoCommandP(0, GB(this->window_number, 16, 16) /* StationID or OrderID (depending on VLW) */,
							(this->window_number & VLW_MASK) | DEPOT_MASS_SEND,
							GetCmdSendToDepot(this->vehicle_type));
						break;

					default: NOT_REACHED();
				}
				break;
			default: NOT_REACHED();
		}
		this->SetDirty();
	}

	virtual void OnTick()
	{
		if (_pause_mode != PM_UNPAUSED) return;
		if (this->vehicles.NeedResort()) {
			StationID station = ((this->window_number & VLW_MASK) == VLW_STATION_LIST) ? GB(this->window_number, 16, 16) : INVALID_STATION;

			DEBUG(misc, 3, "Periodic resort %d list company %d at station %d", this->vehicle_type, this->owner, station);
			this->SetDirty();
		}
	}

	virtual void OnResize(Point delta)
	{
		this->vscroll.UpdateCapacity(delta.y / (int)this->resize.step_height);
		this->widget[VLW_WIDGET_LIST].data = (this->vscroll.GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
	}

	virtual void OnInvalidateData(int data)
	{
		if (HasBit(data, 15) && (this->window_number & VLW_MASK) == VLW_SHARED_ORDERS) {
			SB(this->window_number, 16, 16, GB(data, 16, 16));
			this->vehicles.ForceRebuild();
			return;
		}

		if (data == 0) {
			this->vehicles.ForceRebuild();
		} else {
			this->vehicles.ForceResort();
		}
	}
};

static WindowDesc _vehicle_list_desc(
	WDP_AUTO, WDP_AUTO, 260, 194, 260, 246,
	WC_INVALID, WC_NONE,
	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
	_vehicle_list_widgets,
	_nested_vehicle_list, lengthof(_nested_vehicle_list)
);

static void ShowVehicleListWindowLocal(CompanyID company, uint16 VLW_flag, VehicleType vehicle_type, uint16 unique_number)
{
	if (!Company::IsValidID(company)) return;

	_vehicle_list_desc.cls = GetWindowClassForVehicleType(vehicle_type);
	WindowNumber num = (unique_number << 16) | (vehicle_type << 11) | VLW_flag | company;
	AllocateWindowDescFront<VehicleListWindow>(&_vehicle_list_desc, num);
}

void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type)
{
	/* If _settings_client.gui.advanced_vehicle_list > 1, display the Advanced list
	 * if _settings_client.gui.advanced_vehicle_list == 1, display Advanced list only for local company
	 * if _ctrl_pressed, do the opposite action (Advanced list x Normal list)
	 */

	if ((_settings_client.gui.advanced_vehicle_list > (uint)(company != _local_company)) != _ctrl_pressed) {
		ShowCompanyGroup(company, vehicle_type);
	} else {
		ShowVehicleListWindowLocal(company, VLW_STANDARD, vehicle_type, 0);
	}
}

void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, const Waypoint *wp)
{
	if (wp == NULL) return;
	ShowVehicleListWindowLocal(company, VLW_WAYPOINT_LIST, vehicle_type, wp->index);
}

void ShowVehicleListWindow(const Vehicle *v)
{
	ShowVehicleListWindowLocal(v->owner, VLW_SHARED_ORDERS, v->type, v->FirstShared()->index);
}

void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, StationID station)
{
	ShowVehicleListWindowLocal(company, VLW_STATION_LIST, vehicle_type, station);
}

void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, TileIndex depot_tile)
{
	uint16 depot_airport_index;

	if (vehicle_type == VEH_AIRCRAFT) {
		depot_airport_index = GetStationIndex(depot_tile);
	} else {
		depot_airport_index = GetDepotIndex(depot_tile);
	}
	ShowVehicleListWindowLocal(company, VLW_DEPOT_LIST, vehicle_type, depot_airport_index);
}


/* Unified vehicle GUI - Vehicle Details Window */

/** Constants of vehicle details widget indices */
enum VehicleDetailsWindowWidgets {
	VLD_WIDGET_CLOSEBOX = 0,
	VLD_WIDGET_CAPTION,
	VLD_WIDGET_RENAME_VEHICLE,
	VLD_WIDGET_STICKY,
	VLD_WIDGET_TOP_DETAILS,
	VLD_WIDGET_INCREASE_SERVICING_INTERVAL,
	VLD_WIDGET_DECREASE_SERVICING_INTERVAL,
	VLD_WIDGET_BOTTOM_RIGHT,
	VLD_WIDGET_MIDDLE_DETAILS,
	VLD_WIDGET_SCROLLBAR,
	VLD_WIDGET_DETAILS_CARGO_CARRIED,
	VLD_WIDGET_DETAILS_TRAIN_VEHICLES,
	VLD_WIDGET_DETAILS_CAPACITY_OF_EACH,
	VLD_WIDGET_DETAILS_TOTAL_CARGO,
	VLD_WIDGET_RESIZE,
};

assert_compile(VLD_WIDGET_DETAILS_CARGO_CARRIED    == VLD_WIDGET_DETAILS_CARGO_CARRIED + TDW_TAB_CARGO   );
assert_compile(VLD_WIDGET_DETAILS_TRAIN_VEHICLES   == VLD_WIDGET_DETAILS_CARGO_CARRIED + TDW_TAB_INFO    );
assert_compile(VLD_WIDGET_DETAILS_CAPACITY_OF_EACH == VLD_WIDGET_DETAILS_CARGO_CARRIED + TDW_TAB_CAPACITY);
assert_compile(VLD_WIDGET_DETAILS_TOTAL_CARGO      == VLD_WIDGET_DETAILS_CARGO_CARRIED + TDW_TAB_TOTALS  );

/** Vehicle details widgets. */
static const Widget _vehicle_details_widgets[] = {
	{   WWT_CLOSEBOX,   RESIZE_NONE,  COLOUR_GREY,   0,  10,   0,  13, STR_BLACK_CROSS,                    STR_TOOLTIP_CLOSE_WINDOW},                      // VLD_WIDGET_CLOSEBOX
	{    WWT_CAPTION,  RESIZE_RIGHT,  COLOUR_GREY,  11, 352,   0,  13, STR_VEHICLE_DETAILS_CAPTION,        STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS},            // VLD_WIDGET_CAPTION
	{ WWT_PUSHTXTBTN,     RESIZE_LR,  COLOUR_GREY, 353, 392,   0,  13, STR_VEHICLE_NAME_BUTTON,            STR_NULL /* filled in later */},                // VLD_WIDGET_RENAME_VEHICLE
	{  WWT_STICKYBOX,     RESIZE_LR,  COLOUR_GREY, 393, 404,   0,  13, STR_NULL,                           STR_TOOLTIP_STICKY},                             // VLD_WIDGET_STICKY
	{      WWT_PANEL,  RESIZE_RIGHT,  COLOUR_GREY,   0, 404,  14,  55, 0x0,                                STR_NULL},                                      // VLD_WIDGET_TOP_DETAILS
	{ WWT_PUSHTXTBTN,     RESIZE_TB,  COLOUR_GREY,   0,  10, 101, 106, STR_BLACK_SMALL_ARROW_UP,           STR_VEHICLE_DETAILS_INCREASE_SERVICING_INTERVAL_TOOLTIP},   // VLD_WIDGET_INCREASE_SERVICING_INTERVAL
	{ WWT_PUSHTXTBTN,     RESIZE_TB,  COLOUR_GREY,   0,  10, 107, 112, STR_BLACK_SMALL_ARROW_DOWN,         STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP},   // VLD_WIDGET_DECREASE_SERVICING_INTERVAL
	{      WWT_PANEL,    RESIZE_RTB,  COLOUR_GREY,  11, 404, 101, 112, 0x0,                                STR_NULL},                                      // VLD_WIDGET_BOTTOM_RIGHT
	{     WWT_MATRIX,     RESIZE_RB,  COLOUR_GREY,   0, 392,  56, 100, 0x701,                              STR_NULL},                                      // VLD_WIDGET_MIDDLE_DETAILS
	{  WWT_SCROLLBAR,    RESIZE_LRB,  COLOUR_GREY, 393, 404,  56, 100, 0x0,                                STR_TOOLTIP_VSCROLL_BAR_SCROLLS_LIST},          // VLD_WIDGET_SCROLLBAR
	{ WWT_PUSHTXTBTN,     RESIZE_TB,  COLOUR_GREY,   0,  95, 113, 124, STR_VEHICLE_DETAIL_TAB_CARGO,       STR_VEHICLE_DETAILS_TRAIN_CARGO_TOOLTIP},       // VLD_WIDGET_DETAILS_CARGO_CARRIED
	{ WWT_PUSHTXTBTN,     RESIZE_TB,  COLOUR_GREY,  96, 194, 113, 124, STR_VEHICLE_DETAIL_TAB_INFORMATION, STR_VEHICLE_DETAILS_TRAIN_INFORMATION_TOOLTIP}, // VLD_WIDGET_DETAILS_TRAIN_VEHICLES
	{ WWT_PUSHTXTBTN,     RESIZE_TB,  COLOUR_GREY, 195, 293, 113, 124, STR_VEHICLE_DETAIL_TAB_CAPACITIES,  STR_VEHICLE_DETAILS_TRAIN_CAPACITIES_TOOLTIP},  // VLD_WIDGET_DETAILS_CAPACITY_OF_EACH
	{ WWT_PUSHTXTBTN,    RESIZE_RTB,  COLOUR_GREY, 294, 392, 113, 124, STR_VEHICLE_DETAIL_TAB_TOTAL_CARGO, STR_VEHICLE_DETAILS_TRAIN_TOTAL_CARGO_TOOLTIP}, // VLD_WIDGET_DETAILS_TOTAL_CARGO
	{  WWT_RESIZEBOX,   RESIZE_LRTB,  COLOUR_GREY, 393, 404, 113, 124, 0x0,                                STR_TOOLTIP_RESIZE},                             // VLD_WIDGET_RESIZE
	{   WIDGETS_END},
};

static const NWidgetPart _nested_vehicle_details_widgets[] = {
	NWidget(NWID_HORIZONTAL),
		NWidget(WWT_CLOSEBOX, COLOUR_GREY, VLD_WIDGET_CLOSEBOX),
		NWidget(WWT_CAPTION, COLOUR_GREY, VLD_WIDGET_CAPTION), SetDataTip(STR_VEHICLE_DETAILS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
		NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, VLD_WIDGET_RENAME_VEHICLE), SetMinimalSize(40, 14), SetDataTip(STR_VEHICLE_NAME_BUTTON, STR_NULL /* filled in later */),
		NWidget(WWT_STICKYBOX, COLOUR_GREY, VLD_WIDGET_STICKY),
	EndContainer(),
	NWidget(WWT_PANEL, COLOUR_GREY, VLD_WIDGET_TOP_DETAILS), SetResize(1, 0), SetMinimalSize(405, 42), EndContainer(),
	NWidget(NWID_HORIZONTAL),
		NWidget(WWT_MATRIX, COLOUR_GREY, VLD_WIDGET_MIDDLE_DETAILS), SetResize(1, 1), SetMinimalSize(393, 45), SetDataTip(0x701, STR_NULL),
		NWidget(WWT_SCROLLBAR, COLOUR_GREY, VLD_WIDGET_SCROLLBAR),
	EndContainer(),
	NWidget(NWID_HORIZONTAL),
		NWidget(NWID_VERTICAL),
			NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, VLD_WIDGET_INCREASE_SERVICING_INTERVAL), SetMinimalSize(11, 6), SetDataTip(STR_BLACK_SMALL_ARROW_UP, STR_VEHICLE_DETAILS_INCREASE_SERVICING_INTERVAL_TOOLTIP),
			NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, VLD_WIDGET_DECREASE_SERVICING_INTERVAL), SetMinimalSize(11, 6), SetDataTip(STR_BLACK_SMALL_ARROW_DOWN, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
		EndContainer(),
		NWidget(WWT_PANEL, COLOUR_GREY, VLD_WIDGET_BOTTOM_RIGHT), SetFill(true, true), SetResize(1, 0), EndContainer(),
	EndContainer(),
	NWidget(NWID_HORIZONTAL),
		NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, VLD_WIDGET_DETAILS_CARGO_CARRIED), SetMinimalSize(96, 12), SetDataTip(STR_VEHICLE_DETAIL_TAB_CARGO, STR_VEHICLE_DETAILS_TRAIN_CARGO_TOOLTIP),
		NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, VLD_WIDGET_DETAILS_TRAIN_VEHICLES), SetMinimalSize(99, 12), SetDataTip(STR_VEHICLE_DETAIL_TAB_INFORMATION, STR_VEHICLE_DETAILS_TRAIN_INFORMATION_TOOLTIP),
		NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, VLD_WIDGET_DETAILS_CAPACITY_OF_EACH), SetMinimalSize(99, 12), SetDataTip(STR_VEHICLE_DETAIL_TAB_CAPACITIES, STR_VEHICLE_DETAILS_TRAIN_CAPACITIES_TOOLTIP),
		NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, VLD_WIDGET_DETAILS_TOTAL_CARGO), SetMinimalSize(99, 12), SetDataTip(STR_VEHICLE_DETAIL_TAB_TOTAL_CARGO, STR_VEHICLE_DETAILS_TRAIN_TOTAL_CARGO_TOOLTIP), SetResize(1, 0),
		NWidget(WWT_RESIZEBOX, COLOUR_GREY, VLD_WIDGET_RESIZE),
	EndContainer(),
};


extern int GetTrainDetailsWndVScroll(VehicleID veh_id, TrainDetailsWindowTabs det_tab);
extern void DrawTrainDetails(const Train *v, int left, int right, int y, int vscroll_pos, uint16 vscroll_cap, TrainDetailsWindowTabs det_tab);
extern void DrawRoadVehDetails(const Vehicle *v, int left, int right, int y);
extern void DrawShipDetails(const Vehicle *v, int left, int right, int y);
extern void DrawAircraftDetails(const Aircraft *v, int left, int right, int y);

struct VehicleDetailsWindow : Window {
	TrainDetailsWindowTabs tab;

	/** Initialize a newly created vehicle details window */
	VehicleDetailsWindow(const WindowDesc *desc, WindowNumber window_number) : Window(desc, window_number)
	{
		const Vehicle *v = Vehicle::Get(this->window_number);
		this->widget[VLD_WIDGET_RENAME_VEHICLE].tooltips = STR_VEHICLE_DETAILS_TRAIN_RENAME + v->type;

		switch (v->type) {
			case VEH_TRAIN:
				ResizeWindow(this, 0, 39);

				this->vscroll.SetCapacity(6);
				this->height += 12;
				this->resize.step_height = 14;
				this->resize.height = this->height - 14 * 2; // Minimum of 4 wagons in the display
				break;

			case VEH_ROAD: {
				if (!RoadVehicle::From(v)->HasArticulatedPart()) break;

				/* Draw the text under the vehicle instead of next to it, minus the
				 * height already allocated for the cargo of the first vehicle. */
				uint height_extension = 15 - 11;

				/* Add space for the cargo amount for each part. */
				for (const Vehicle *u = v; u != NULL; u = u->Next()) {
					if (u->cargo_cap != 0) height_extension += 11;
				}

				ResizeWindow(this, 0, height_extension);
			} break;

			case VEH_SHIP:
				break;

			case VEH_AIRCRAFT:
				ResizeWindow(this, 0, 11);
				break;
			default: NOT_REACHED();
		}

		if (v->type != VEH_TRAIN) {
			this->vscroll.SetCapacity(1);
			this->widget[VLD_WIDGET_MIDDLE_DETAILS].right += 12;
		}

		this->widget[VLD_WIDGET_MIDDLE_DETAILS].data = (this->vscroll.GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
		this->owner = v->owner;

		this->tab = TDW_TAB_CARGO;

		this->FindWindowPlacementAndResize(desc);
	}

	/** Checks whether service interval is enabled for the vehicle. */
	static bool IsVehicleServiceIntervalEnabled(const VehicleType vehicle_type, CompanyID company_id)
	{
		const VehicleDefaultSettings *vds = &Company::Get(company_id)->settings.vehicle;
		switch (vehicle_type) {
			default: NOT_REACHED();
			case VEH_TRAIN:    return vds->servint_trains   != 0;
			case VEH_ROAD:     return vds->servint_roadveh  != 0;
			case VEH_SHIP:     return vds->servint_ships    != 0;
			case VEH_AIRCRAFT: return vds->servint_aircraft != 0;
		}
	}

	/**
	 * Draw the details for the given vehicle at the position of the Details windows
	 *
	 * @param v     current vehicle
	 * @param left  The left most coordinate to draw
	 * @param right The right most coordinate to draw
	 * @param y     The y coordinate
	 * @param vscroll_pos Position of scrollbar (train only)
	 * @param vscroll_cap Number of lines currently displayed (train only)
	 * @param det_tab Selected details tab (train only)
	 */
	static void DrawVehicleDetails(const Vehicle *v, int left, int right, int y, int vscroll_pos, uint vscroll_cap, TrainDetailsWindowTabs det_tab)
	{
		switch (v->type) {
			case VEH_TRAIN:    DrawTrainDetails(Train::From(v), left, right, y, vscroll_pos, vscroll_cap, det_tab);  break;
			case VEH_ROAD:     DrawRoadVehDetails(v, left, right, y);  break;
			case VEH_SHIP:     DrawShipDetails(v, left, right, y);     break;
			case VEH_AIRCRAFT: DrawAircraftDetails(Aircraft::From(v), left, right, y); break;
			default: NOT_REACHED();
		}
	}

	/** Repaint vehicle details window. */
	virtual void OnPaint()
	{
		const Vehicle *v = Vehicle::Get(this->window_number);
		TrainDetailsWindowTabs det_tab = this->tab;

		this->SetWidgetDisabledState(VLD_WIDGET_RENAME_VEHICLE, v->owner != _local_company);

		if (v->type == VEH_TRAIN) {
			this->DisableWidget(det_tab + VLD_WIDGET_DETAILS_CARGO_CARRIED);
			this->vscroll.SetCount(GetTrainDetailsWndVScroll(v->index, det_tab));
		}

		this->SetWidgetsHiddenState(v->type != VEH_TRAIN,
			VLD_WIDGET_SCROLLBAR,
			VLD_WIDGET_DETAILS_CARGO_CARRIED,
			VLD_WIDGET_DETAILS_TRAIN_VEHICLES,
			VLD_WIDGET_DETAILS_CAPACITY_OF_EACH,
			VLD_WIDGET_DETAILS_TOTAL_CARGO,
			VLD_WIDGET_RESIZE,
			WIDGET_LIST_END);

		/* Disable service-scroller when interval is set to disabled */
		this->SetWidgetsDisabledState(!IsVehicleServiceIntervalEnabled(v->type, v->owner),
			VLD_WIDGET_INCREASE_SERVICING_INTERVAL,
			VLD_WIDGET_DECREASE_SERVICING_INTERVAL,
			WIDGET_LIST_END);


		SetDParam(0, v->index);
		this->DrawWidgets();

		/* Draw running cost */
		SetDParam(1, v->age / DAYS_IN_LEAP_YEAR);
		SetDParam(0, (v->age + DAYS_IN_YEAR < v->max_age) ? STR_VEHICLE_INFO_AGE : STR_VEHICLE_INFO_AGE_RED);
		SetDParam(2, v->max_age / DAYS_IN_LEAP_YEAR);
		SetDParam(3, v->GetDisplayRunningCost());
		DrawString(2, this->width - 2, 15, STR_VEHICLE_INFO_AGE_RUNNING_COST_YR);

		/* Draw max speed */
		switch (v->type) {
			case VEH_TRAIN:
				SetDParam(2, v->GetDisplayMaxSpeed());
				SetDParam(1, Train::From(v)->tcache.cached_power);
				SetDParam(0, Train::From(v)->tcache.cached_weight);
				SetDParam(3, Train::From(v)->tcache.cached_max_te / 1000);
				DrawString(2, this->width - 2, 25, (_settings_game.vehicle.train_acceleration_model != TAM_ORIGINAL && Train::From(v)->railtype != RAILTYPE_MAGLEV) ?
					STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE :
					STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED);
				break;

			case VEH_ROAD:
			case VEH_SHIP:
			case VEH_AIRCRAFT:
				SetDParam(0, v->GetDisplayMaxSpeed());
				DrawString(2, this->width - 2, 25, STR_VEHICLE_INFO_MAX_SPEED);
				break;

			default: NOT_REACHED();
		}

		/* Draw profit */
		SetDParam(0, v->GetDisplayProfitThisYear());
		SetDParam(1, v->GetDisplayProfitLastYear());
		DrawString(2, this->width - 2, 35, STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR);

		/* Draw breakdown & reliability */
		SetDParam(0, ToPercent16(v->reliability));
		SetDParam(1, v->breakdowns_since_last_service);
		DrawString(2, this->width - 2, 45, STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS);

		/* Draw service interval text */
		SetDParam(0, v->service_interval);
		SetDParam(1, v->date_of_last_service);
		DrawString(13, this->width - 2, this->height - (v->type != VEH_TRAIN ? 11 : 23), Company::Get(v->owner)->settings.vehicle.servint_ispercent ? STR_VEHICLE_DETAILS_SERVICING_INTERVAL_PERCENT : STR_VEHICLE_DETAILS_SERVICING_INTERVAL_DAYS);

		const Widget *matrix = &this->widget[VLD_WIDGET_MIDDLE_DETAILS];
		switch (v->type) {
			case VEH_TRAIN:
				DrawVehicleDetails(v, matrix->left + 2, matrix->right - 2, matrix->top + 1, this->vscroll.GetPosition(), this->vscroll.GetCapacity(), det_tab);
				break;

			case VEH_ROAD:
			case VEH_SHIP:
			case VEH_AIRCRAFT:
				DrawVehicleImage(v, matrix->left + 3, matrix->top + 1, INVALID_VEHICLE, matrix->right - matrix->left - 5, 0);
				DrawVehicleDetails(v, matrix->left + 75, matrix->right - 2, matrix->top + 1, this->vscroll.GetPosition(), this->vscroll.GetCapacity(), det_tab);
				break;

			default: NOT_REACHED();
		}
	}

	virtual void OnClick(Point pt, int widget)
	{
		switch (widget) {
			case VLD_WIDGET_RENAME_VEHICLE: {// rename
				const Vehicle *v = Vehicle::Get(this->window_number);
				SetDParam(0, v->index);
				ShowQueryString(STR_VEHICLE_NAME, STR_QUERY_RENAME_TRAIN_CAPTION + v->type, MAX_LENGTH_VEHICLE_NAME_BYTES, MAX_LENGTH_VEHICLE_NAME_PIXELS, this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT);
			} break;

			case VLD_WIDGET_INCREASE_SERVICING_INTERVAL:   // increase int
			case VLD_WIDGET_DECREASE_SERVICING_INTERVAL: { // decrease int
				int mod = _ctrl_pressed ? 5 : 10;
				const Vehicle *v = Vehicle::Get(this->window_number);

				mod = (widget == VLD_WIDGET_DECREASE_SERVICING_INTERVAL) ? -mod : mod;
				mod = GetServiceIntervalClamped(mod + v->service_interval, v->owner);
				if (mod == v->service_interval) return;

				DoCommandP(v->tile, v->index, mod, CMD_CHANGE_SERVICE_INT | CMD_MSG(STR_ERROR_CAN_T_CHANGE_SERVICING));
			} break;

			case VLD_WIDGET_DETAILS_CARGO_CARRIED:
			case VLD_WIDGET_DETAILS_TRAIN_VEHICLES:
			case VLD_WIDGET_DETAILS_CAPACITY_OF_EACH:
			case VLD_WIDGET_DETAILS_TOTAL_CARGO:
				this->SetWidgetsDisabledState(false,
					VLD_WIDGET_DETAILS_CARGO_CARRIED,
					VLD_WIDGET_DETAILS_TRAIN_VEHICLES,
					VLD_WIDGET_DETAILS_CAPACITY_OF_EACH,
					VLD_WIDGET_DETAILS_TOTAL_CARGO,
					widget,
					WIDGET_LIST_END);

				this->tab = (TrainDetailsWindowTabs)(widget - VLD_WIDGET_DETAILS_CARGO_CARRIED);
				this->SetDirty();
				break;
		}
	}

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

		DoCommandP(0, this->window_number, 0, CMD_RENAME_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_RENAME_TRAIN + Vehicle::Get(this->window_number)->type), NULL, str);
	}

	virtual void OnResize(Point delta)
	{
		if (delta.x != 0) ResizeButtons(this, VLD_WIDGET_DETAILS_CARGO_CARRIED, VLD_WIDGET_DETAILS_TOTAL_CARGO);
		if (delta.y == 0) return;

		this->vscroll.UpdateCapacity(delta.y / 14);
		this->widget[VLD_WIDGET_MIDDLE_DETAILS].data = (this->vscroll.GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
	}
};

/** Vehicle details window descriptor. */
static const WindowDesc _vehicle_details_desc(
	WDP_AUTO, WDP_AUTO, 405, 113, 405, 113,
	WC_VEHICLE_DETAILS, WC_VEHICLE_VIEW,
	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
	_vehicle_details_widgets, _nested_vehicle_details_widgets, lengthof(_nested_vehicle_details_widgets)
);

/** Shows the vehicle details window of the given vehicle. */
static void ShowVehicleDetailsWindow(const Vehicle *v)
{
	DeleteWindowById(WC_VEHICLE_ORDERS, v->index, false);
	DeleteWindowById(WC_VEHICLE_TIMETABLE, v->index, false);
	AllocateWindowDescFront<VehicleDetailsWindow>(&_vehicle_details_desc, v->index);
}


/* Unified vehicle GUI - Vehicle View Window */

/** Vehicle view widgets. */
static const Widget _vehicle_view_widgets[] = {
	{   WWT_CLOSEBOX,  RESIZE_NONE,  COLOUR_GREY,   0,  10,   0,  13, STR_BLACK_CROSS,          STR_TOOLTIP_CLOSE_WINDOW },           // VVW_WIDGET_CLOSEBOX
	{    WWT_CAPTION, RESIZE_RIGHT,  COLOUR_GREY,  11, 237,   0,  13, STR_VEHICLE_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS }, // VVW_WIDGET_CAPTION
	{  WWT_STICKYBOX,    RESIZE_LR,  COLOUR_GREY, 238, 249,   0,  13, 0x0,                      STR_TOOLTIP_STICKY },                  // VVW_WIDGET_STICKY
	{      WWT_PANEL,    RESIZE_RB,  COLOUR_GREY,   0, 231,  14, 103, 0x0,                      STR_NULL },                           // VVW_WIDGET_PANEL
	{      WWT_INSET,    RESIZE_RB,  COLOUR_GREY,   2, 229,  16, 101, 0x0,                      STR_NULL },                           // VVW_WIDGET_VIEWPORT
	{    WWT_PUSHBTN,   RESIZE_RTB,  COLOUR_GREY,   0, 237, 104, 115, 0x0,                      0x0 /* filled later */ },             // VVW_WIDGET_START_STOP_VEH
	{ WWT_PUSHIMGBTN,    RESIZE_LR,  COLOUR_GREY, 232, 249,  14,  31, SPR_CENTRE_VIEW_VEHICLE,  0x0 /* filled later */ },             // VVW_WIDGET_CENTER_MAIN_VIEH
	{ WWT_PUSHIMGBTN,    RESIZE_LR,  COLOUR_GREY, 232, 249,  32,  49, 0x0 /* filled later */,   0x0 /* filled later */ },             // VVW_WIDGET_GOTO_DEPOT
	{ WWT_PUSHIMGBTN,    RESIZE_LR,  COLOUR_GREY, 232, 249,  50,  67, SPR_REFIT_VEHICLE,        0x0 /* filled later */ },             // VVW_WIDGET_REFIT_VEH
	{ WWT_PUSHIMGBTN,    RESIZE_LR,  COLOUR_GREY, 232, 249,  68,  85, SPR_SHOW_ORDERS,          0x0 /* filled later */ },             // VVW_WIDGET_SHOW_ORDERS
	{ WWT_PUSHIMGBTN,    RESIZE_LR,  COLOUR_GREY, 232, 249,  86, 103, SPR_SHOW_VEHICLE_DETAILS, 0x0 /* filled later */ },             // VVW_WIDGET_SHOW_DETAILS
	{ WWT_PUSHIMGBTN,    RESIZE_LR,  COLOUR_GREY, 232, 249,  32,  49, 0x0 /* filled later */,   0x0 /* filled later */ },             // VVW_WIDGET_CLONE_VEH
	{      WWT_PANEL,   RESIZE_LRB,  COLOUR_GREY, 232, 249, 104, 103, 0x0,                      STR_NULL },                           // VVW_WIDGET_EMPTY_BOTTOM_RIGHT
	{  WWT_RESIZEBOX,  RESIZE_LRTB,  COLOUR_GREY, 238, 249, 104, 115, 0x0,                      STR_TOOLTIP_RESIZE },                  // VVW_WIDGET_RESIZE
	{ WWT_PUSHIMGBTN,    RESIZE_LR,  COLOUR_GREY, 232, 249,  50,  67, SPR_FORCE_VEHICLE_TURN,   STR_VEHICLE_VIEW_ROAD_VEHICLE_REVERSE_TOOLTIP }, // VVW_WIDGET_TURN_AROUND
	{ WWT_PUSHIMGBTN,    RESIZE_LR,  COLOUR_GREY, 232, 249,  50,  67, SPR_IGNORE_SIGNALS,       STR_VEHICLE_VIEW_TRAIN_IGNORE_SIGNAL_TOOLTIP }, // VVW_WIDGET_FORCE_PROCEED
{   WIDGETS_END},
};

static const NWidgetPart _nested_vehicle_view_widgets[] = {
	NWidget(NWID_HORIZONTAL),
		NWidget(WWT_CLOSEBOX, COLOUR_GREY, VVW_WIDGET_CLOSEBOX),
		NWidget(WWT_CAPTION, COLOUR_GREY, VVW_WIDGET_CAPTION), SetDataTip(STR_VEHICLE_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
		NWidget(WWT_STICKYBOX, COLOUR_GREY, VVW_WIDGET_STICKY),
	EndContainer(),
	NWidget(NWID_HORIZONTAL),
		NWidget(WWT_PANEL, COLOUR_GREY, VVW_WIDGET_PANEL),
			NWidget(WWT_INSET, COLOUR_GREY, VVW_WIDGET_VIEWPORT), SetPadding(2, 2, 2, 2), SetMinimalSize(228, 86), SetResize(1, 1), EndContainer(),
		EndContainer(),
		NWidget(NWID_VERTICAL),
			NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, VVW_WIDGET_CENTER_MAIN_VIEH), SetMinimalSize(18, 18), SetDataTip(SPR_CENTRE_VIEW_VEHICLE, 0x0 /* filled later */),
			NWidget(NWID_SELECTION, INVALID_COLOUR, -1),
				NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, VVW_WIDGET_GOTO_DEPOT), SetMinimalSize(18, 18), SetDataTip(0x0 /* filled later */, 0x0 /* filled later */),
				NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, VVW_WIDGET_CLONE_VEH), SetMinimalSize(18, 18), SetDataTip(0x0 /* filled later */, 0x0 /* filled later */),
			EndContainer(),
			NWidget(NWID_SELECTION, INVALID_COLOUR, -1),
				NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, VVW_WIDGET_REFIT_VEH), SetMinimalSize(18, 18),
												SetDataTip(SPR_REFIT_VEHICLE, 0x0 /* filled later */),
				NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, VVW_WIDGET_TURN_AROUND), SetMinimalSize(18, 18),
												SetDataTip(SPR_FORCE_VEHICLE_TURN, STR_VEHICLE_VIEW_ROAD_VEHICLE_REVERSE_TOOLTIP),
				NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, VVW_WIDGET_FORCE_PROCEED), SetMinimalSize(18, 18),
												SetDataTip(SPR_IGNORE_SIGNALS, STR_VEHICLE_VIEW_TRAIN_IGNORE_SIGNAL_TOOLTIP),
			EndContainer(),
			NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, VVW_WIDGET_SHOW_ORDERS), SetMinimalSize(18, 18), SetDataTip(SPR_SHOW_ORDERS, 0x0 /* filled later */),
			NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, VVW_WIDGET_SHOW_DETAILS), SetMinimalSize(18, 18), SetDataTip(SPR_SHOW_VEHICLE_DETAILS, 0x0 /* filled later */),
			NWidget(WWT_PANEL, COLOUR_GREY, VVW_WIDGET_EMPTY_BOTTOM_RIGHT), SetMinimalSize(18, 0), SetResize(0, 1), EndContainer(),
		EndContainer(),
	EndContainer(),
	NWidget(NWID_HORIZONTAL),
		NWidget(WWT_PUSHBTN, COLOUR_GREY, VVW_WIDGET_START_STOP_VEH), SetMinimalSize(0, 12), SetResize(1, 0), SetFill(true, false),
		NWidget(WWT_RESIZEBOX, COLOUR_GREY, VVW_WIDGET_RESIZE),
	EndContainer(),
};

/** Vehicle view window descriptor for all vehicles but trains. */
static const WindowDesc _vehicle_view_desc(
	WDP_AUTO, WDP_AUTO, 250, 116, 250, 116,
	WC_VEHICLE_VIEW, WC_NONE,
	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
	_vehicle_view_widgets, _nested_vehicle_view_widgets, lengthof(_nested_vehicle_view_widgets)
);

/** Vehicle view window descriptor for trains. Only minimum_height and
 *  default_height are different for train view.
 */
static const WindowDesc _train_view_desc(
	WDP_AUTO, WDP_AUTO, 250, 134, 250, 134,
	WC_VEHICLE_VIEW, WC_NONE,
	WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
	_vehicle_view_widgets, _nested_vehicle_view_widgets, lengthof(_nested_vehicle_view_widgets)
);


/* Just to make sure, nobody has changed the vehicle type constants, as we are
	 using them for array indexing in a number of places here. */
assert_compile(VEH_TRAIN == 0);
assert_compile(VEH_ROAD == 1);
assert_compile(VEH_SHIP == 2);
assert_compile(VEH_AIRCRAFT == 3);

/** Zoom levels for vehicle views indexed by vehicle type. */
static const ZoomLevel _vehicle_view_zoom_levels[] = {
	ZOOM_LVL_TRAIN,
	ZOOM_LVL_ROADVEH,
	ZOOM_LVL_SHIP,
	ZOOM_LVL_AIRCRAFT,
};

/* Constants for geometry of vehicle view viewport */
static const int VV_VIEWPORT_X = 3;
static const int VV_VIEWPORT_Y = 17;
static const int VV_INITIAL_VIEWPORT_WIDTH = 226;
static const int VV_INITIAL_VIEWPORT_HEIGHT = 84;
static const int VV_INITIAL_VIEWPORT_HEIGHT_TRAIN = 102;

/** Command indices for the _vehicle_command_translation_table. */
enum VehicleCommandTranslation {
	VCT_CMD_START_STOP = 0,
	VCT_CMD_CLONE_VEH,
	VCT_CMD_TURN_AROUND,
};

/** Command codes for the shared buttons indexed by VehicleCommandTranslation and vehicle type. */
static const uint32 _vehicle_command_translation_table[][4] = {
	{ // VCT_CMD_START_STOP
		CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_TRAIN),
		CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_ROAD_VEHICLE),
		CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_SHIP),
		CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_AIRCRAFT)
	},
	{ // VCT_CMD_CLONE_VEH
		CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_TRAIN),
		CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_ROAD_VEHICLE),
		CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_SHIP),
		CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_AIRCRAFT)
	},
	{ // VCT_CMD_TURN_AROUND
		CMD_REVERSE_TRAIN_DIRECTION | CMD_MSG(STR_ERROR_CAN_T_REVERSE_DIRECTION_TRAIN),
		CMD_TURN_ROADVEH            | CMD_MSG(STR_ERROR_CAN_T_MAKE_ROAD_VEHICLE_TURN),
		0xffffffff, // invalid for ships
		0xffffffff  // invalid for aircrafts
	},
};

/** Checks whether the vehicle may be refitted at the moment.*/
static bool IsVehicleRefitable(const Vehicle *v)
{
	if (!v->IsStoppedInDepot()) return false;

	do {
		if (IsEngineRefittable(v->engine_type)) return true;
	} while ((v->type == VEH_TRAIN || v->type == VEH_ROAD) && (v = v->Next()) != NULL);

	return false;
}

struct VehicleViewWindow : Window {
	VehicleViewWindow(const WindowDesc *desc, WindowNumber window_number) : Window(desc, window_number)
	{
		const Vehicle *v = Vehicle::Get(this->window_number);

		this->owner = v->owner;
		InitializeWindowViewport(this, VV_VIEWPORT_X, VV_VIEWPORT_Y, VV_INITIAL_VIEWPORT_WIDTH,
												 (v->type == VEH_TRAIN) ? VV_INITIAL_VIEWPORT_HEIGHT_TRAIN : VV_INITIAL_VIEWPORT_HEIGHT,
												 this->window_number | (1 << 31), _vehicle_view_zoom_levels[v->type]);

		this->widget[VVW_WIDGET_START_STOP_VEH].tooltips   = STR_VEHICLE_VIEW_TRAIN_STATE_START_STOP_TOOLTIP + v->type;
		this->widget[VVW_WIDGET_CENTER_MAIN_VIEH].tooltips = STR_VEHICLE_VIEW_TRAIN_LOCATION_TOOLTIP + v->type;
		this->widget[VVW_WIDGET_REFIT_VEH].tooltips        = STR_VEHICLE_VIEW_TRAIN_REFIT_TOOLTIP + v->type;
		this->widget[VVW_WIDGET_GOTO_DEPOT].tooltips       = STR_VEHICLE_VIEW_TRAIN_SEND_TO_DEPOT_TOOLTIP + v->type;
		this->widget[VVW_WIDGET_SHOW_ORDERS].tooltips      = STR_VEHICLE_VIEW_TRAIN_ORDERS_TOOLTIP + v->type;
		this->widget[VVW_WIDGET_SHOW_DETAILS].tooltips     = STR_VEHICLE_VIEW_TRAIN_SHOW_DETAILS_TOOLTIP + v->type;
		this->widget[VVW_WIDGET_CLONE_VEH].tooltips        = STR_VEHICLE_VIEW_CLONE_TRAIN_INFO + v->type;

		/*
		 * fill in data and tooltip codes for the widgets and
		 * move some of the buttons for trains
		 */
		switch (v->type) {
			case VEH_TRAIN:
				this->widget[VVW_WIDGET_GOTO_DEPOT].data = SPR_SEND_TRAIN_TODEPOT;
				this->widget[VVW_WIDGET_CLONE_VEH].data = SPR_CLONE_TRAIN;

				this->widget[VVW_WIDGET_TURN_AROUND].tooltips = STR_VEHICLE_VIEW_TRAIN_REVERSE_TOOLTIP;

				/* due to more buttons we must modify the layout a bit for trains */
				this->widget[VVW_WIDGET_PANEL].bottom = 121;
				this->widget[VVW_WIDGET_VIEWPORT].bottom = 119;

				this->widget[VVW_WIDGET_START_STOP_VEH].top = 122;
				this->widget[VVW_WIDGET_START_STOP_VEH].bottom = 133;

				this->widget[VVW_WIDGET_REFIT_VEH].top = 68;
				this->widget[VVW_WIDGET_REFIT_VEH].bottom = 85;

				this->widget[VVW_WIDGET_SHOW_ORDERS].top = 86;
				this->widget[VVW_WIDGET_SHOW_ORDERS].bottom = 103;

				this->widget[VVW_WIDGET_SHOW_DETAILS].top = 104;
				this->widget[VVW_WIDGET_SHOW_DETAILS].bottom = 121;

				this->widget[VVW_WIDGET_EMPTY_BOTTOM_RIGHT].top = 122;
				this->widget[VVW_WIDGET_EMPTY_BOTTOM_RIGHT].bottom = 121;

				this->widget[VVW_WIDGET_RESIZE].top = 122;
				this->widget[VVW_WIDGET_RESIZE].bottom = 133;

				this->widget[VVW_WIDGET_TURN_AROUND].top = 68;
				this->widget[VVW_WIDGET_TURN_AROUND].bottom = 85;
				break;

			case VEH_ROAD:
				this->widget[VVW_WIDGET_GOTO_DEPOT].data = SPR_SEND_ROADVEH_TODEPOT;
				this->widget[VVW_WIDGET_CLONE_VEH].data = SPR_CLONE_ROADVEH;

				this->SetWidgetHiddenState(VVW_WIDGET_FORCE_PROCEED, true);
				break;

			case VEH_SHIP:
				this->widget[VVW_WIDGET_GOTO_DEPOT].data = SPR_SEND_SHIP_TODEPOT;
				this->widget[VVW_WIDGET_CLONE_VEH].data = SPR_CLONE_SHIP;

				this->SetWidgetsHiddenState(true,
																		VVW_WIDGET_TURN_AROUND,
																		VVW_WIDGET_FORCE_PROCEED,
																		WIDGET_LIST_END);
				break;

			case VEH_AIRCRAFT:
				this->widget[VVW_WIDGET_GOTO_DEPOT].data = SPR_SEND_AIRCRAFT_TODEPOT;
				this->widget[VVW_WIDGET_CLONE_VEH].data = SPR_CLONE_AIRCRAFT;

				this->SetWidgetsHiddenState(true,
																		VVW_WIDGET_TURN_AROUND,
																		VVW_WIDGET_FORCE_PROCEED,
																		WIDGET_LIST_END);
				break;

			default: NOT_REACHED();
		}

		this->FindWindowPlacementAndResize(desc);
	}

	~VehicleViewWindow()
	{
		DeleteWindowById(WC_VEHICLE_ORDERS, this->window_number, false);
		DeleteWindowById(WC_VEHICLE_REFIT, this->window_number, false);
		DeleteWindowById(WC_VEHICLE_DETAILS, this->window_number, false);
		DeleteWindowById(WC_VEHICLE_TIMETABLE, this->window_number, false);
	}

	virtual void OnPaint()
	{
		const Vehicle *v = Vehicle::Get(this->window_number);
		StringID str;
		bool is_localcompany = v->owner == _local_company;
		bool refitable_and_stopped_in_depot = IsVehicleRefitable(v);

		this->SetWidgetDisabledState(VVW_WIDGET_GOTO_DEPOT, !is_localcompany);
		this->SetWidgetDisabledState(VVW_WIDGET_REFIT_VEH,
																!refitable_and_stopped_in_depot || !is_localcompany);
		this->SetWidgetDisabledState(VVW_WIDGET_CLONE_VEH, !is_localcompany);

		if (v->type == VEH_TRAIN) {
			this->SetWidgetDisabledState(VVW_WIDGET_FORCE_PROCEED, !is_localcompany);
			this->SetWidgetDisabledState(VVW_WIDGET_TURN_AROUND, !is_localcompany);
		}

		/* draw widgets & caption */
		SetDParam(0, v->index);
		this->DrawWidgets();

		if (v->vehstatus & VS_CRASHED) {
			str = STR_VEHICLE_STATUS_CRASHED;
		} else if (v->type != VEH_AIRCRAFT && v->breakdown_ctr == 1) { // check for aircraft necessary?
			str = STR_VEHICLE_STATUS_BROKEN_DOWN;
		} else if (v->vehstatus & VS_STOPPED) {
			if (v->type == VEH_TRAIN) {
				if (v->cur_speed == 0) {
					if (Train::From(v)->tcache.cached_power == 0) {
						str = STR_VEHICLE_STATUS_TRAIN_NO_POWER;
					} else {
						str = STR_VEHICLE_STATUS_STOPPED;
					}
				} else {
					SetDParam(0, v->GetDisplaySpeed());
					str = STR_VEHICLE_STATUS_TRAIN_STOPPING + _settings_client.gui.vehicle_speed;
				}
			} else { // no train
				str = STR_VEHICLE_STATUS_STOPPED;
			}
		} else if (v->type == VEH_TRAIN && HasBit(Train::From(v)->flags, VRF_TRAIN_STUCK) && !v->current_order.IsType(OT_LOADING)) {
			str = STR_VEHICLE_STATUS_TRAIN_STUCK;
		} else { // vehicle is in a "normal" state, show current order
			switch (v->current_order.GetType()) {
				case OT_GOTO_STATION: {
					SetDParam(0, v->current_order.GetDestination());
					SetDParam(1, v->GetDisplaySpeed());
					str = STR_VEHICLE_STATUS_HEADING_FOR_STATION + _settings_client.gui.vehicle_speed;
				} break;

				case OT_GOTO_DEPOT: {
					if (v->type == VEH_AIRCRAFT) {
						/* Aircrafts always go to a station, even if you say depot */
						SetDParam(0, v->current_order.GetDestination());
						SetDParam(1, v->GetDisplaySpeed());
					} else {
						Depot *depot = Depot::Get(v->current_order.GetDestination());
						SetDParam(0, depot->town_index);
						SetDParam(1, v->GetDisplaySpeed());
					}
					if (v->current_order.GetDepotActionType() & ODATFB_HALT) {
						str = STR_VEHICLE_STATUS_HEADING_FOR_TRAIN_DEPOT + 2 * v->type + _settings_client.gui.vehicle_speed;
					} else {
						str = STR_VEHICLE_STATUS_HEADING_FOR_TRAIN_DEPOT_SERVICE + 2 * v->type + _settings_client.gui.vehicle_speed;
					}
				} break;

				case OT_LOADING:
					str = STR_VEHICLE_STATUS_LOADING_UNLOADING;
					break;

				case OT_GOTO_WAYPOINT: {
					assert(v->type == VEH_TRAIN || v->type == VEH_SHIP);
					SetDParam(0, v->current_order.GetDestination());
					str = STR_VEHICLE_STATUS_HEADING_FOR_WAYPOINT + _settings_client.gui.vehicle_speed;
					SetDParam(1, v->GetDisplaySpeed());
					break;
				}

				case OT_LEAVESTATION:
					if (v->type != VEH_AIRCRAFT) {
						str = STR_VEHICLE_STATUS_LEAVING;
						break;
					}
					/* fall-through if aircraft. Does this even happen? */

				default:
					if (v->GetNumOrders() == 0) {
						str = STR_VEHICLE_STATUS_NO_ORDERS + _settings_client.gui.vehicle_speed;
						SetDParam(0, v->GetDisplaySpeed());
					} else {
						str = STR_EMPTY;
					}
					break;
			}
		}

		/* draw the flag plus orders */
		DrawSprite(v->vehstatus & VS_STOPPED ? SPR_FLAG_VEH_STOPPED : SPR_FLAG_VEH_RUNNING, PAL_NONE, 2, this->widget[VVW_WIDGET_START_STOP_VEH].top + 1);
		DrawString(this->widget[VVW_WIDGET_START_STOP_VEH].left + 8, this->widget[VVW_WIDGET_START_STOP_VEH].right, this->widget[VVW_WIDGET_START_STOP_VEH].top + 1, str, TC_FROMSTRING, SA_CENTER);
		this->DrawViewport();
	}

	virtual void OnClick(Point pt, int widget)
	{
		const Vehicle *v = Vehicle::Get(this->window_number);

		switch (widget) {
			case VVW_WIDGET_START_STOP_VEH: // start stop
				DoCommandP(v->tile, v->index, 0,
										_vehicle_command_translation_table[VCT_CMD_START_STOP][v->type]);
				break;
			case VVW_WIDGET_CENTER_MAIN_VIEH: {// center main view
				const Window *mainwindow = FindWindowById(WC_MAIN_WINDOW, 0);
				/* code to allow the main window to 'follow' the vehicle if the ctrl key is pressed */
				if (_ctrl_pressed && mainwindow->viewport->zoom == ZOOM_LVL_NORMAL) {
					mainwindow->viewport->follow_vehicle = v->index;
				} else {
					ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos);
				}
			} break;

			case VVW_WIDGET_GOTO_DEPOT: // goto hangar
				DoCommandP(v->tile, v->index, _ctrl_pressed ? DEPOT_SERVICE : 0, GetCmdSendToDepot(v));
				break;
			case VVW_WIDGET_REFIT_VEH: // refit
				ShowVehicleRefitWindow(v, INVALID_VEH_ORDER_ID, this);
				break;
			case VVW_WIDGET_SHOW_ORDERS: // show orders
				if (_ctrl_pressed) {
					ShowTimetableWindow(v);
				} else {
					ShowOrdersWindow(v);
				}
				break;
			case VVW_WIDGET_SHOW_DETAILS: // show details
				ShowVehicleDetailsWindow(v);
				break;
			case VVW_WIDGET_CLONE_VEH: // clone vehicle
				DoCommandP(v->tile, v->index, _ctrl_pressed ? 1 : 0,
										_vehicle_command_translation_table[VCT_CMD_CLONE_VEH][v->type],
										CcCloneVehicle);
				break;
			case VVW_WIDGET_TURN_AROUND: // turn around
				assert(v->type == VEH_TRAIN || v->type == VEH_ROAD);
				DoCommandP(v->tile, v->index, 0,
										_vehicle_command_translation_table[VCT_CMD_TURN_AROUND][v->type]);
				break;
			case VVW_WIDGET_FORCE_PROCEED: // force proceed
				assert(v->type == VEH_TRAIN);
				DoCommandP(v->tile, v->index, 0, CMD_FORCE_TRAIN_PROCEED | CMD_MSG(STR_ERROR_CAN_T_MAKE_TRAIN_PASS_SIGNAL));
				break;
		}
	}

	virtual void OnResize(Point delta)
	{
		this->viewport->width          += delta.x;
		this->viewport->height         += delta.y;
		this->viewport->virtual_width  += delta.x;
		this->viewport->virtual_height += delta.y;
	}

	virtual void OnTick()
	{
		const Vehicle *v = Vehicle::Get(this->window_number);
		bool veh_stopped = v->IsStoppedInDepot();

		/* Widget VVW_WIDGET_GOTO_DEPOT must be hidden if the vehicle is already
		 * stopped in depot.
		 * Widget VVW_WIDGET_CLONE_VEH should then be shown, since cloning is
		 * allowed only while in depot and stopped.
		 * This sytem allows to have two buttons, on top of each other.
		 * The same system applies to widget VVW_WIDGET_REFIT_VEH and VVW_WIDGET_TURN_AROUND.*/
		if (veh_stopped != this->IsWidgetHidden(VVW_WIDGET_GOTO_DEPOT) || veh_stopped == this->IsWidgetHidden(VVW_WIDGET_CLONE_VEH)) {
			this->SetWidgetHiddenState( VVW_WIDGET_GOTO_DEPOT, veh_stopped);  // send to depot
			this->SetWidgetHiddenState(VVW_WIDGET_CLONE_VEH, !veh_stopped); // clone
			if (v->type == VEH_ROAD || v->type == VEH_TRAIN) {
				this->SetWidgetHiddenState( VVW_WIDGET_REFIT_VEH, !veh_stopped); // refit
				this->SetWidgetHiddenState(VVW_WIDGET_TURN_AROUND, veh_stopped);  // force turn around
			}
			this->SetDirty();
		}
	}
};


/** Shows the vehicle view window of the given vehicle. */
void ShowVehicleViewWindow(const Vehicle *v)
{
	AllocateWindowDescFront<VehicleViewWindow>((v->type == VEH_TRAIN) ? &_train_view_desc : &_vehicle_view_desc, v->index);
}

void StopGlobalFollowVehicle(const Vehicle *v)
{
	Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
	if (w != NULL && w->viewport->follow_vehicle == v->index) {
		ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos, true); // lock the main view on the vehicle's last position
		w->viewport->follow_vehicle = INVALID_VEHICLE;
	}
}