Files @ r7921:8e674055514f
Branch filter:

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

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

/** @file window.cpp windowing system, widgets and events */

#include "stdafx.h"
#include <stdarg.h>
#include "openttd.h"
#include "debug.h"
#include "functions.h"
#include "map.h"
#include "player.h"
#include "window.h"
#include "gfx.h"
#include "viewport.h"
#include "console.h"
#include "variables.h"
#include "table/sprites.h"
#include "genworld.h"
#include "helpers.hpp"
#include "blitter/factory.hpp"

/* delta between mouse cursor and upper left corner of dragged window */
static Point _drag_delta;

static Window _windows[25];
Window *_z_windows[lengthof(_windows)];
Window **_last_z_window; ///< always points to the next free space in the z-array

void CDECL SetWindowWidgetsDisabledState(Window *w, bool disab_stat, int widgets, ...)
{
	va_list wdg_list;

	va_start(wdg_list, widgets);

	while (widgets != WIDGET_LIST_END) {
		SetWindowWidgetDisabledState(w, widgets, disab_stat);
		widgets = va_arg(wdg_list, int);
	}

	va_end(wdg_list);
}

void CDECL SetWindowWidgetsHiddenState(Window *w, bool hidden_stat, int widgets, ...)
{
	va_list wdg_list;

	va_start(wdg_list, widgets);

	while (widgets != WIDGET_LIST_END) {
		SetWindowWidgetHiddenState(w, widgets, hidden_stat);
		widgets = va_arg(wdg_list, int);
	}

	va_end(wdg_list);
}

void CDECL SetWindowWidgetsLoweredState(Window *w, bool lowered_stat, int widgets, ...)
{
	va_list wdg_list;

	va_start(wdg_list, widgets);

	while (widgets != WIDGET_LIST_END) {
		SetWindowWidgetLoweredState(w, widgets, lowered_stat);
		widgets = va_arg(wdg_list, int);
	}

	va_end(wdg_list);
}

void RaiseWindowButtons(Window *w)
{
	uint i;

	for (i = 0; i < w->widget_count; i++) {
		if (IsWindowWidgetLowered(w, i)) {
			RaiseWindowWidget(w, i);
			InvalidateWidget(w, i);
		}
	}
}

void HandleButtonClick(Window *w, byte widget)
{
	LowerWindowWidget(w, widget);
	w->flags4 |= 5 << WF_TIMEOUT_SHL;
	InvalidateWidget(w, widget);
}


static void StartWindowDrag(Window *w);
static void StartWindowSizing(Window *w);

static void DispatchLeftClickEvent(Window *w, int x, int y, bool double_click)
{
	WindowEvent e;
	const Widget *wi;

	e.we.click.pt.x = x;
	e.we.click.pt.y = y;
	e.event = double_click ? WE_DOUBLE_CLICK : WE_CLICK;

	if (w->desc_flags & WDF_DEF_WIDGET) {
		e.we.click.widget = GetWidgetFromPos(w, x, y);
		if (e.we.click.widget < 0) return; // exit if clicked outside of widgets

		/* don't allow any interaction if the button has been disabled */
		if (IsWindowWidgetDisabled(w, e.we.click.widget)) return;

		wi = &w->widget[e.we.click.widget];

		if (wi->type & WWB_MASK) {
			/* special widget handling for buttons*/
			switch (wi->type) {
				case WWT_PANEL   | WWB_PUSHBUTTON: /* WWT_PUSHBTN */
				case WWT_IMGBTN  | WWB_PUSHBUTTON: /* WWT_PUSHIMGBTN */
				case WWT_TEXTBTN | WWB_PUSHBUTTON: /* WWT_PUSHTXTBTN */
					HandleButtonClick(w, e.we.click.widget);
					break;
			}
		} else if (wi->type == WWT_SCROLLBAR || wi->type == WWT_SCROLL2BAR || wi->type == WWT_HSCROLLBAR) {
			ScrollbarClickHandler(w, wi, e.we.click.pt.x, e.we.click.pt.y);
		}

		if (w->desc_flags & WDF_STD_BTN) {
			if (e.we.click.widget == 0) { /* 'X' */
				DeleteWindow(w);
				return;
			}

			if (e.we.click.widget == 1) { /* 'Title bar' */
				StartWindowDrag(w);
				return;
			}
		}

		if (w->desc_flags & WDF_RESIZABLE && wi->type == WWT_RESIZEBOX) {
			StartWindowSizing(w);
			InvalidateWidget(w, e.we.click.widget);
			return;
		}

		if (w->desc_flags & WDF_STICKY_BUTTON && wi->type == WWT_STICKYBOX) {
			w->flags4 ^= WF_STICKY;
			InvalidateWidget(w, e.we.click.widget);
			return;
		}
	}

	w->wndproc(w, &e);
}

static void DispatchRightClickEvent(Window *w, int x, int y)
{
	WindowEvent e;

	/* default tooltips handler? */
	if (w->desc_flags & WDF_STD_TOOLTIPS) {
		e.we.click.widget = GetWidgetFromPos(w, x, y);
		if (e.we.click.widget < 0)
			return; // exit if clicked outside of widgets

		if (w->widget[e.we.click.widget].tooltips != 0) {
			GuiShowTooltips(w->widget[e.we.click.widget].tooltips);
			return;
		}
	}

	e.event = WE_RCLICK;
	e.we.click.pt.x = x;
	e.we.click.pt.y = y;
	w->wndproc(w, &e);
}

/** Dispatch the mousewheel-action to the window which will scroll any
 * compatible scrollbars if the mouse is pointed over the bar or its contents
 * @param *w Window
 * @param widget the widget where the scrollwheel was used
 * @param wheel scroll up or down
 */
static void DispatchMouseWheelEvent(Window *w, int widget, int wheel)
{
	const Widget *wi1, *wi2;
	Scrollbar *sb;

	if (widget < 0) return;

	wi1 = &w->widget[widget];
	wi2 = &w->widget[widget + 1];

	/* The listbox can only scroll if scrolling was done on the scrollbar itself,
	 * or on the listbox (and the next item is (must be) the scrollbar)
	 * XXX - should be rewritten as a widget-dependent scroller but that's
	 * not happening until someone rewrites the whole widget-code */
	if ((sb = &w->vscroll,  wi1->type == WWT_SCROLLBAR)  || (sb = &w->vscroll2, wi1->type == WWT_SCROLL2BAR)  ||
			(sb = &w->vscroll2, wi2->type == WWT_SCROLL2BAR) || (sb = &w->vscroll, wi2->type == WWT_SCROLLBAR) ) {

		if (sb->count > sb->cap) {
			int pos = clamp(sb->pos + wheel, 0, sb->count - sb->cap);
			if (pos != sb->pos) {
				sb->pos = pos;
				SetWindowDirty(w);
			}
		}
	}
}

static void DrawOverlappedWindow(Window* const *wz, int left, int top, int right, int bottom);

void DrawOverlappedWindowForAll(int left, int top, int right, int bottom)
{
	Window* const *wz;
	DrawPixelInfo bk;
	_cur_dpi = &bk;

	FOR_ALL_WINDOWS(wz) {
		const Window *w = *wz;
		if (right > w->left &&
				bottom > w->top &&
				left < w->left + w->width &&
				top < w->top + w->height) {
			DrawOverlappedWindow(wz, left, top, right, bottom);
		}
	}
}

static void DrawOverlappedWindow(Window* const *wz, int left, int top, int right, int bottom)
{
	Window* const *vz = wz;
	int x;

	while (++vz != _last_z_window) {
		const Window *v = *vz;

		if (right > v->left &&
				bottom > v->top &&
				left < v->left + v->width &&
				top < v->top + v->height) {
			if (left < (x = v->left)) {
				DrawOverlappedWindow(wz, left, top, x, bottom);
				DrawOverlappedWindow(wz, x, top, right, bottom);
				return;
			}

			if (right > (x = v->left + v->width)) {
				DrawOverlappedWindow(wz, left, top, x, bottom);
				DrawOverlappedWindow(wz, x, top, right, bottom);
				return;
			}

			if (top < (x = v->top)) {
				DrawOverlappedWindow(wz, left, top, right, x);
				DrawOverlappedWindow(wz, left, x, right, bottom);
				return;
			}

			if (bottom > (x = v->top + v->height)) {
				DrawOverlappedWindow(wz, left, top, right, x);
				DrawOverlappedWindow(wz, left, x, right, bottom);
				return;
			}

			return;
		}
	}

	{
		DrawPixelInfo *dp = _cur_dpi;
		dp->width = right - left;
		dp->height = bottom - top;
		dp->left = left - (*wz)->left;
		dp->top = top - (*wz)->top;
		dp->pitch = _screen.pitch;
		dp->dst_ptr = BlitterFactoryBase::GetCurrentBlitter()->MoveTo(_screen.dst_ptr, left, top);
		dp->zoom = ZOOM_LVL_NORMAL;
		CallWindowEventNP(*wz, WE_PAINT);
	}
}

void CallWindowEventNP(Window *w, int event)
{
	WindowEvent e;

	e.event = event;
	w->wndproc(w, &e);
}

void SetWindowDirty(const Window *w)
{
	if (w == NULL) return;
	SetDirtyBlocks(w->left, w->top, w->left + w->width, w->top + w->height);
}

/** Find the Window whose parent pointer points to this window
 * @param w parent Window to find child of
 * @return a Window pointer that is the child of w, or NULL otherwise */
static Window *FindChildWindow(const Window *w)
{
	Window* const *wz;

	FOR_ALL_WINDOWS(wz) {
		Window *v = *wz;
		if (v->parent == w) return v;
	}

	return NULL;
}

/** Find the z-value of a window. A window must already be open
 * or the behaviour is undefined but function should never fail
 * @param w window to query Z Position
 * @return the window that matches it */
Window **FindWindowZPosition(const Window *w)
{
	Window **wz;

	for (wz = _z_windows; wz != _last_z_window; wz++) {
		if (*wz == w) return wz;
	}

	DEBUG(misc, 3, "Window (cls %d, number %d) is not open, probably removed by recursive calls",
		w->window_class, w->window_number);
	return NULL;
}

void DeleteWindow(Window *w)
{
	Window *v;
	Window **wz;
	if (w == NULL) return;

	/* Delete any children a window might have in a head-recursive manner */
	v = FindChildWindow(w);
	if (v != NULL) DeleteWindow(v);

	if (_thd.place_mode != VHM_NONE &&
			_thd.window_class == w->window_class &&
			_thd.window_number == w->window_number) {
		ResetObjectToPlace();
	}

	CallWindowEventNP(w, WE_DESTROY);
	if (w->viewport != NULL) DeleteWindowViewport(w);

	SetWindowDirty(w);
	free(w->widget);
	w->widget = NULL;
	w->widget_count = 0;
	w->parent = NULL;

	/* Find the window in the z-array, and effectively remove it
	 * by moving all windows after it one to the left */
	wz = FindWindowZPosition(w);
	if (wz == NULL) return;
	memmove(wz, wz + 1, (byte*)_last_z_window - (byte*)wz);
	_last_z_window--;
}

Window *FindWindowById(WindowClass cls, WindowNumber number)
{
	Window* const *wz;

	FOR_ALL_WINDOWS(wz) {
		Window *w = *wz;
		if (w->window_class == cls && w->window_number == number) return w;
	}

	return NULL;
}

void DeleteWindowById(WindowClass cls, WindowNumber number)
{
	DeleteWindow(FindWindowById(cls, number));
}

void DeleteWindowByClass(WindowClass cls)
{
	Window* const *wz;

restart_search:
	/* When we find the window to delete, we need to restart the search
	 * as deleting this window could cascade in deleting (many) others
	 * anywhere in the z-array */
	FOR_ALL_WINDOWS(wz) {
		Window *w = *wz;
		if (w->window_class == cls) {
			DeleteWindow(w);
			goto restart_search;
		}
	}
}

/** Delete all windows of a player. We identify windows of a player
 * by looking at the caption colour. If it is equal to the player ID
 * then we say the window belongs to the player and should be deleted
 * @param id PlayerID player identifier */
void DeletePlayerWindows(PlayerID id)
{
	Window* const *wz;

restart_search:
	/* When we find the window to delete, we need to restart the search
	 * as deleting this window could cascade in deleting (many) others
	 * anywhere in the z-array */
	FOR_ALL_WINDOWS(wz) {
		Window *w = *wz;
		if (w->caption_color == id) {
			DeleteWindow(w);
			goto restart_search;
		}
	}

	/* Also delete the player specific windows, that don't have a player-colour */
	DeleteWindowById(WC_BUY_COMPANY, id);
}

/** Change the owner of all the windows one player can take over from another
 * player in the case of a company merger. Do not change ownership of windows
 * that need to be deleted once takeover is complete
 * @param old_player PlayerID of original owner of the window
 * @param new_player PlayerID of the new owner of the window */
void ChangeWindowOwner(PlayerID old_player, PlayerID new_player)
{
	Window* const *wz;

	FOR_ALL_WINDOWS(wz) {
		Window *w = *wz;

		if (w->caption_color != old_player)      continue;
		if (w->window_class == WC_PLAYER_COLOR)  continue;
		if (w->window_class == WC_FINANCES)      continue;
		if (w->window_class == WC_STATION_LIST)  continue;
		if (w->window_class == WC_TRAINS_LIST)   continue;
		if (w->window_class == WC_ROADVEH_LIST)  continue;
		if (w->window_class == WC_SHIPS_LIST)    continue;
		if (w->window_class == WC_AIRCRAFT_LIST) continue;
		if (w->window_class == WC_BUY_COMPANY)   continue;
		if (w->window_class == WC_COMPANY)       continue;

		w->caption_color = new_player;
	}
}

static void BringWindowToFront(const Window *w);

/** Find a window and make it the top-window on the screen. The window
 * gets a white border for a brief period of time to visualize its "activation"
 * @param cls WindowClass of the window to activate
 * @param number WindowNumber of the window to activate
 * @return a pointer to the window thus activated */
Window *BringWindowToFrontById(WindowClass cls, WindowNumber number)
{
	Window *w = FindWindowById(cls, number);

	if (w != NULL) {
		w->flags4 |= WF_WHITE_BORDER_MASK;
		BringWindowToFront(w);
		SetWindowDirty(w);
	}

	return w;
}

static inline bool IsVitalWindow(const Window *w)
{
	WindowClass wc = w->window_class;
	return (wc == WC_MAIN_TOOLBAR || wc == WC_STATUS_BAR || wc == WC_NEWS_WINDOW || wc == WC_SEND_NETWORK_MSG);
}

/** On clicking on a window, make it the frontmost window of all. However
 * there are certain windows that always need to be on-top; these include
 * - Toolbar, Statusbar (always on)
 * - New window, Chatbar (only if open)
 * The window is marked dirty for a repaint if the window is actually moved
 * @param w window that is put into the foreground
 * @return pointer to the window, the same as the input pointer
 */
static void BringWindowToFront(const Window *w)
{
	Window *tempz;
	Window **wz = FindWindowZPosition(w);
	Window **vz = _last_z_window;

	/* Bring the window just below the vital windows */
	do {
		if (--vz < _z_windows) return;
	} while (IsVitalWindow(*vz));

	if (wz == vz) return; // window is already in the right position
	assert(wz < vz);

	tempz = *wz;
	memmove(wz, wz + 1, (byte*)vz - (byte*)wz);
	*vz = tempz;

	SetWindowDirty(w);
}

/** We have run out of windows, so find a suitable candidate for replacement.
 * Keep all important windows intact. These are
 * - Main window (gamefield), Toolbar, Statusbar (always on)
 * - News window, Chatbar (when on)
 * - Any sticked windows since we wanted to keep these
 * @return w pointer to the window that is going to be deleted
 */
static Window *FindDeletableWindow()
{
	Window* const *wz;

	FOR_ALL_WINDOWS(wz) {
		Window *w = *wz;
		if (w->window_class != WC_MAIN_WINDOW && !IsVitalWindow(w) && !(w->flags4 & WF_STICKY)) {
			return w;
		}
	}
	return NULL;
}

/** A window must be freed, and all are marked as important windows. Ease the
 * restriction a bit by allowing to delete sticky windows. Keep important/vital
 * windows intact (Main window, Toolbar, Statusbar, News Window, Chatbar)
 * Start finding an appropiate candidate from the lowest z-values (bottom)
 * @see FindDeletableWindow()
 * @return w Pointer to the window that is being deleted
 */
static Window *ForceFindDeletableWindow()
{
	Window* const *wz;

	for (wz = _z_windows;; wz++) {
		Window *w = *wz;
		assert(wz < _last_z_window);
		if (w->window_class != WC_MAIN_WINDOW && !IsVitalWindow(w)) return w;
	}
}

bool IsWindowOfPrototype(const Window *w, const Widget *widget)
{
	return (w->original_widget == widget);
}

/** Copies 'widget' to 'w->widget' to allow for resizable windows
 * @param w Window on which to attach the widget array
 * @param widget pointer of widget array to fill the window with */
void AssignWidgetToWindow(Window *w, const Widget *widget)
{
	w->original_widget = widget;

	if (widget != NULL) {
		uint index = 1;
		const Widget *wi;

		for (wi = widget; wi->type != WWT_LAST; wi++) index++;

		w->widget = ReallocT(w->widget, index);
		memcpy(w->widget, widget, sizeof(*w->widget) * index);
		w->widget_count = index - 1;
	} else {
		w->widget = NULL;
		w->widget_count = 0;
	}
}

static Window *FindFreeWindow()
{
	Window *w;

	for (w = _windows; w < endof(_windows); w++) {
		Window* const *wz;
		bool window_in_use = false;

		FOR_ALL_WINDOWS(wz) {
			if (*wz == w) {
				window_in_use = true;
				break;
			}
		}

		if (!window_in_use) return w;
	}

	assert(_last_z_window == endof(_z_windows));
	return NULL;
}

/** Open a new window.
 * This function is called from AllocateWindow() or AllocateWindowDesc()
 * See descriptions for those functions for usage
 * See AllocateWindow() for description of arguments.
 * Only addition here is window_number, which is the window_number being assigned to the new window
 * @param x offset in pixels from the left of the screen
 * @param y offset in pixels from the top of the screen
 * @param min_width minimum width in pixels of the window
 * @param min_height minimum height in pixels of the window
 * @param def_width default width in pixels of the window
 * @param def_height default height in pixels of the window
 * @param *proc see WindowProc function to call when any messages/updates happen to the window
 * @param cls see WindowClass class of the window, used for identification and grouping
 * @param *widget see Widget pointer to the window layout and various elements
 * @param window_number number being assigned to the new window
 * @param data the data to be given during the WE_CREATE message
 * @return Window pointer of the newly created window */
static Window *LocalAllocateWindow(
							int x, int y, int min_width, int min_height, int def_width, int def_height,
							WindowProc *proc, WindowClass cls, const Widget *widget, int window_number, void *data)
{
	Window *w = FindFreeWindow();

	/* We have run out of windows, close one and use that as the place for our new one */
	if (w == NULL) {
		w = FindDeletableWindow();
		if (w == NULL) w = ForceFindDeletableWindow();
		DeleteWindow(w);
	}

	/* Set up window properties */
	memset(w, 0, sizeof(*w));
	w->window_class = cls;
	w->flags4 = WF_WHITE_BORDER_MASK; // just opened windows have a white border
	w->caption_color = 0xFF;
	w->left = x;
	w->top = y;
	w->width = min_width;
	w->height = min_height;
	w->wndproc = proc;
	AssignWidgetToWindow(w, widget);
	w->resize.width = min_width;
	w->resize.height = min_height;
	w->resize.step_width = 1;
	w->resize.step_height = 1;
	w->window_number = window_number;

	{
		Window **wz = _last_z_window;

		/* Hacky way of specifying always-on-top windows. These windows are
		 * always above other windows because they are moved below them.
		 * status-bar is above news-window because it has been created earlier.
		 * Also, as the chat-window is excluded from this, it will always be
		 * the last window, thus always on top.
		 * XXX - Yes, ugly, probably needs something like w->always_on_top flag
		 * to implement correctly, but even then you need some kind of distinction
		 * between on-top of chat/news and status windows, because these conflict */
		if (wz != _z_windows && w->window_class != WC_SEND_NETWORK_MSG && w->window_class != WC_HIGHSCORE && w->window_class != WC_ENDSCREEN) {
			if (FindWindowById(WC_MAIN_TOOLBAR, 0)     != NULL) wz--;
			if (FindWindowById(WC_STATUS_BAR, 0)       != NULL) wz--;
			if (FindWindowById(WC_NEWS_WINDOW, 0)      != NULL) wz--;
			if (FindWindowById(WC_SEND_NETWORK_MSG, 0) != NULL) wz--;

			assert(wz >= _z_windows);
			if (wz != _last_z_window) memmove(wz + 1, wz, (byte*)_last_z_window - (byte*)wz);
		}

		*wz = w;
		_last_z_window++;
	}

	WindowEvent e;
	e.event = WE_CREATE;
	e.we.create.data = data;
	w->wndproc(w, &e);

	/* Try to make windows smaller when our window is too small.
	 * w->(width|height) is normally the same as min_(width|height),
	 * but this way the GUIs can be made a little more dynamic;
	 * one can use the same spec for multiple windows and those
	 * can then determine the real minimum size of the window. */
	if (w->width != def_width || w->height != def_height) {
		/* Think about the overlapping toolbars when determining the minimum window size */
		int free_height = _screen.height;
		const Window *wt = FindWindowById(WC_STATUS_BAR, 0);
		if (wt != NULL) free_height -= wt->height;
		wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
		if (wt != NULL) free_height -= wt->height;

		int enlarge_x = max(min(def_width  - w->width,  _screen.width - w->width),  0);
		int enlarge_y = max(min(def_height - w->height, free_height   - w->height), 0);

		/* X and Y has to go by step.. calculate it.
		 * The cast to int is necessary else x/y are implicitly casted to
		 * unsigned int, which won't work. */
		if (w->resize.step_width  > 1) enlarge_x -= enlarge_x % (int)w->resize.step_width;
		if (w->resize.step_height > 1) enlarge_y -= enlarge_y % (int)w->resize.step_height;

		ResizeWindow(w, enlarge_x, enlarge_y);

		WindowEvent e;
		e.event = WE_RESIZE;
		e.we.sizing.size.x = w->width;
		e.we.sizing.size.y = w->height;
		e.we.sizing.diff.x = enlarge_x;
		e.we.sizing.diff.y = enlarge_y;
		w->wndproc(w, &e);
	}

	int nx = w->left;
	int ny = w->top;

	if (nx + w->width > _screen.width) nx -= (nx + w->width - _screen.width);

	const Window *wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
	ny = max(ny, (wt == NULL || w == wt || y == 0) ? 0 : wt->height);
	nx = max(nx, 0);

	if (w->viewport != NULL) {
		w->viewport->left += nx - w->left;
		w->viewport->top  += ny - w->top;
	}
	w->left = nx;
	w->top = ny;

	SetWindowDirty(w);

	return w;
}

/**
 * Open a new window. If there is no space for a new window, close an open
 * window. Try to avoid stickied windows, but if there is no else, close one of
 * those as well. Then make sure all created windows are below some always-on-top
 * ones. Finally set all variables and call the WE_CREATE event
 * @param x offset in pixels from the left of the screen
 * @param y offset in pixels from the top of the screen
 * @param width width in pixels of the window
 * @param height height in pixels of the window
 * @param *proc see WindowProc function to call when any messages/updates happen to the window
 * @param cls see WindowClass class of the window, used for identification and grouping
 * @param *widget see Widget pointer to the window layout and various elements
 * @return Window pointer of the newly created window */
Window *AllocateWindow(
							int x, int y, int width, int height,
							WindowProc *proc, WindowClass cls, const Widget *widget, void *data)
{
	return LocalAllocateWindow(x, y, width, height, width, height, proc, cls, widget, 0, data);
}

struct SizeRect {
	int left,top,width,height;
};


static bool IsGoodAutoPlace1(int left, int top, int width, int height, Point &pos)
{
	Window* const *wz;

	int right  = width + left;
	int bottom = height + top;

	if (left < 0 || top < 22 || right > _screen.width || bottom > _screen.height)
		return false;

	/* Make sure it is not obscured by any window. */
	FOR_ALL_WINDOWS(wz) {
		const Window *w = *wz;
		if (w->window_class == WC_MAIN_WINDOW) continue;

		if (right > w->left &&
				w->left + w->width > left &&
				bottom > w->top &&
				w->top + w->height > top) {
			return false;
		}
	}

	pos.x = left;
	pos.y = top;
	return true;
}

static bool IsGoodAutoPlace2(int left, int top, int width, int height, Point &pos)
{
	Window* const *wz;

	if (left < -(width>>2) || left > _screen.width - (width>>1)) return false;
	if (top < 22 || top > _screen.height - (height>>2)) return false;

	/* Make sure it is not obscured by any window. */
	FOR_ALL_WINDOWS(wz) {
		const Window *w = *wz;
		if (w->window_class == WC_MAIN_WINDOW) continue;

		if (left + width > w->left &&
				w->left + w->width > left &&
				top + height > w->top &&
				w->top + w->height > top) {
			return false;
		}
	}

	pos.x = left;
	pos.y = top;
	return true;
}

static Point GetAutoPlacePosition(int width, int height)
{
	Window* const *wz;
	Point pt;

	if (IsGoodAutoPlace1(0, 24, width, height, pt)) return pt;

	FOR_ALL_WINDOWS(wz) {
		const Window *w = *wz;
		if (w->window_class == WC_MAIN_WINDOW) continue;

		if (IsGoodAutoPlace1(w->left + w->width + 2, w->top, width, height, pt)) return pt;
		if (IsGoodAutoPlace1(w->left - width - 2,    w->top, width, height, pt)) return pt;
		if (IsGoodAutoPlace1(w->left, w->top + w->height + 2, width, height, pt)) return pt;
		if (IsGoodAutoPlace1(w->left, w->top - height - 2,    width, height, pt)) return pt;
		if (IsGoodAutoPlace1(w->left + w->width + 2, w->top + w->height - height, width, height, pt)) return pt;
		if (IsGoodAutoPlace1(w->left - width - 2,    w->top + w->height - height, width, height, pt)) return pt;
		if (IsGoodAutoPlace1(w->left + w->width - width, w->top + w->height + 2, width, height, pt)) return pt;
		if (IsGoodAutoPlace1(w->left + w->width - width, w->top - height - 2,    width, height, pt)) return pt;
	}

	FOR_ALL_WINDOWS(wz) {
		const Window *w = *wz;
		if (w->window_class == WC_MAIN_WINDOW) continue;

		if (IsGoodAutoPlace2(w->left + w->width + 2, w->top, width, height, pt)) return pt;
		if (IsGoodAutoPlace2(w->left - width - 2,    w->top, width, height, pt)) return pt;
		if (IsGoodAutoPlace2(w->left, w->top + w->height + 2, width, height, pt)) return pt;
		if (IsGoodAutoPlace2(w->left, w->top - height - 2,    width, height, pt)) return pt;
	}

	{
		int left = 0, top = 24;

restart:
		FOR_ALL_WINDOWS(wz) {
			const Window *w = *wz;

			if (w->left == left && w->top == top) {
				left += 5;
				top += 5;
				goto restart;
			}
		}

		pt.x = left;
		pt.y = top;
		return pt;
	}
}

/**
 * Set the x and y coordinates of a new window.
 *
 * @param *desc         The pointer to the WindowDesc to be created
 * @param window_number the window number of the new window
 * @param data          arbitrary data that is send with the WE_CREATE message
 *
 * @return see Window pointer of the newly created window
 */
static Window *LocalAllocateWindowDesc(const WindowDesc *desc, int window_number, void *data)
{
	Point pt;
	Window *w;

	/* By default position a child window at an offset of 10/10 of its parent.
	 * With the exception of WC_BUILD_TOOLBAR (build railway/roads/ship docks/airports)
	 * and WC_SCEN_LAND_GEN (landscaping). Whose child window has an offset of 0/36 of
	 * its parent. So it's exactly under the parent toolbar and no buttons will be covered.
	 * However if it falls too extremely outside window positions, reposition
	 * it to an automatic place */
	if (desc->parent_cls != 0 /* WC_MAIN_WINDOW */ &&
			(w = FindWindowById(desc->parent_cls, window_number)) != NULL &&
			w->left < _screen.width - 20 && w->left > -60 && w->top < _screen.height - 20) {

		pt.x = w->left + ((desc->parent_cls == WC_BUILD_TOOLBAR || desc->parent_cls == WC_SCEN_LAND_GEN) ? 0 : 10);
		if (pt.x > _screen.width + 10 - desc->default_width) {
			pt.x = (_screen.width + 10 - desc->default_width) - 20;
		}
		pt.y = w->top + ((desc->parent_cls == WC_BUILD_TOOLBAR || desc->parent_cls == WC_SCEN_LAND_GEN) ? 36 : 10);
	} else {
		switch (desc->left) {
			case WDP_ALIGN_TBR: { /* Align the right side with the top toolbar */
				w = FindWindowById(WC_MAIN_TOOLBAR, 0);
				pt.x = (w->left + w->width) - desc->default_width;
			} break;
			case WDP_ALIGN_TBL: /* Align the left side with the top toolbar */
				pt.x = FindWindowById(WC_MAIN_TOOLBAR, 0)->left;
				break;
			case WDP_AUTO: /* Find a good automatic position for the window */
				pt = GetAutoPlacePosition(desc->default_width, desc->default_height);
				goto allocate_window;
			case WDP_CENTER: /* Centre the window horizontally */
				pt.x = (_screen.width - desc->default_width) / 2;
				break;
			default:
				pt.x = desc->left;
				if (pt.x < 0) pt.x += _screen.width; // negative is from right of the screen
		}

		switch (desc->top) {
			case WDP_CENTER: /* Centre the window vertically */
				pt.y = (_screen.height - desc->default_height) / 2;
				break;
			/* WDP_AUTO sets the position at once and is controlled by desc->left.
			 * Both left and top must be set to WDP_AUTO */
			case WDP_AUTO:
				NOT_REACHED();
				assert(desc->left == WDP_AUTO && desc->top != WDP_AUTO);
				/* fallthrough */
			default:
				pt.y = desc->top;
				if (pt.y < 0) pt.y += _screen.height; // negative is from bottom of the screen
				break;
		}
	}

allocate_window:
	w = LocalAllocateWindow(pt.x, pt.y, desc->minimum_width, desc->minimum_height, desc->default_width, desc->default_height, desc->proc, desc->cls, desc->widgets, window_number, data);
	w->desc_flags = desc->flags;
	return w;
}

/**
 * Open a new window.
 * @param *desc The pointer to the WindowDesc to be created
 * @param data arbitrary data that is send with the WE_CREATE message
 * @return Window pointer of the newly created window
 */
Window *AllocateWindowDesc(const WindowDesc *desc, void *data)
{
	return LocalAllocateWindowDesc(desc, 0, data);
}

/**
 * Open a new window.
 * @param *desc The pointer to the WindowDesc to be created
 * @param window_number the window number of the new window
 * @param data arbitrary data that is send with the WE_CREATE message
 * @return see Window pointer of the newly created window
 */
Window *AllocateWindowDescFront(const WindowDesc *desc, int window_number, void *data)
{
	Window *w;

	if (BringWindowToFrontById(desc->cls, window_number)) return NULL;
	w = LocalAllocateWindowDesc(desc, window_number, data);
	return w;
}

/** Do a search for a window at specific coordinates. For this we start
 * at the topmost window, obviously and work our way down to the bottom
 * @param x position x to query
 * @param y position y to query
 * @return a pointer to the found window if any, NULL otherwise */
Window *FindWindowFromPt(int x, int y)
{
	Window* const *wz;

	for (wz = _last_z_window; wz != _z_windows;) {
		Window *w = *--wz;
		if (IS_INSIDE_1D(x, w->left, w->width) && IS_INSIDE_1D(y, w->top, w->height)) {
			return w;
		}
	}

	return NULL;
}

void InitWindowSystem()
{
	IConsoleClose();

	memset(&_windows, 0, sizeof(_windows));
	_last_z_window = _z_windows;
	InitViewports();
	_no_scroll = 0;
}

void UnInitWindowSystem()
{
	Window **wz;

restart_search:
	/* Delete all windows, reset z-array.
	 *When we find the window to delete, we need to restart the search
	 * as deleting this window could cascade in deleting (many) others
	 * anywhere in the z-array. We call DeleteWindow() so that it can properly
	 * release own alloc'd memory, which otherwise could result in memleaks */
	FOR_ALL_WINDOWS(wz) {
		DeleteWindow(*wz);
		goto restart_search;
	}

	assert(_last_z_window == _z_windows);
}

void ResetWindowSystem()
{
	UnInitWindowSystem();
	InitWindowSystem();
	_thd.pos.x = 0;
	_thd.pos.y = 0;
	_thd.new_pos.x = 0;
	_thd.new_pos.y = 0;
}

static void DecreaseWindowCounters()
{
	Window *w;
	Window* const *wz;

	for (wz = _last_z_window; wz != _z_windows;) {
		w = *--wz;
		/* Unclick scrollbar buttons if they are pressed. */
		if (w->flags4 & (WF_SCROLL_DOWN | WF_SCROLL_UP)) {
			w->flags4 &= ~(WF_SCROLL_DOWN | WF_SCROLL_UP);
			SetWindowDirty(w);
		}
		CallWindowEventNP(w, WE_MOUSELOOP);
	}

	for (wz = _last_z_window; wz != _z_windows;) {
		w = *--wz;

		if (w->flags4&WF_TIMEOUT_MASK && !(--w->flags4&WF_TIMEOUT_MASK)) {
			CallWindowEventNP(w, WE_TIMEOUT);
			if (w->desc_flags & WDF_UNCLICK_BUTTONS) RaiseWindowButtons(w);
		}
	}
}

Window *GetCallbackWnd()
{
	return FindWindowById(_thd.window_class, _thd.window_number);
}

static void HandlePlacePresize()
{
	Window *w;
	WindowEvent e;

	if (_special_mouse_mode != WSM_PRESIZE) return;

	w = GetCallbackWnd();
	if (w == NULL) return;

	e.we.place.pt = GetTileBelowCursor();
	if (e.we.place.pt.x == -1) {
		_thd.selend.x = -1;
		return;
	}
	e.we.place.tile = TileVirtXY(e.we.place.pt.x, e.we.place.pt.y);
	e.event = WE_PLACE_PRESIZE;
	w->wndproc(w, &e);
}

static bool HandleDragDrop()
{
	Window *w;
	WindowEvent e;

	if (_special_mouse_mode != WSM_DRAGDROP) return true;

	if (_left_button_down) return false;

	w = GetCallbackWnd();

	ResetObjectToPlace();

	if (w != NULL) {
		/* send an event in client coordinates. */
		e.event = WE_DRAGDROP;
		e.we.dragdrop.pt.x = _cursor.pos.x - w->left;
		e.we.dragdrop.pt.y = _cursor.pos.y - w->top;
		e.we.dragdrop.widget = GetWidgetFromPos(w, e.we.dragdrop.pt.x, e.we.dragdrop.pt.y);
		w->wndproc(w, &e);
	}
	return false;
}

static bool HandlePopupMenu()
{
	Window *w;
	WindowEvent e;

	if (!_popup_menu_active) return true;

	w = FindWindowById(WC_TOOLBAR_MENU, 0);
	if (w == NULL) {
		_popup_menu_active = false;
		return false;
	}

	if (_left_button_down) {
		e.event = WE_POPUPMENU_OVER;
		e.we.popupmenu.pt = _cursor.pos;
	} else {
		_popup_menu_active = false;
		e.event = WE_POPUPMENU_SELECT;
		e.we.popupmenu.pt = _cursor.pos;
	}

	w->wndproc(w, &e);

	return false;
}

static bool HandleMouseOver()
{
	Window *w;
	WindowEvent e;
	static Window *last_w = NULL;

	w = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);

	/* We changed window, put a MOUSEOVER event to the last window */
	if (last_w != NULL && last_w != w) {
		e.event = WE_MOUSEOVER;
		e.we.mouseover.pt.x = -1;
		e.we.mouseover.pt.y = -1;
		if (last_w->wndproc) last_w->wndproc(last_w, &e);
	}
	last_w = w;

	if (w != NULL) {
		/* send an event in client coordinates. */
		e.event = WE_MOUSEOVER;
		e.we.mouseover.pt.x = _cursor.pos.x - w->left;
		e.we.mouseover.pt.y = _cursor.pos.y - w->top;
		if (w->widget != NULL) {
			e.we.mouseover.widget = GetWidgetFromPos(w, e.we.mouseover.pt.x, e.we.mouseover.pt.y);
		}
		w->wndproc(w, &e);
	}

	/* Mouseover never stops execution */
	return true;
}

/** Update all the widgets of a window based on their resize flags
 * Both the areas of the old window and the new sized window are set dirty
 * ensuring proper redrawal.
 * @param w Window to resize
 * @param x delta x-size of changed window (positive if larger, etc.)
 * @param y delta y-size of changed window */
void ResizeWindow(Window *w, int x, int y)
{
	Widget *wi;
	bool resize_height = false;
	bool resize_width = false;

	if (x == 0 && y == 0) return;

	SetWindowDirty(w);
	for (wi = w->widget; wi->type != WWT_LAST; wi++) {
		/* Isolate the resizing flags */
		byte rsizeflag = GB(wi->display_flags, 0, 4);

		if (rsizeflag == RESIZE_NONE) continue;

		/* Resize the widget based on its resize-flag */
		if (rsizeflag & RESIZE_LEFT) {
			wi->left += x;
			resize_width = true;
		}

		if (rsizeflag & RESIZE_RIGHT) {
			wi->right += x;
			resize_width = true;
		}

		if (rsizeflag & RESIZE_TOP) {
			wi->top += y;
			resize_height = true;
		}

		if (rsizeflag & RESIZE_BOTTOM) {
			wi->bottom += y;
			resize_height = true;
		}
	}

	/* We resized at least 1 widget, so let's resize the window totally */
	if (resize_width)  w->width  += x;
	if (resize_height) w->height += y;

	SetWindowDirty(w);
}

static bool _dragging_window;

static bool HandleWindowDragging()
{
	Window* const *wz;
	/* Get out immediately if no window is being dragged at all. */
	if (!_dragging_window) return true;

	/* Otherwise find the window... */
	FOR_ALL_WINDOWS(wz) {
		Window *w = *wz;

		if (w->flags4 & WF_DRAGGING) {
			const Widget *t = &w->widget[1]; // the title bar ... ugh
			const Window *v;
			int x;
			int y;
			int nx;
			int ny;

			/* Stop the dragging if the left mouse button was released */
			if (!_left_button_down) {
				w->flags4 &= ~WF_DRAGGING;
				break;
			}

			SetWindowDirty(w);

			x = _cursor.pos.x + _drag_delta.x;
			y = _cursor.pos.y + _drag_delta.y;
			nx = x;
			ny = y;

			if (_patches.window_snap_radius != 0) {
				Window* const *vz;

				int hsnap = _patches.window_snap_radius;
				int vsnap = _patches.window_snap_radius;
				int delta;

				FOR_ALL_WINDOWS(vz) {
					const Window *v = *vz;

					if (v == w) continue; // Don't snap at yourself

					if (y + w->height > v->top && y < v->top + v->height) {
						/* Your left border <-> other right border */
						delta = abs(v->left + v->width - x);
						if (delta <= hsnap) {
							nx = v->left + v->width;
							hsnap = delta;
						}

						/* Your right border <-> other left border */
						delta = abs(v->left - x - w->width);
						if (delta <= hsnap) {
							nx = v->left - w->width;
							hsnap = delta;
						}
					}

					if (w->top + w->height >= v->top && w->top <= v->top + v->height) {
						/* Your left border <-> other left border */
						delta = abs(v->left - x);
						if (delta <= hsnap) {
							nx = v->left;
							hsnap = delta;
						}

						/* Your right border <-> other right border */
						delta = abs(v->left + v->width - x - w->width);
						if (delta <= hsnap) {
							nx = v->left + v->width - w->width;
							hsnap = delta;
						}
					}

					if (x + w->width > v->left && x < v->left + v->width) {
						/* Your top border <-> other bottom border */
						delta = abs(v->top + v->height - y);
						if (delta <= vsnap) {
							ny = v->top + v->height;
							vsnap = delta;
						}

						/* Your bottom border <-> other top border */
						delta = abs(v->top - y - w->height);
						if (delta <= vsnap) {
							ny = v->top - w->height;
							vsnap = delta;
						}
					}

					if (w->left + w->width >= v->left && w->left <= v->left + v->width) {
						/* Your top border <-> other top border */
						delta = abs(v->top - y);
						if (delta <= vsnap) {
							ny = v->top;
							vsnap = delta;
						}

						/* Your bottom border <-> other bottom border */
						delta = abs(v->top + v->height - y - w->height);
						if (delta <= vsnap) {
							ny = v->top + v->height - w->height;
							vsnap = delta;
						}
					}
				}
			}

			/* Make sure the window doesn't leave the screen
			 * 13 is the height of the title bar */
			nx = clamp(nx, 13 - t->right, _screen.width - 13 - t->left);
			ny = clamp(ny, 0, _screen.height - 13);

			/* Make sure the title bar isn't hidden by behind the main tool bar */
			v = FindWindowById(WC_MAIN_TOOLBAR, 0);
			if (v != NULL) {
				int v_bottom = v->top + v->height;
				int v_right = v->left + v->width;
				if (ny + t->top >= v->top && ny + t->top < v_bottom) {
					if ((v->left < 13 && nx + t->left < v->left) ||
							(v_right > _screen.width - 13 && nx + t->right > v_right)) {
						ny = v_bottom;
					} else {
						if (nx + t->left > v->left - 13 &&
								nx + t->right < v_right + 13) {
							if (w->top >= v_bottom) {
								ny = v_bottom;
							} else if (w->left < nx) {
								nx = v->left - 13 - t->left;
							} else {
								nx = v_right + 13 - t->right;
							}
						}
					}
				}
			}

			if (w->viewport != NULL) {
				w->viewport->left += nx - w->left;
				w->viewport->top  += ny - w->top;
			}
			w->left = nx;
			w->top  = ny;

			SetWindowDirty(w);
			return false;
		} else if (w->flags4 & WF_SIZING) {
			WindowEvent e;
			int x, y;

			/* Stop the sizing if the left mouse button was released */
			if (!_left_button_down) {
				w->flags4 &= ~WF_SIZING;
				SetWindowDirty(w);
				break;
			}

			x = _cursor.pos.x - _drag_delta.x;
			y = _cursor.pos.y - _drag_delta.y;

			/* X and Y has to go by step.. calculate it.
			 * The cast to int is necessary else x/y are implicitly casted to
			 * unsigned int, which won't work. */
			if (w->resize.step_width > 1) x -= x % (int)w->resize.step_width;

			if (w->resize.step_height > 1) y -= y % (int)w->resize.step_height;

			/* Check if we don't go below the minimum set size */
			if ((int)w->width + x < (int)w->resize.width)
				x = w->resize.width - w->width;
			if ((int)w->height + y < (int)w->resize.height)
				y = w->resize.height - w->height;

			/* Window already on size */
			if (x == 0 && y == 0) return false;

			/* Now find the new cursor pos.. this is NOT _cursor, because
			    we move in steps. */
			_drag_delta.x += x;
			_drag_delta.y += y;

			/* ResizeWindow sets both pre- and after-size to dirty for redrawal */
			ResizeWindow(w, x, y);

			e.event = WE_RESIZE;
			e.we.sizing.size.x = x + w->width;
			e.we.sizing.size.y = y + w->height;
			e.we.sizing.diff.x = x;
			e.we.sizing.diff.y = y;
			w->wndproc(w, &e);
			return false;
		}
	}

	_dragging_window = false;
	return false;
}

static void StartWindowDrag(Window *w)
{
	w->flags4 |= WF_DRAGGING;
	_dragging_window = true;

	_drag_delta.x = w->left - _cursor.pos.x;
	_drag_delta.y = w->top  - _cursor.pos.y;

	BringWindowToFront(w);
	DeleteWindowById(WC_DROPDOWN_MENU, 0);
}

static void StartWindowSizing(Window *w)
{
	w->flags4 |= WF_SIZING;
	_dragging_window = true;

	_drag_delta.x = _cursor.pos.x;
	_drag_delta.y = _cursor.pos.y;

	BringWindowToFront(w);
	DeleteWindowById(WC_DROPDOWN_MENU, 0);
}


static bool HandleScrollbarScrolling()
{
	Window* const *wz;
	int i;
	int pos;
	Scrollbar *sb;

	/* Get out quickly if no item is being scrolled */
	if (!_scrolling_scrollbar) return true;

	/* Find the scrolling window */
	FOR_ALL_WINDOWS(wz) {
		Window *w = *wz;

		if (w->flags4 & WF_SCROLL_MIDDLE) {
			/* Abort if no button is clicked any more. */
			if (!_left_button_down) {
				w->flags4 &= ~WF_SCROLL_MIDDLE;
				SetWindowDirty(w);
				break;
			}

			if (w->flags4 & WF_HSCROLL) {
				sb = &w->hscroll;
				i = _cursor.pos.x - _cursorpos_drag_start.x;
			} else if (w->flags4 & WF_SCROLL2){
				sb = &w->vscroll2;
				i = _cursor.pos.y - _cursorpos_drag_start.y;
			} else {
				sb = &w->vscroll;
				i = _cursor.pos.y - _cursorpos_drag_start.y;
			}

			/* Find the item we want to move to and make sure it's inside bounds. */
			pos = min(max(0, i + _scrollbar_start_pos) * sb->count / _scrollbar_size, max(0, sb->count - sb->cap));
			if (pos != sb->pos) {
				sb->pos = pos;
				SetWindowDirty(w);
			}
			return false;
		}
	}

	_scrolling_scrollbar = false;
	return false;
}

static bool HandleViewportScroll()
{
	WindowEvent e;
	Window *w;

	bool scrollwheel_scrolling = _patches.scrollwheel_scrolling == 1 && (_cursor.v_wheel != 0 || _cursor.h_wheel != 0);

	if (!_scrolling_viewport) return true;

	w = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);

	if (!(_right_button_down || scrollwheel_scrolling) || w == NULL) {
		_cursor.fix_at = false;
		_scrolling_viewport = false;
		return true;
	}

	if (WP(w, vp_d).follow_vehicle != INVALID_VEHICLE && w == FindWindowById(WC_MAIN_WINDOW, 0)) {
		/* If the main window is following a vehicle, then first let go of it! */
		const Vehicle *veh = GetVehicle(WP(w, vp_d).follow_vehicle);
		ScrollMainWindowTo(veh->x_pos, veh->y_pos, true); /* This also resets follow_vehicle */
		return true;
	}

	if (_patches.reverse_scroll) {
		e.we.scroll.delta.x = -_cursor.delta.x;
		e.we.scroll.delta.y = -_cursor.delta.y;
	} else {
		e.we.scroll.delta.x = _cursor.delta.x;
		e.we.scroll.delta.y = _cursor.delta.y;
	}

	if (scrollwheel_scrolling) {
		/* We are using scrollwheels for scrolling */
		e.we.scroll.delta.x = _cursor.h_wheel;
		e.we.scroll.delta.y = _cursor.v_wheel;
		_cursor.v_wheel = 0;
		_cursor.h_wheel = 0;
	}

	/* Create a scroll-event and send it to the window */
	e.event = WE_SCROLL;
	w->wndproc(w, &e);

	_cursor.delta.x = 0;
	_cursor.delta.y = 0;
	return false;
}

/** Check if a window can be made top-most window, and if so do
 * it. If a window does not obscure any other windows, it will not
 * be brought to the foreground. Also if the only obscuring windows
 * are so-called system-windows, the window will not be moved.
 * The function will return false when a child window of this window is a
 * modal-popup; function returns a false and child window gets a white border
 * @param w Window to bring on-top
 * @return false if the window has an active modal child, true otherwise */
static bool MaybeBringWindowToFront(const Window *w)
{
	bool bring_to_front = false;
	Window* const *wz;
	Window* const *uz;

	if (w->window_class == WC_MAIN_WINDOW ||
			IsVitalWindow(w) ||
			w->window_class == WC_TOOLTIPS ||
			w->window_class == WC_DROPDOWN_MENU) {
		return true;
	}

	wz = FindWindowZPosition(w);
	for (uz = wz; ++uz != _last_z_window;) {
		Window *u = *uz;

		/* A modal child will prevent the activation of the parent window */
		if (u->parent == w && (u->desc_flags & WDF_MODAL)) {
			u->flags4 |= WF_WHITE_BORDER_MASK;
			SetWindowDirty(u);
			return false;
		}

		if (u->window_class == WC_MAIN_WINDOW ||
				IsVitalWindow(u) ||
				u->window_class == WC_TOOLTIPS ||
				u->window_class == WC_DROPDOWN_MENU) {
			continue;
		}

		/* Window sizes don't interfere, leave z-order alone */
		if (w->left + w->width <= u->left ||
				u->left + u->width <= w->left ||
				w->top  + w->height <= u->top ||
				u->top + u->height <= w->top) {
			continue;
		}

		bring_to_front = true;
	}

	if (bring_to_front) BringWindowToFront(w);
	return true;
}

/** Send a message from one window to another. The receiving window is found by
 * @param w Window pointer pointing to the other window
 * @param msg Specifies the message to be sent
 * @param wparam Specifies additional message-specific information
 * @param lparam Specifies additional message-specific information
 */
static void SendWindowMessageW(Window *w, uint msg, uint wparam, uint lparam)
{
	WindowEvent e;

	e.event             = WE_MESSAGE;
	e.we.message.msg    = msg;
	e.we.message.wparam = wparam;
	e.we.message.lparam = lparam;

	w->wndproc(w, &e);
}

/** Send a message from one window to another. The receiving window is found by
 * @param wnd_class see WindowClass class AND
 * @param wnd_num see WindowNumber number, mostly 0
 * @param msg Specifies the message to be sent
 * @param wparam Specifies additional message-specific information
 * @param lparam Specifies additional message-specific information
 */
void SendWindowMessage(WindowClass wnd_class, WindowNumber wnd_num, int msg, int wparam, int lparam)
{
	Window *w = FindWindowById(wnd_class, wnd_num);
	if (w != NULL) SendWindowMessageW(w, msg, wparam, lparam);
}

/** Send a message from one window to another. The message will be sent
 * to ALL windows of the windowclass specified in the first parameter
 * @param wnd_class see WindowClass class
 * @param msg Specifies the message to be sent
 * @param wparam Specifies additional message-specific information
 * @param lparam Specifies additional message-specific information
 */
void SendWindowMessageClass(WindowClass wnd_class, int msg, int wparam, int lparam)
{
	Window* const *wz;

	FOR_ALL_WINDOWS(wz) {
		if ((*wz)->window_class == wnd_class) SendWindowMessageW(*wz, msg, wparam, lparam);
	}
}

/** Handle keyboard input.
 * @param key Lower 8 bits contain the ASCII character, the higher
 * 16 bits the keycode */
void HandleKeypress(uint32 key)
{
	Window* const *wz;
	WindowEvent e;
	/* Stores if a window with a textfield for typing is open
	 * If this is the case, keypress events are only passed to windows with text fields and
	 * to thein this main toolbar. */
	bool query_open = false;

	/*
	* During the generation of the world, there might be
	* another thread that is currently building for example
	* a road. To not interfere with those tasks, we should
	* NOT change the _current_player here.
	*
	* This is not necessary either, as the only events that
	* can be handled are the 'close application' events
	*/
	if (!IsGeneratingWorld()) _current_player = _local_player;

	/* Setup event */
	e.event = WE_KEYPRESS;
	e.we.keypress.key     = GB(key,  0, 16);
	e.we.keypress.keycode = GB(key, 16, 16);
	e.we.keypress.cont = true;

	/* check if we have a query string window open before allowing hotkeys */
	if (FindWindowById(WC_QUERY_STRING,       0) != NULL ||
			FindWindowById(WC_SEND_NETWORK_MSG,   0) != NULL ||
			FindWindowById(WC_GENERATE_LANDSCAPE, 0) != NULL ||
			FindWindowById(WC_CONSOLE,            0) != NULL ||
			FindWindowById(WC_SAVELOAD,           0) != NULL) {
		query_open = true;
	}

	/* Call the event, start with the uppermost window. */
	for (wz = _last_z_window; wz != _z_windows;) {
		Window *w = *--wz;

		/* if a query window is open, only call the event for certain window types */
		if (query_open &&
				w->window_class != WC_QUERY_STRING &&
				w->window_class != WC_SEND_NETWORK_MSG &&
				w->window_class != WC_GENERATE_LANDSCAPE &&
				w->window_class != WC_CONSOLE &&
				w->window_class != WC_SAVELOAD) {
			continue;
		}
		w->wndproc(w, &e);
		if (!e.we.keypress.cont) break;
	}

	if (e.we.keypress.cont) {
		Window *w = FindWindowById(WC_MAIN_TOOLBAR, 0);
		/* When there is no toolbar w is null, check for that */
		if (w != NULL) w->wndproc(w, &e);
	}
}

extern void UpdateTileSelection();
extern bool VpHandlePlaceSizingDrag();

static int _input_events_this_tick = 0;

static void HandleAutoscroll()
{
	Window *w;
	ViewPort *vp;
	int x = _cursor.pos.x;
	int y = _cursor.pos.y;

	if (_input_events_this_tick != 0) {
		/* HandleAutoscroll is called only once per GameLoop() - so we can clear the counter here */
		_input_events_this_tick = 0;
		/* there were some inputs this tick, don't scroll ??? */
		return;
	}

	if (_patches.autoscroll && _game_mode != GM_MENU && !IsGeneratingWorld()) {
		w = FindWindowFromPt(x, y);
		if (w == NULL || w->flags4 & WF_DISABLE_VP_SCROLL) return;
		vp = IsPtInWindowViewport(w, x, y);
		if (vp != NULL) {
			x -= vp->left;
			y -= vp->top;
			/* here allows scrolling in both x and y axis */
#define scrollspeed 3
			if (x - 15 < 0) {
				WP(w, vp_d).dest_scrollpos_x += ScaleByZoom((x - 15) * scrollspeed, vp->zoom);
			} else if (15 - (vp->width - x) > 0) {
				WP(w, vp_d).dest_scrollpos_x += ScaleByZoom((15 - (vp->width - x)) * scrollspeed, vp->zoom);
			}
			if (y - 15 < 0) {
				WP(w, vp_d).dest_scrollpos_y += ScaleByZoom((y - 15) * scrollspeed, vp->zoom);
			} else if (15 - (vp->height - y) > 0) {
				WP(w, vp_d).dest_scrollpos_y += ScaleByZoom((15 - (vp->height - y)) * scrollspeed, vp->zoom);
			}
#undef scrollspeed
		}
	}
}

enum MouseClick {
	MC_NONE = 0,
	MC_LEFT,
	MC_RIGHT,
	MC_DOUBLE_LEFT,

	MAX_OFFSET_DOUBLE_CLICK = 5,     ///< How much the mouse is allowed to move to call it a double click
	TIME_BETWEEN_DOUBLE_CLICK = 500, ///< Time between 2 left clicks before it becoming a double click, in ms
};

void MouseLoop(MouseClick click, int mousewheel)
{
	int x,y;
	Window *w;
	ViewPort *vp;
	bool scrollwheel_scrolling = _patches.scrollwheel_scrolling == 1 && (_cursor.v_wheel != 0 || _cursor.h_wheel != 0);

	DecreaseWindowCounters();
	HandlePlacePresize();
	UpdateTileSelection();
	if (!VpHandlePlaceSizingDrag())  return;
	if (!HandleDragDrop())           return;
	if (!HandlePopupMenu())          return;
	if (!HandleWindowDragging())     return;
	if (!HandleScrollbarScrolling()) return;
	if (!HandleViewportScroll())     return;
	if (!HandleMouseOver())          return;

	x = _cursor.pos.x;
	y = _cursor.pos.y;

	if (click == MC_NONE && mousewheel == 0 && !scrollwheel_scrolling) return;

	w = FindWindowFromPt(x, y);
	if (w == NULL) return;
	if (!MaybeBringWindowToFront(w)) return;
	vp = IsPtInWindowViewport(w, x, y);

	/* Don't allow any action in a viewport if either in menu of in generating world */
	if (vp != NULL && (_game_mode == GM_MENU || IsGeneratingWorld())) return;

	if (mousewheel != 0) {
		if (_patches.scrollwheel_scrolling == 0) {
			/* Scrollwheel is in zoom mode. Make the zoom event. */
			WindowEvent e;

			/* Send WE_MOUSEWHEEL event to window */
			e.event = WE_MOUSEWHEEL;
			e.we.wheel.wheel = mousewheel;
			w->wndproc(w, &e);
		}

		/* Dispatch a MouseWheelEvent for widgets if it is not a viewport */
		if (vp == NULL) DispatchMouseWheelEvent(w, GetWidgetFromPos(w, x - w->left, y - w->top), mousewheel);
	}

	if (vp != NULL) {
		if (scrollwheel_scrolling) click = MC_RIGHT; // we are using the scrollwheel in a viewport, so we emulate right mouse button
		switch (click) {
			case MC_DOUBLE_LEFT:
			case MC_LEFT:
				DEBUG(misc, 2, "Cursor: 0x%X (%d)", _cursor.sprite, _cursor.sprite);
				if (_thd.place_mode != VHM_NONE &&
						/* query button and place sign button work in pause mode */
						_cursor.sprite != SPR_CURSOR_QUERY &&
						_cursor.sprite != SPR_CURSOR_SIGN &&
						_pause_game != 0 &&
						!_cheats.build_in_pause.value) {
					return;
				}

				if (_thd.place_mode == VHM_NONE) {
					HandleViewportClicked(vp, x, y);
				} else {
					PlaceObject();
				}
				break;

			case MC_RIGHT:
				if (!(w->flags4 & WF_DISABLE_VP_SCROLL)) {
					_scrolling_viewport = true;
					_cursor.fix_at = true;
				}
				break;

			default:
				break;
		}
	} else {
		switch (click) {
			case MC_DOUBLE_LEFT: DispatchLeftClickEvent(w, x - w->left, y - w->top, true);
				/* fallthough, and also give a single-click for backwards compatible */
			case MC_LEFT: DispatchLeftClickEvent(w, x - w->left, y - w->top, false); break;
			default:
				if (!scrollwheel_scrolling || w == NULL || w->window_class != WC_SMALLMAP) break;
				/* We try to use the scrollwheel to scroll since we didn't touch any of the buttons.
				* Simulate a right button click so we can get started. */
				/* fallthough */
			case MC_RIGHT: DispatchRightClickEvent(w, x - w->left, y - w->top); break;
		}
	}
}

void HandleMouseEvents()
{
	static int double_click_time = 0;
	static int double_click_x = 0;
	static int double_click_y = 0;
	MouseClick click;
	int mousewheel;

	/*
	 * During the generation of the world, there might be
	 * another thread that is currently building for example
	 * a road. To not interfere with those tasks, we should
	 * NOT change the _current_player here.
	 *
	 * This is not necessary either, as the only events that
	 * can be handled are the 'close application' events
	 */
	if (!IsGeneratingWorld()) _current_player = _local_player;

	/* Mouse event? */
	click = MC_NONE;
	if (_left_button_down && !_left_button_clicked) {
		click = MC_LEFT;
		if (double_click_time != 0 && _realtime_tick - double_click_time   < TIME_BETWEEN_DOUBLE_CLICK &&
			  double_click_x != 0    && abs(_cursor.pos.x - double_click_x) < MAX_OFFSET_DOUBLE_CLICK  &&
			  double_click_y != 0    && abs(_cursor.pos.y - double_click_y) < MAX_OFFSET_DOUBLE_CLICK) {
			click = MC_DOUBLE_LEFT;
		}
		double_click_time = _realtime_tick;
		double_click_x = _cursor.pos.x;
		double_click_y = _cursor.pos.y;
		_left_button_clicked = true;
		_input_events_this_tick++;
	} else if (_right_button_clicked) {
		_right_button_clicked = false;
		click = MC_RIGHT;
		_input_events_this_tick++;
	}

	mousewheel = 0;
	if (_cursor.wheel) {
		mousewheel = _cursor.wheel;
		_cursor.wheel = 0;
		_input_events_this_tick++;
	}

	MouseLoop(click, mousewheel);
}

void InputLoop()
{
	HandleMouseEvents();
	HandleAutoscroll();
}

void UpdateWindows()
{
	Window* const *wz;
	static int we4_timer = 0;
	int t = we4_timer + 1;

	if (t >= 100) {
		for (wz = _last_z_window; wz != _z_windows;) {
			CallWindowEventNP(*--wz, WE_4);
		}
		t = 0;
	}
	we4_timer = t;

	for (wz = _last_z_window; wz != _z_windows;) {
		Window *w = *--wz;
		if (w->flags4 & WF_WHITE_BORDER_MASK) {
			w->flags4 -= WF_WHITE_BORDER_ONE;

			if (!(w->flags4 & WF_WHITE_BORDER_MASK)) SetWindowDirty(w);
		}
	}

	DrawDirtyBlocks();

	FOR_ALL_WINDOWS(wz) {
		if ((*wz)->viewport != NULL) UpdateViewportPosition(*wz);
	}
	DrawChatMessage();
	/* Redraw mouse cursor in case it was hidden */
	DrawMouseCursor();
}


int GetMenuItemIndex(const Window *w, int x, int y)
{
	if ((x -= w->left) >= 0 && x < w->width && (y -= w->top + 1) >= 0) {
		y /= 10;

		if (y < WP(w, const menu_d).item_count &&
				!HASBIT(WP(w, const menu_d).disabled_items, y)) {
			return y;
		}
	}
	return -1;
}

void InvalidateWindow(WindowClass cls, WindowNumber number)
{
	Window* const *wz;

	FOR_ALL_WINDOWS(wz) {
		const Window *w = *wz;
		if (w->window_class == cls && w->window_number == number) SetWindowDirty(w);
	}
}

void InvalidateWidget(const Window *w, byte widget_index)
{
	const Widget *wi = &w->widget[widget_index];

	/* Don't redraw the window if the widget is invisible or of no-type */
	if (wi->type == WWT_EMPTY || IsWindowWidgetHidden(w, widget_index)) return;

	SetDirtyBlocks(w->left + wi->left, w->top + wi->top, w->left + wi->right + 1, w->top + wi->bottom + 1);
}

void InvalidateWindowWidget(WindowClass cls, WindowNumber number, byte widget_index)
{
	Window* const *wz;

	FOR_ALL_WINDOWS(wz) {
		const Window *w = *wz;
		if (w->window_class == cls && w->window_number == number) {
			InvalidateWidget(w, widget_index);
		}
	}
}

void InvalidateWindowClasses(WindowClass cls)
{
	Window* const *wz;

	FOR_ALL_WINDOWS(wz) {
		if ((*wz)->window_class == cls) SetWindowDirty(*wz);
	}
}

void InvalidateThisWindowData(Window *w)
{
	CallWindowEventNP(w, WE_INVALIDATE_DATA);
	SetWindowDirty(w);
}

void InvalidateWindowData(WindowClass cls, WindowNumber number)
{
	Window* const *wz;

	FOR_ALL_WINDOWS(wz) {
		Window *w = *wz;
		if (w->window_class == cls && w->window_number == number) InvalidateThisWindowData(w);
	}
}

void InvalidateWindowClassesData(WindowClass cls)
{
	Window* const *wz;

	FOR_ALL_WINDOWS(wz) {
		if ((*wz)->window_class == cls) InvalidateThisWindowData(*wz);
	}
}

void CallWindowTickEvent()
{
	Window* const *wz;

	for (wz = _last_z_window; wz != _z_windows;) {
		CallWindowEventNP(*--wz, WE_TICK);
	}
}

void DeleteNonVitalWindows()
{
	Window* const *wz;

restart_search:
	/* When we find the window to delete, we need to restart the search
	 * as deleting this window could cascade in deleting (many) others
	 * anywhere in the z-array */
	FOR_ALL_WINDOWS(wz) {
		Window *w = *wz;
		if (w->window_class != WC_MAIN_WINDOW &&
				w->window_class != WC_SELECT_GAME &&
				w->window_class != WC_MAIN_TOOLBAR &&
				w->window_class != WC_STATUS_BAR &&
				w->window_class != WC_TOOLBAR_MENU &&
				w->window_class != WC_TOOLTIPS &&
				(w->flags4 & WF_STICKY) == 0) { // do not delete windows which are 'pinned'

			DeleteWindow(w);
			goto restart_search;
		}
	}
}

/** It is possible that a stickied window gets to a position where the
 * 'close' button is outside the gaming area. You cannot close it then; except
 * with this function. It closes all windows calling the standard function,
 * then, does a little hacked loop of closing all stickied windows. Note
 * that standard windows (status bar, etc.) are not stickied, so these aren't affected */
void DeleteAllNonVitalWindows()
{
	Window* const *wz;

	/* Delete every window except for stickied ones, then sticky ones as well */
	DeleteNonVitalWindows();

restart_search:
	/* When we find the window to delete, we need to restart the search
	 * as deleting this window could cascade in deleting (many) others
	 * anywhere in the z-array */
	FOR_ALL_WINDOWS(wz) {
		if ((*wz)->flags4 & WF_STICKY) {
			DeleteWindow(*wz);
			goto restart_search;
		}
	}
}

/** Delete all always on-top windows to get an empty screen */
void HideVitalWindows()
{
	DeleteWindowById(WC_TOOLBAR_MENU, 0);
	DeleteWindowById(WC_MAIN_TOOLBAR, 0);
	DeleteWindowById(WC_STATUS_BAR, 0);
}

int PositionMainToolbar(Window *w)
{
	DEBUG(misc, 5, "Repositioning Main Toolbar...");

	if (w == NULL || w->window_class != WC_MAIN_TOOLBAR) {
		w = FindWindowById(WC_MAIN_TOOLBAR, 0);
	}

	switch (_patches.toolbar_pos) {
		case 1:  w->left = (_screen.width - w->width) / 2; break;
		case 2:  w->left = _screen.width - w->width; break;
		default: w->left = 0;
	}
	SetDirtyBlocks(0, 0, _screen.width, w->height); // invalidate the whole top part
	return w->left;
}

void RelocateAllWindows(int neww, int newh)
{
	Window* const *wz;

	FOR_ALL_WINDOWS(wz) {
		Window *w = *wz;
		int left, top;

		if (w->window_class == WC_MAIN_WINDOW) {
			ViewPort *vp = w->viewport;
			vp->width = w->width = neww;
			vp->height = w->height = newh;
			vp->virtual_width = ScaleByZoom(neww, vp->zoom);
			vp->virtual_height = ScaleByZoom(newh, vp->zoom);
			continue; // don't modify top,left
		}

		/* XXX - this probably needs something more sane. For example specying
		 * in a 'backup'-desc that the window should always be centred. */
		switch (w->window_class) {
			case WC_MAIN_TOOLBAR:
				if (neww - w->width != 0) {
					ResizeWindow(w, min(neww, 640) - w->width, 0);

					WindowEvent e;
					e.event = WE_RESIZE;
					e.we.sizing.size.x = w->width;
					e.we.sizing.size.y = w->height;
					e.we.sizing.diff.x = neww - w->width;
					e.we.sizing.diff.y = 0;
					w->wndproc(w, &e);
				}

				top = w->top;
				left = PositionMainToolbar(w); // changes toolbar orientation
				break;

			case WC_SELECT_GAME:
			case WC_GAME_OPTIONS:
			case WC_NETWORK_WINDOW:
				top = (newh - w->height) >> 1;
				left = (neww - w->width) >> 1;
				break;

			case WC_NEWS_WINDOW:
				top = newh - w->height;
				left = (neww - w->width) >> 1;
				break;

			case WC_STATUS_BAR:
				ResizeWindow(w, clamp(neww, 320, 640) - w->width, 0);
				top = newh - w->height;
				left = (neww - w->width) >> 1;
				break;

			case WC_SEND_NETWORK_MSG:
				ResizeWindow(w, clamp(neww, 320, 640) - w->width, 0);
				top = (newh - 26); // 26 = height of status bar + height of chat bar
				left = (neww - w->width) >> 1;
				break;

			case WC_CONSOLE:
				IConsoleResize(w);
				continue;

			default:
				left = w->left;
				if (left + (w->width >> 1) >= neww) left = neww - w->width;
				top = w->top;
				if (top + (w->height >> 1) >= newh) top = newh - w->height;
				break;
		}

		if (w->viewport != NULL) {
			w->viewport->left += left - w->left;
			w->viewport->top += top - w->top;
		}

		w->left = left;
		w->top = top;
	}
}