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
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
//! Items related to the `App` type and the application context in general.
//!
//! See here for items relating to the event loop, device access, creating and managing windows,
//! streams and more.
//!
//! - [**App**](./struct.App.html) - provides a context and API for windowing, devices, etc.
//! - [**Proxy**](./struct.Proxy.html) - a handle to an **App** that may be used from a non-main
//!   thread.
//! - [**Draw**](./struct.Draw.html) - a simple API for drawing graphics, accessible via
//!   `app.draw()`.
//! - [**LoopMode**](./enum.LoopMode.html) - describes the behaviour of the application event loop.

use crate::draw;
use crate::event::{self, Event, Key, LoopEvent, Update};
use crate::frame::{Frame, RawFrame, RenderData};
use crate::geom;
use crate::state;
use crate::time::DurationF64;
use crate::ui;
use crate::vk::{self, DeviceOwned, GpuFuture};
use crate::window::{self, Window};
use find_folder;
use std;
use std::cell::{RefCell, RefMut};
use std::collections::{HashMap, HashSet};
use std::ops::{Deref, DerefMut};
use std::path::PathBuf;
use std::sync::atomic::{self, AtomicBool};
use std::sync::Arc;
use std::time::{Duration, Instant};
use winit;

#[cfg(all(target_os = "macos", not(test)))]
use moltenvk_deps as mvkd;

/// The user function type for initialising their model.
pub type ModelFn<Model> = fn(&App) -> Model;

/// The user function type for updating their model in accordance with some event.
pub type EventFn<Model, Event> = fn(&App, &mut Model, Event);

/// The user function type for updating the user model within the application loop.
pub type UpdateFn<Model> = fn(&App, &mut Model, Update);

/// The user function type for drawing their model to the surface of a single window.
pub type ViewFn<Model> = fn(&App, &Model, &Frame);

/// A shorthand version of `ViewFn` for sketches where the user does not need a model.
pub type SketchViewFn = fn(&App, &Frame);

/// The user function type allowing them to consume the `model` when the application exits.
pub type ExitFn<Model> = fn(&App, Model);

/// The **App**'s view function.
enum View<Model = ()> {
    /// A view function allows for viewing the user's model.
    WithModel(ViewFn<Model>),
    /// A **Simple** view function does not require a user **Model**. Simpler to get started.
    Sketch(SketchViewFn),
}

/// A nannou `App` builder.
pub struct Builder<M = (), E = Event> {
    model: ModelFn<M>,
    event: Option<EventFn<M, E>>,
    update: Option<UpdateFn<M>>,
    default_view: Option<View<M>>,
    exit: Option<ExitFn<M>>,
    vk_instance: Option<Arc<vk::Instance>>,
    vk_debug_callback: Option<vk::DebugCallbackBuilder>,
    create_default_window: bool,
    #[cfg(all(target_os = "macos", not(test)))]
    moltenvk_settings: Option<mvkd::Install>,
}

/// The default `model` function used when none is specified by the user.
fn default_model(_: &App) -> () {
    ()
}

/// Each nannou application has a single **App** instance. This **App** represents the entire
/// context of the application.
///
/// The **App** provides access to most application and windowing related "IO" related APIs. In
/// other words, if you need access to windowing, the Vulkan instance, etc, the **App** will
/// provide access to this.
///
/// The **App** owns and manages:
///
/// - The **window and input event loop** used to drive the application forward.
/// - **All windows** for graphics and user input. Windows can be referenced via their IDs.
pub struct App {
    config: RefCell<Config>,
    pub(crate) vk_instance: Arc<vk::Instance>,
    pub(crate) events_loop: winit::EventsLoop,
    pub(crate) windows: RefCell<HashMap<window::Id, Window>>,
    draw_state: DrawState,
    pub(crate) ui: ui::Arrangement,
    /// The window that is currently in focus.
    pub(crate) focused_window: RefCell<Option<window::Id>>,

    /// Indicates whether or not the events loop is currently asleep.
    ///
    /// This is set to `true` each time the events loop is ready to return and the `LoopMode` is
    /// set to `Wait` for events.
    ///
    /// This value is set back to `false` each time the events loop receives any kind of event.
    pub(crate) events_loop_is_asleep: Arc<AtomicBool>,

    /// The current state of the `Mouse`.
    pub mouse: state::Mouse,
    /// State of the keyboard keys.
    ///
    /// `mods` provides state of each of the modifier keys: `shift`, `ctrl`, `alt`, `logo`.
    ///
    /// `down` is the set of keys that are currently pressed.
    ///
    /// NOTE: `down` this is tracked by the nannou `App` so issues might occur if e.g. a key is
    /// pressed while the app is in focus and then released when out of focus. Eventually we should
    /// change this to query the OS somehow, but I don't think `winit` provides a way to do this
    /// yet.
    pub keys: state::Keys,
    /// Key time measurements tracked by the App.
    ///
    /// `duration.since_start` specifies the duration since the app started running.
    ///
    /// `duration.since_prev_update` specifies the duration since the previous update event.
    pub duration: state::Time,

    /// The time in seconds since the `App` started running.
    ///
    /// Primarily, this field is a convenience that removes the need to call
    /// `app.duration.since_start.secs()`. Normally we would try to avoid using such an ambiguous
    /// field name, however due to the sheer amount of use that this value has we feel it is
    /// beneficial to provide easier access.
    ///
    /// This value is of the same type as the scalar value used for describing space in animations.
    /// This makes it very easy to animate graphics and create changes over time without having to
    /// cast values or repeatedly calculate it from a `Duration` type. A small example might be
    /// `app.time.sin()` for simple oscillation behaviour.
    ///
    /// **Note:** This is suitable for use in short sketches, however should be avoided in long
    /// running installations. This is because the "resolution" of floating point values reduces as
    /// the number becomes higher. Instead, we recommend using `app.duration.since_start` or
    /// `app.duration.since_prev_update` to access a more precise form of app time.
    pub time: DrawScalar,
}

// /// Graphics related items within the `App`.
// pub struct Graphics {
// }
//
// /// Items related to the presence of one or more windows within the App.
// pub struct Windowing {
// }

/// Miscellaneous app configuration parameters.
#[derive(Debug)]
struct Config {
    loop_mode: LoopMode,
    exit_on_escape: bool,
    fullscreen_on_shortcut: bool,
}

/// A **nannou::Draw** instance owned by the **App**. A simple API for sketching with 2D and 3D
/// graphics.
///
/// This is a conveniently accessible **Draw** instance which can be easily re-used between calls
/// to an app's **view** function.
#[derive(Debug)]
pub struct Draw<'a> {
    window_id: window::Id,
    draw: RefMut<'a, draw::Draw<DrawScalar>>,
    renderer: RefMut<'a, RefCell<draw::backend::vulkano::Renderer>>,
    depth_format: vk::Format,
}

// Draw state managed by the **App**.
#[derive(Debug)]
struct DrawState {
    draw: RefCell<draw::Draw<DrawScalar>>,
    renderers: RefCell<HashMap<window::Id, RefCell<draw::backend::vulkano::Renderer>>>,
    // The supported depth format for each device.
    //
    // Devices are mapped via their `index`, which is stated to "never change" according to the
    // vulkano docs.
    supported_depth_formats: RefCell<HashMap<usize, vk::Format>>,
}

/// The app uses a set scalar type in order to provide a simplistic API to users.
///
/// If you require changing the scalar type to something else, consider using a custom
/// **nannou::draw::Draw** instance.
pub type DrawScalar = geom::scalar::Default;

/// A handle to the **App** that can be shared across threads. This may be used to "wake up" the
/// **App**'s inner event loop.
pub struct Proxy {
    events_loop_proxy: winit::EventsLoopProxy,
    events_loop_is_asleep: Arc<AtomicBool>,
}

// The type returned by a mode-specific run loop within the `run_loop` function.
struct Break<M> {
    model: M,
    reason: BreakReason,
}

// The reason why the mode-specific run loop broke out of looping.
enum BreakReason {
    // The application has exited.
    Exit,
    // The LoopMode has been changed to the given mode.
    NewLoopMode(LoopMode),
}

// State related specifically to the application loop, shared between loop modes.
struct LoopContext<M, E> {
    // The user's application event function.
    event_fn: Option<EventFn<M, E>>,
    // The user's update function.
    update_fn: Option<UpdateFn<M>>,
    // The user's default function for drawing to a window's swapchain's image, used in the case
    // that the user has not provided a window-specific view function.
    default_view: Option<View<M>>,
    // The moment at which `run_loop` began.
    loop_start: Instant,
    // A buffer for collecting polled events.
    winit_events: Vec<winit::Event>,
    // The last instant that `update` was called. Initialised to `loop_start`.
    last_update: Instant,
    // The instant that the loop last ended. Initialised to `loop_start`.
    last_loop_end: Instant,
    // The number of updates yet to be called (for `LoopMode::Wait`).
    updates_remaining: usize,
}

/// The mode in which the **App** is currently running the event loop and emitting `Update` events.
#[derive(Clone, Debug, PartialEq)]
pub enum LoopMode {
    /// Specifies that the application is continuously looping at a consistent rate.
    ///
    /// An application running in the **Rate** loop mode will behave as follows:
    ///
    /// 1. Poll for and collect all pending user input. `event` is then called with all application
    ///    events that have occurred.
    ///
    /// 2. `event` is called with an `Update` event.
    ///
    /// 3. Check the time and sleep for the remainder of the `update_interval` then go to 1.
    ///
    /// `view` is called at an arbitraty rate by the vulkan swapchain for each window. It uses
    /// whatever the state of the user's model happens to be at that moment in time.
    Rate {
        /// The minimum interval between emitted updates.
        update_interval: Duration,
    },

    /// Waits for user input events to occur before calling `event` with an `Update` event.
    ///
    /// This is particularly useful for low-energy GUIs that only need to update when some sort of
    /// input has occurred. The benefit of using this mode is that you don't waste CPU cycles
    /// looping or updating when you know nothing is changing in your model or view.
    Wait {
        /// The number of `update`s (and in turn `view` calls per window) that should occur since
        /// the application last received a non-`Update` event.
        updates_following_event: usize,
        /// The minimum interval between emitted updates.
        update_interval: Duration,
    },

    /// Loops for the given number of updates and then finishes.
    ///
    /// This is similar to the **Wait** loop mode, except that windowing, application and input
    /// events will not cause the loop to update or view again after the initial
    /// `number_of_updates` have already been applied.
    ///
    /// This is useful for sketches where you only want to draw one frame, or if you know exactly
    /// how many updates you require for an animation, etc.
    NTimes {
        /// The number of updates that must be emited regardless of non-update events
        number_of_updates: usize,
        /// The minimum interval between emitted updates.
        update_interval: Duration,
    },

    /// Synchronises `Update` events with requests for a new image by the swapchain for each
    /// window in order to achieve minimal latency between the state of the model and what is
    /// displayed on screen. This mode should be particularly useful for interactive applications
    /// and games where minimal latency between user input and the display image is essential.
    ///
    /// The result of using this loop mode is similar to using vsync in traditional applications.
    /// E.g. if you have one window running on a monitor with a 60hz refresh rate, your update will
    /// get called at a fairly consistent interval that is close to 60 times per second.
    ///
    /// It is worth noting that, in the case that you have more than one window and they are
    /// situated on different displays with different refresh rates, `update` will almost certainly
    /// not be called at a consistent interval. Instead, it will be called as often as necessary -
    /// if it has been longer than `minimum_update_interval` or if some user input was received
    /// since the last `Update`. That said, each `Update` event contains the duration since the
    /// last `Update` occurred, so as long as all time-based state (like animations or physics
    /// simulations) are driven by this, the `update` interval consistency should not cause issues.
    ///
    /// ### The Swapchain
    ///
    /// The purpose of the swapchain for each window is to synchronise the presentation of images
    /// (calls to `view` in nannou) with the refresh rate of the screen. *You can learn more about
    /// the swap chain
    /// [here](https://vulkan-tutorial.com/Drawing_a_triangle/Presentation/Swap_chain).*
    RefreshSync {
        /// The minimum duration that must occur between calls to `update`. Under the `RefreshSync`
        /// mode, the application loop will attempt to emit an `Update` event once every time a new
        /// image is acquired from a window's swapchain. Thus, this value is very useful when
        /// working with multiple windows in order to avoid updating at an unnecessarily high rate.
        ///
        /// We recommend using a `Duration` that is roughly half the duration between refreshes of
        /// the window on the display with the highest refresh rate. For example, if the highest
        /// display refresh rate is 60hz (with an interval of ~16ms) a suitable
        /// `minimum_update_interval` might be 8ms. This should result in `update` being called
        /// once every 16ms regardless of the number of windows.
        minimum_update_interval: Duration,
        /// The windows to which `Update` events should be synchronised.
        ///
        /// If this is `Some`, an `Update` will only occur for those windows that are contained
        /// within this set. This is particularly useful if you only want to synchronise your
        /// updates with one or more "main" windows and you don't mind so much about the latency
        /// for the rest.
        ///
        /// If this is `None` (the default case), `Update` events will be synchronised with *all*
        /// windows.
        windows: Option<HashSet<window::Id>>,
    },
}

impl<M> Builder<M, Event>
where
    M: 'static,
{
    /// Begin building the `App`.
    ///
    /// The `model` argument is the function that the App will call to initialise your Model.
    ///
    /// The Model can be thought of as the state that you would like to track throughout the
    /// lifetime of your nannou program from start to exit.
    ///
    /// The given function is called before any event processing begins within the application.
    ///
    /// The Model that is returned by the function is the same model that will be passed to the
    /// given event and view functions.
    pub fn new(model: ModelFn<M>) -> Self {
        Builder {
            model,
            event: None,
            update: None,
            default_view: None,
            exit: None,
            vk_instance: None,
            vk_debug_callback: None,
            create_default_window: false,
            #[cfg(all(target_os = "macos", not(test)))]
            moltenvk_settings: None,
        }
    }

    /// The function that the app will call to allow you to update your Model on events.
    ///
    /// The `event` function allows you to expect any event type that implements `LoopEvent`,
    /// however nannou also provides a default `Event` type that should cover most use cases. This
    /// event type is an `enum` that describes all the different kinds of I/O events that might
    /// occur during the life of the program. These include things like `Update`s and
    /// `WindowEvent`s such as `KeyPressed`, `MouseMoved`, and so on.
    #[cfg_attr(rustfmt, rustfmt_skip)]
    pub fn event<E>(self, event: EventFn<M, E>) -> Builder<M, E>
    where
        E: LoopEvent,
    {
        let Builder {
            model,
            update,
            default_view,
            exit,
            create_default_window,
            vk_instance,
            vk_debug_callback,
            #[cfg(all(target_os = "macos", not(test)))]
            moltenvk_settings,
            ..
        } = self;
        Builder {
            model,
            event: Some(event),
            update,
            default_view,
            exit,
            create_default_window,
            vk_instance,
            vk_debug_callback,
            #[cfg(all(target_os = "macos", not(test)))]
            moltenvk_settings,
        }
    }
}

impl<M, E> Builder<M, E>
where
    M: 'static,
    E: LoopEvent,
{
    /// The default `view` function that the app will call to allow you to present your Model to
    /// the surface of a window on your display.
    ///
    /// This function will be used in the case that a window-specific view function has not been
    /// provided, e.g. via `window::Builder::view` or `window::Builder::sketch`.
    ///
    /// Note that when working with more than one window, you can use `frame.window_id()` to
    /// determine which window the current call is associated with.
    pub fn view(mut self, view: ViewFn<M>) -> Self {
        self.default_view = Some(View::WithModel(view));
        self
    }

    /// A function for updating the model within the application loop.
    ///
    /// See the `LoopMode` documentation for more information about the different kinds of
    /// application loop modes available in nannou and how they behave.
    ///
    /// Update events are also emitted as a variant of the `event` function. Note that if you
    /// specify both an `event` function and an `update` function, the `event` function will always
    /// be called with an update event prior to this `update` function.
    pub fn update(mut self, update: UpdateFn<M>) -> Self {
        self.update = Some(update);
        self
    }

    /// Tell the app that you would like it to create a single, simple, default window just before
    /// it calls your model function.
    ///
    /// The given `view` function will play the same role as if passed to the `view` builder
    /// method. Note that the `view` function passed to this method will overwrite any pre-existing
    /// view function specified by any preceding call to the `view`
    ///
    /// Note that calling this multiple times will not give you multiple windows, but instead will
    /// simply overwrite pre-existing calls to the method. If you would like to create multiple
    /// windows or would like more flexibility in your window creation process, please see the
    /// `App::new_window` method. The role of this `simple_window` method is to provide a
    /// quick-and-easy way to start with a simple window. This can be very useful for quick ideas,
    /// small single-window applications and examples.
    pub fn simple_window(mut self, view: ViewFn<M>) -> Self {
        self.default_view = Some(View::WithModel(view));
        self.create_default_window = true;
        self
    }

    /// Specify an `exit` function to be called when the application exits.
    ///
    /// The exit function gives ownership of the model back to you for any cleanup that might be
    /// necessary.
    pub fn exit(mut self, exit: ExitFn<M>) -> Self {
        self.exit = Some(exit);
        self
    }

    /// The vulkan instance to use for interfacing with the system vulkan API.
    ///
    /// If unspecified, nannou will create one via the following:
    ///
    /// ```norun
    /// # use nannou::prelude::*;
    /// # fn main() {
    /// vk::InstanceBuilder::new()
    ///     .build()
    ///     .expect("failed to creat vulkan instance")
    /// # ;
    /// # }
    /// ```
    ///
    /// If a `vk_debug_callback` was specified but the `vk_instance` is unspecified, nannou
    /// will do the following:
    ///
    /// ```norun
    /// # use nannou::prelude::*;
    /// # fn main() {
    /// vk::InstanceBuilder::new()
    ///     .extensions(vk::InstanceExtensions {
    ///         ext_debug_report: true,
    ///         ..vk::required_windowing_extensions()
    ///     })
    ///     .layers(vec!["VK_LAYER_LUNARG_standard_validation"])
    ///     .build()
    ///     .expect("failed to creat vulkan instance")
    /// # ;
    /// # }
    /// ```
    pub fn vk_instance(mut self, vk_instance: Arc<vk::Instance>) -> Self {
        self.vk_instance = Some(vk_instance);
        self
    }

    /// Specify a debug callback to be used with the vulkan instance.
    ///
    /// If you just want to print messages from the standard validation layers to stdout, you can
    /// call this method with `Default::default()` as the argument.
    ///
    /// Note that if you have specified a custom `vk_instance`, that instance must have the
    /// `ext_debug_report` extension enabled and must have been constructed with a debug layer.
    pub fn vk_debug_callback(mut self, debug_cb: vk::DebugCallbackBuilder) -> Self {
        self.vk_debug_callback = Some(debug_cb);
        self
    }

    #[cfg(all(target_os = "macos", not(test)))]
    /// Set custom settings for the moltenvk dependacy
    /// installer.
    ///
    /// Install silently
    /// `Install::Silent`
    /// Install with callbacks
    /// `Install::Message(message)`
    ///
    /// See moltenvk_deps::Message docs for more information.
    pub fn macos_installer(mut self, settings: mvkd::Install) -> Self {
        self.moltenvk_settings = Some(settings);
        self
    }

    /// Build and run an `App` with the specified parameters.
    ///
    /// This function will not return until the application has exited.
    ///
    /// If you wish to remain cross-platform frienly, we recommend that you call this on the main
    /// thread as some platforms require that their application event loop and windows are
    /// initialised on the main thread.
    pub fn run(mut self) {
        // Start the winit window event loop.
        let events_loop = winit::EventsLoop::new();

        // Keep track of whether or not a debug cb was specified so we know what default extensions
        // and layers are necessary.
        let debug_callback_specified = self.vk_debug_callback.is_some();

        #[cfg(all(target_os = "macos", not(test)))]
        let moltenvk_settings = self.moltenvk_settings;

        // The vulkan instance necessary for graphics.
        let vk_instance = self.vk_instance.take().unwrap_or_else(|| {
            if debug_callback_specified {
                let vk_builder = vk::InstanceBuilder::new();

                #[cfg(all(target_os = "macos", not(test)))]
                let vk_builder = vk::check_moltenvk(vk_builder, moltenvk_settings);

                #[cfg(any(not(target_os = "macos"), test))]
                let vk_builder = vk_builder.extensions(vk::required_windowing_extensions());

                vk_builder
                    .add_extensions(vk::InstanceExtensions {
                        ext_debug_report: true,
                        ..vk::InstanceExtensions::none()
                    })
                    .layers(vec!["VK_LAYER_LUNARG_standard_validation"])
                    .build()
                    .expect("failed to create vulkan instance")
            } else {
                let vk_builder = vk::InstanceBuilder::new();

                #[cfg(all(target_os = "macos", not(test)))]
                let vk_builder = vk::check_moltenvk(vk_builder, moltenvk_settings);

                #[cfg(any(not(target_os = "macos"), test))]
                let vk_builder = vk_builder.extensions(vk::required_windowing_extensions());

                vk_builder
                    .build()
                    .expect("failed to create vulkan instance")
            }
        });

        // If a callback was specified, build it with the created instance.
        let _vk_debug_callback = self.vk_debug_callback.take().map(|builder| {
            builder
                .build(&vk_instance)
                .expect("failed to build vulkan debug callback")
        });

        // Initialise the app.
        let app = App::new(events_loop, vk_instance).expect("failed to construct `App`");

        // Create the default window if necessary
        if self.create_default_window {
            let window_id = app
                .new_window()
                .build()
                .expect("could not build default app window");
            *app.focused_window.borrow_mut() = Some(window_id);
        }

        // Call the user's model function.
        let model = (self.model)(&app);

        // If there is not yet some default window in "focus" check to see if one has been created.
        if app.focused_window.borrow().is_none() {
            if let Some(id) = app.windows.borrow().keys().next() {
                *app.focused_window.borrow_mut() = Some(id.clone());
            }
        }

        // If the loop mode was set in the user's model function, ensure all window swapchains are
        // re-created appropriately.
        let loop_mode = app.loop_mode();
        if loop_mode != LoopMode::default() {
            let mut windows = app.windows.borrow_mut();
            for window in windows.values_mut() {
                let capabilities = window
                    .surface
                    .capabilities(window.swapchain.device().physical_device())
                    .expect("failed to get surface capabilities");
                let min_image_count = capabilities.min_image_count;
                let user_specified_present_mode = window.user_specified_present_mode;
                let user_specified_image_count = window.user_specified_image_count;
                let (present_mode, image_count) = window::preferred_present_mode_and_image_count(
                    &loop_mode,
                    min_image_count,
                    user_specified_present_mode,
                    user_specified_image_count,
                    &capabilities.present_modes,
                );
                if window.swapchain.present_mode() != present_mode
                    || window.swapchain.num_images() != image_count
                {
                    change_loop_mode_for_window(window, &loop_mode);
                }
            }
        }

        run_loop(
            app,
            model,
            self.event,
            self.update,
            self.default_view,
            self.exit,
        );
    }
}

impl Builder<(), Event> {
    /// Shorthand for building a simple app that has no model, handles no events and simply draws
    /// to a single window.
    ///
    /// This is useful for late night hack sessions where you just don't care about all that other
    /// stuff, you just want to play around with some ideas or make something pretty.
    pub fn sketch(view: SketchViewFn) {
        let builder: Self = Builder {
            model: default_model,
            event: None,
            update: None,
            default_view: Some(View::Sketch(view)),
            exit: None,
            create_default_window: true,
            vk_instance: None,
            vk_debug_callback: None,
            #[cfg(all(target_os = "macos", not(test)))]
            moltenvk_settings: None,
        };
        builder.run()
    }
}

/// Given some "frames per second", return the interval between frames as a `Duration`.
fn update_interval(fps: f64) -> Duration {
    assert!(fps > 0.0);
    const NANOSEC_PER_SEC: f64 = 1_000_000_000.0;
    let interval_nanosecs = NANOSEC_PER_SEC / fps;
    let secs = (interval_nanosecs / NANOSEC_PER_SEC) as u64;
    let nanosecs = (interval_nanosecs % NANOSEC_PER_SEC) as u32;
    Duration::new(secs, nanosecs)
}

impl LoopMode {
    pub const DEFAULT_RATE_FPS: f64 = 60.0;
    pub const DEFAULT_UPDATES_FOLLOWING_EVENT: usize = 3;

    /// Specify the **Rate** mode with the given frames-per-second.
    pub fn rate_fps(fps: f64) -> Self {
        let update_interval = update_interval(fps);
        LoopMode::Rate { update_interval }
    }

    /// Specify the **Wait** mode with the given number of updates following each non-`Update`
    /// event.
    ///
    /// Uses the default update interval.
    pub fn wait(updates_following_event: usize) -> Self {
        let update_interval = update_interval(Self::DEFAULT_RATE_FPS);
        LoopMode::Wait {
            updates_following_event,
            update_interval,
        }
    }

    /// Specify the **Wait** mode with the given number of updates following each non-`Update`
    /// event.
    ///
    /// Waits long enough to ensure loop iteration never occurs faster than the given `max_fps`.
    pub fn wait_with_max_fps(updates_following_event: usize, max_fps: f64) -> Self {
        let update_interval = update_interval(max_fps);
        LoopMode::Wait {
            updates_following_event,
            update_interval,
        }
    }

    /// Specify the **Wait** mode with the given number of updates following each non-`Update`
    /// event.
    ///
    /// Waits long enough to ensure loop iteration never occurs faster than the given `max_fps`.
    pub fn wait_with_interval(updates_following_event: usize, update_interval: Duration) -> Self {
        LoopMode::Wait {
            updates_following_event,
            update_interval,
        }
    }

    /// Specify the **Ntimes** mode with one update
    ///
    /// Waits long enough to ensure loop iteration never occurs faster than the given `max_fps`.
    pub fn loop_ntimes(number_of_updates: usize) -> Self {
        let update_interval = update_interval(Self::DEFAULT_RATE_FPS);
        LoopMode::NTimes {
            number_of_updates,
            update_interval,
        }
    }

    /// Specify the **Ntimes** mode with one update
    pub fn loop_once() -> Self {
        let update_interval = update_interval(Self::DEFAULT_RATE_FPS);
        let number_of_updates = 1;
        LoopMode::NTimes {
            number_of_updates,
            update_interval,
        }
    }

    /// A simplified constructor for the default `RefreshSync` loop mode.
    ///
    /// Assumes a display refresh rate of ~60hz and in turn specifies a `minimum_update_latency` of
    /// ~8.33ms. The `windows` field is set to `None`.
    pub fn refresh_sync() -> Self {
        LoopMode::RefreshSync {
            minimum_update_interval: update_interval(Self::DEFAULT_RATE_FPS * 2.0),
            windows: None,
        }
    }
}

impl Default for LoopMode {
    fn default() -> Self {
        LoopMode::refresh_sync()
    }
}

impl Default for Config {
    fn default() -> Self {
        let loop_mode = Default::default();
        let exit_on_escape = App::DEFAULT_EXIT_ON_ESCAPE;
        let fullscreen_on_shortcut = App::DEFAULT_FULLSCREEN_ON_SHORTCUT;
        Config {
            loop_mode,
            exit_on_escape,
            fullscreen_on_shortcut,
        }
    }
}

impl App {
    pub const ASSETS_DIRECTORY_NAME: &'static str = "assets";
    pub const DEFAULT_EXIT_ON_ESCAPE: bool = true;
    pub const DEFAULT_FULLSCREEN_ON_SHORTCUT: bool = true;

    // Create a new `App`.
    pub(super) fn new(
        events_loop: winit::EventsLoop,
        vk_instance: Arc<vk::Instance>,
    ) -> Result<Self, vk::InstanceCreationError> {
        let windows = RefCell::new(HashMap::new());
        let draw = RefCell::new(draw::Draw::default());
        let config = RefCell::new(Default::default());
        let renderers = RefCell::new(Default::default());
        let supported_depth_formats = RefCell::new(HashMap::new());
        let draw_state = DrawState {
            draw,
            renderers,
            supported_depth_formats,
        };
        let focused_window = RefCell::new(None);
        let ui = ui::Arrangement::new();
        let mouse = state::Mouse::new();
        let keys = state::Keys::default();
        let duration = state::Time::default();
        let time = duration.since_start.secs() as _;
        let events_loop_is_asleep = Arc::new(AtomicBool::new(false));
        let app = App {
            vk_instance,
            events_loop,
            events_loop_is_asleep,
            focused_window,
            windows,
            config,
            draw_state,
            ui,
            mouse,
            keys,
            duration,
            time,
        };
        Ok(app)
    }

    /// A reference to the vulkan instance associated with the `App`.
    ///
    /// If you would like to construct the app with a custom vulkan instance, see the
    /// `app::Builder::vk_instance` method.
    pub fn vk_instance(&self) -> &Arc<vk::instance::Instance> {
        &self.vk_instance
    }

    /// Returns an iterator yielding each of the physical devices on the system that are vulkan
    /// compatible.
    ///
    /// If a physical device is not specified for a window surface's swapchain, the first device
    /// yielded by this iterator is used as the default.
    pub fn vk_physical_devices(&self) -> vk::instance::PhysicalDevicesIter {
        vk::instance::PhysicalDevice::enumerate(&self.vk_instance)
    }

    /// Retrieve the default vulkan physical device.
    ///
    /// This is simply the first device yielded by the `vk_physical_devices` method.
    pub fn default_vk_physical_device(&self) -> Option<vk::instance::PhysicalDevice> {
        self.vk_physical_devices().next()
    }

    /// Find and return the absolute path to the project's `assets` directory.
    ///
    /// This method looks for the assets directory in the following order:
    ///
    /// 1. Checks the same directory as the executable.
    /// 2. Recursively checks exe's parent directories (to a max depth of 5).
    /// 3. Recursively checks exe's children directories (to a max depth of 3).
    pub fn assets_path(&self) -> Result<PathBuf, find_folder::Error> {
        find_assets_path()
    }

    /// Begin building a new window.
    pub fn new_window(&self) -> window::Builder {
        window::Builder::new(self)
    }

    /// The number of windows currently in the application.
    pub fn window_count(&self) -> usize {
        self.windows.borrow().len()
    }

    /// A reference to the window with the given `Id`.
    pub fn window(&self, id: window::Id) -> Option<std::cell::Ref<Window>> {
        let windows = self.windows.borrow();
        if !windows.contains_key(&id) {
            None
        } else {
            Some(std::cell::Ref::map(windows, |ws| &ws[&id]))
        }
    }

    /// Return the **Id** of the currently focused window.
    ///
    /// **Panics** if there are no windows or if no window is in focus.
    pub fn window_id(&self) -> window::Id {
        self.focused_window
            .borrow()
            .expect("called `App::window_id` but there is no window currently in focus")
    }

    /// Return a `Vec` containing a unique `window::Id` for each currently open window managed by
    /// the `App`.
    pub fn window_ids(&self) -> Vec<window::Id> {
        let windows = self.windows.borrow();
        windows.keys().cloned().collect()
    }

    /// Return the **Rect** for the currently focused window.
    ///
    /// The **Rect** coords are described in "points" (pixels divided by the hidpi factor).
    ///
    /// **Panics** if there are no windows or if no window is in focus.
    pub fn window_rect(&self) -> geom::Rect<DrawScalar> {
        let (w, h) = self.main_window().inner_size_points();
        geom::Rect::from_w_h(w as _, h as _)
    }

    /// A reference to the window currently in focus.
    ///
    /// **Panics** if their are no windows open in the **App**.
    ///
    /// Uses the **App::window** method internally.
    ///
    /// TODO: Currently this produces a reference to the *focused* window, but this behaviour
    /// should be changed to track the "main" window (the first window created?).
    pub fn main_window(&self) -> std::cell::Ref<Window> {
        self.window(self.window_id())
            .expect("no window for focused id")
    }

    /// Return whether or not the `App` is currently set to exit when the `Escape` key is pressed.
    pub fn exit_on_escape(&self) -> bool {
        self.config.borrow().exit_on_escape
    }

    /// Specify whether or not the app should close when the `Escape` key is pressed.
    ///
    /// By default this is `true`.
    pub fn set_exit_on_escape(&self, b: bool) {
        self.config.borrow_mut().exit_on_escape = b;
    }

    /// Returns whether or not the `App` is currently allows the focused window to enter or exit
    /// fullscreen via typical platform-specific shortcuts.
    ///
    /// - Linux uses F11.
    /// - macOS uses apple key + f.
    /// - Windows uses windows key + f.
    pub fn fullscreen_on_shortcut(&self) -> bool {
        self.config.borrow().fullscreen_on_shortcut
    }

    /// Set whether or not the `App` should allow the focused window to enter or exit fullscreen
    /// via typical platform-specific shortcuts.
    ///
    /// - Linux uses F11.
    /// - macOS uses apple key + f.
    /// - Windows uses windows key + f.
    pub fn set_fullscreen_on_shortcut(&self, b: bool) {
        self.config.borrow_mut().fullscreen_on_shortcut = b;
    }

    /// Returns the **App**'s current **LoopMode**.
    ///
    /// The default loop mode is `Rate` at 60 frames per second (an `update_interval` of ~16ms).
    pub fn loop_mode(&self) -> LoopMode {
        self.config.borrow().loop_mode.clone()
    }

    /// Sets the loop mode of the **App**.
    ///
    /// Note: Setting the loop mode will not affect anything until the end of the current loop
    /// iteration. The behaviour of a single loop iteration is described under each of the
    /// **LoopMode** variants.
    pub fn set_loop_mode(&self, mode: LoopMode) {
        self.config.borrow_mut().loop_mode = mode;
    }

    /// A handle to the **App** that can be shared across threads.
    ///
    /// This can be used to "wake up" the **App**'s inner event loop.
    pub fn create_proxy(&self) -> Proxy {
        let events_loop_proxy = self.events_loop.create_proxy();
        let events_loop_is_asleep = self.events_loop_is_asleep.clone();
        Proxy {
            events_loop_proxy,
            events_loop_is_asleep,
        }
    }

    /// A builder for creating a new **Ui**.
    ///
    /// Each **Ui** is associated with one specific window. By default, this is the window returned
    /// by `App::window_id` (the currently focused window).
    pub fn new_ui(&self) -> ui::Builder {
        ui::Builder::new(self)
    }

    /// Produce the **App**'s **Draw** API for drawing geometry and text with colors and textures.
    ///
    /// **Note:** There may only be a single **app::Draw** instance at any point in time. If this
    /// method is called while there is a pre-existing instance of **app::Draw** this method will
    /// **panic**.
    ///
    /// Returns **None** if there is no window for the given **window::Id**.
    pub fn draw_for_window(&self, window_id: window::Id) -> Option<Draw> {
        let window = match self.window(window_id) {
            None => return None,
            Some(window) => window,
        };
        let queue = window.swapchain_queue().clone();
        let device = queue.device().clone();
        let color_format = crate::frame::COLOR_FORMAT;
        let mut supported_depth_formats = self.draw_state.supported_depth_formats.borrow_mut();
        let depth_format = *supported_depth_formats
            .entry(device.physical_device().index())
            .or_insert_with(|| {
                find_draw_depth_format(device)
                    .expect("no supported vulkan depth format for the App's `Draw` API")
            });
        let draw = self.draw_state.draw.borrow_mut();
        draw.reset();

        let renderers = self.draw_state.renderers.borrow_mut();
        let renderer = RefMut::map(renderers, |renderers| {
            renderers.entry(window_id).or_insert_with(|| {
                let msaa_samples = window.msaa_samples();
                let (px_w, px_h) = window.inner_size_pixels();
                // TODO: This should be configurable.
                let glyph_cache_dims = [px_w, px_h];
                let renderer = draw::backend::vulkano::Renderer::new(
                    queue,
                    color_format,
                    depth_format,
                    msaa_samples,
                    glyph_cache_dims,
                )
                .expect("failed to create `Draw` renderer for vulkano backend");
                RefCell::new(renderer)
            })
        });
        Some(Draw {
            window_id,
            draw,
            renderer,
            depth_format,
        })
    }

    /// Produce the **App**'s **Draw** API for drawing geometry and text with colors and textures.
    ///
    /// This is a simplified wrapper around the **App::draw_for_window** method that draws to the
    /// window currently in focus.
    ///
    /// **Panics** if there are no windows open.
    ///
    /// **Note:** There may only be a single **app::Draw** instance at any point in time. If this
    /// method is called while there is a pre-existing instance of **app::Draw** this method will
    /// **panic**.
    pub fn draw(&self) -> Draw {
        self.draw_for_window(self.window_id())
            .expect("no window open for `app.window_id`")
    }

    /// The number of times the focused window's **view** function has been called since the start
    /// of the program.
    pub fn elapsed_frames(&self) -> u64 {
        self.main_window().frame_count
    }

    /// The number of frames that can currently be displayed a second
    pub fn fps(&self) -> f32 {
        self.duration.updates_per_second()
    }
}

impl Proxy {
    /// Wake up the application!
    ///
    /// This wakes up the **App**'s inner event loop and inserts an **Awakened** event.
    ///
    /// The `app::Proxy` stores a flag in order to track whether or not the `EventsLoop` is
    /// currently blocking and waiting for events. This method will only call the underlying
    /// `winit::EventsLoopProxy::wakeup` method if this flag is set to true and will immediately
    /// set the flag to false afterwards. This makes it safe to call the `wakeup` method as
    /// frequently as necessary across methods without causing any underlying OS methods to be
    /// called more than necessary.
    pub fn wakeup(&self) -> Result<(), winit::EventsLoopClosed> {
        if self.events_loop_is_asleep.load(atomic::Ordering::Relaxed) {
            self.events_loop_proxy.wakeup()?;
            self.events_loop_is_asleep
                .store(false, atomic::Ordering::Relaxed);
        }
        Ok(())
    }
}

impl<'a> Draw<'a> {
    /// Draw the current state of the inner mesh to the given frame.
    pub fn to_frame(
        &self,
        app: &App,
        frame: &Frame,
    ) -> Result<(), draw::backend::vulkano::DrawError> {
        let window = app
            .window(self.window_id)
            .expect("no window to draw to for `app::Draw`'s window_id");
        assert_eq!(
            self.window_id,
            frame.window_id(),
            "attempted to draw content intended for window {:?} in a frame \
             associated with window {:?}",
            self.window_id,
            frame.window_id(),
        );
        let dpi_factor = window.hidpi_factor();
        let mut renderer = self.renderer.borrow_mut();
        renderer.draw_to_frame(&self.draw, dpi_factor, frame, self.depth_format)
    }
}

impl<'a> Deref for Draw<'a> {
    type Target = RefMut<'a, draw::Draw<DrawScalar>>;
    fn deref(&self) -> &Self::Target {
        &self.draw
    }
}

impl<'a> DerefMut for Draw<'a> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.draw
    }
}

/// Attempt to find the assets directory path relative to the executable location.
pub fn find_assets_path() -> Result<PathBuf, find_folder::Error> {
    let exe_path = std::env::current_exe()?;
    find_folder::Search::ParentsThenKids(5, 3)
        .of(exe_path
            .parent()
            .expect("executable has no parent directory to search")
            .into())
        .for_folder(App::ASSETS_DIRECTORY_NAME)
}

/// Find a compatible depth format for the `App`'s `Draw` API.
pub fn find_draw_depth_format(device: Arc<vk::Device>) -> Option<vk::Format> {
    let candidates = [
        vk::Format::D32Sfloat,
        vk::Format::D32Sfloat_S8Uint,
        vk::Format::D24Unorm_S8Uint,
        vk::Format::D16Unorm,
        vk::Format::D16Unorm_S8Uint,
    ];
    vk::find_supported_depth_image_format(device, &candidates)
}

// Application Loop.
//
// Beyond this point lies the master function for running the main application loop!
//
// This is undoubtedly the hairiest part of nannou's code base. This is largely due to the fact
// that it is the part of nannou where we marry application and user input events, loop timing,
// updating the model, platform-specific quirks and warts, the various possible `LoopMode`s and
// Vulkan interop.
//
// If you would like to contribute but are unsure about any of the following, feel free to open an
// issue and ask!
fn run_loop<M, E>(
    mut app: App,
    mut model: M,
    event_fn: Option<EventFn<M, E>>,
    update_fn: Option<UpdateFn<M>>,
    default_view: Option<View<M>>,
    exit_fn: Option<ExitFn<M>>,
) where
    M: 'static,
    E: LoopEvent,
{
    let loop_start = Instant::now();

    // Initialise the loop context.
    let mut loop_ctxt = LoopContext {
        event_fn,
        update_fn,
        default_view,
        loop_start,
        winit_events: vec![],
        last_update: loop_start,
        last_loop_end: loop_start,
        updates_remaining: LoopMode::DEFAULT_UPDATES_FOLLOWING_EVENT,
    };

    let mut loop_mode = app.loop_mode();

    // Begin running the application loop based on the current `LoopMode`.
    'mode: loop {
        let Break {
            model: new_model,
            reason,
        } = match loop_mode {
            LoopMode::Rate { update_interval } => {
                run_loop_mode_rate(&mut app, model, &mut loop_ctxt, update_interval)
            }
            LoopMode::Wait {
                updates_following_event,
                update_interval,
            } => {
                loop_ctxt.updates_remaining = updates_following_event;
                run_loop_mode_wait(
                    &mut app,
                    model,
                    &mut loop_ctxt,
                    updates_following_event,
                    update_interval,
                )
            }
            LoopMode::NTimes {
                number_of_updates,
                update_interval,
            } => {
                loop_ctxt.updates_remaining = number_of_updates;
                run_loop_mode_ntimes(&mut app, model, &mut loop_ctxt, update_interval)
            }
            LoopMode::RefreshSync {
                minimum_update_interval,
                windows,
            } => run_loop_mode_refresh_sync(
                &mut app,
                model,
                &mut loop_ctxt,
                minimum_update_interval,
                windows,
            ),
        };

        model = new_model;
        match reason {
            // If the break reason was due to the `LoopMode` changing, switch to the new loop mode
            // and continue.
            BreakReason::NewLoopMode(new_loop_mode) => {
                loop_mode = new_loop_mode;
                change_loop_mode(&app, &loop_mode);
            }
            // If the loop broke due to the application exiting, we're done!
            BreakReason::Exit => {
                if let Some(exit_fn) = exit_fn {
                    exit_fn(&app, model);
                }
                return;
            }
        }
    }
}

// Run the application loop under the `Rate` mode.
fn run_loop_mode_rate<M, E>(
    app: &mut App,
    mut model: M,
    loop_ctxt: &mut LoopContext<M, E>,
    mut update_interval: Duration,
) -> Break<M>
where
    M: 'static,
    E: LoopEvent,
{
    loop {
        // Handle any pending window events.
        app.events_loop
            .poll_events(|event| loop_ctxt.winit_events.push(event));
        for winit_event in loop_ctxt.winit_events.drain(..) {
            let (new_model, exit) =
                process_and_emit_winit_event(app, model, loop_ctxt.event_fn, winit_event);
            model = new_model;
            if exit {
                let reason = BreakReason::Exit;
                return Break { model, reason };
            }
        }

        // Update the app's durations.
        let now = Instant::now();
        let since_last = now.duration_since(loop_ctxt.last_update).into();
        let since_start = now.duration_since(loop_ctxt.loop_start).into();
        app.duration.since_start = since_start;
        app.duration.since_prev_update = since_last;
        app.time = app.duration.since_start.secs() as _;

        // Emit an update event.
        let update = update_event(loop_ctxt.loop_start, &mut loop_ctxt.last_update);
        if let Some(event_fn) = loop_ctxt.event_fn {
            let event = E::from(update.clone());
            event_fn(&app, &mut model, event);
        }
        if let Some(update_fn) = loop_ctxt.update_fn {
            update_fn(&app, &mut model, update);
        }

        // Draw to each window.
        for window_id in app.window_ids() {
            acquire_image_and_view_frame(app, window_id, &model, loop_ctxt.default_view.as_ref());
        }

        // Sleep if there's still some time left within the interval.
        let now = Instant::now();
        let since_last_loop_end = now.duration_since(loop_ctxt.last_loop_end);
        if since_last_loop_end < update_interval {
            std::thread::sleep(update_interval - since_last_loop_end);
        }
        loop_ctxt.last_loop_end = Instant::now();

        // See if the loop mode has changed. If so, break.
        update_interval = match app.loop_mode() {
            LoopMode::Rate { update_interval } => update_interval,
            loop_mode => {
                let reason = BreakReason::NewLoopMode(loop_mode);
                return Break { model, reason };
            }
        };
    }
}

// Run the application loop under the `Wait` mode.
fn run_loop_mode_wait<M, E>(
    app: &mut App,
    mut model: M,
    loop_ctxt: &mut LoopContext<M, E>,
    mut updates_following_event: usize,
    mut update_interval: Duration,
) -> Break<M>
where
    M: 'static,
    E: LoopEvent,
{
    loop {
        // First collect any pending window events.
        app.events_loop
            .poll_events(|event| loop_ctxt.winit_events.push(event));

        // If there are no events and the `Ui` does not need updating,
        // wait for the next event.
        if loop_ctxt.winit_events.is_empty() && loop_ctxt.updates_remaining == 0 {
            let events_loop_is_asleep = app.events_loop_is_asleep.clone();
            events_loop_is_asleep.store(true, atomic::Ordering::Relaxed);
            app.events_loop.run_forever(|event| {
                events_loop_is_asleep.store(false, atomic::Ordering::Relaxed);
                loop_ctxt.winit_events.push(event);
                winit::ControlFlow::Break
            });
        }

        // If there are some winit events to process, reset the updates-remaining count.
        if !loop_ctxt.winit_events.is_empty() {
            loop_ctxt.updates_remaining = updates_following_event;
        }

        for winit_event in loop_ctxt.winit_events.drain(..) {
            let (new_model, exit) =
                process_and_emit_winit_event(app, model, loop_ctxt.event_fn, winit_event);
            model = new_model;
            if exit {
                let reason = BreakReason::Exit;
                return Break { model, reason };
            }
        }

        // Update the app's durations.
        let now = Instant::now();
        let since_last = now.duration_since(loop_ctxt.last_update).into();
        let since_start = now.duration_since(loop_ctxt.loop_start).into();
        app.duration.since_start = since_start;
        app.duration.since_prev_update = since_last;
        app.time = app.duration.since_start.secs() as _;

        // Emit an update event.
        let update = update_event(loop_ctxt.loop_start, &mut loop_ctxt.last_update);
        if let Some(event_fn) = loop_ctxt.event_fn {
            let event = E::from(update.clone());
            event_fn(&app, &mut model, event);
        }
        if let Some(update_fn) = loop_ctxt.update_fn {
            update_fn(&app, &mut model, update);
        }
        loop_ctxt.updates_remaining -= 1;

        // Draw to each window.
        for window_id in app.window_ids() {
            acquire_image_and_view_frame(app, window_id, &model, loop_ctxt.default_view.as_ref());
        }

        // Sleep if there's still some time left within the interval.
        let now = Instant::now();
        let since_last_loop_end = now.duration_since(loop_ctxt.last_loop_end);
        if since_last_loop_end < update_interval {
            std::thread::sleep(update_interval - since_last_loop_end);
        }
        loop_ctxt.last_loop_end = Instant::now();

        // See if the loop mode has changed. If so, break.
        match app.loop_mode() {
            LoopMode::Wait {
                update_interval: ui,
                updates_following_event: ufe,
            } => {
                update_interval = ui;
                updates_following_event = ufe;
            }
            loop_mode => {
                let reason = BreakReason::NewLoopMode(loop_mode);
                return Break { model, reason };
            }
        };
    }
}

// Run the application loop under the `NTimes` mode.
fn run_loop_mode_ntimes<M, E>(
    app: &mut App,
    mut model: M,
    loop_ctxt: &mut LoopContext<M, E>,
    mut update_interval: Duration,
) -> Break<M>
where
    M: 'static,
    E: LoopEvent,
{
    loop {
        // First collect any pending window events.
        app.events_loop
            .poll_events(|event| loop_ctxt.winit_events.push(event));

        // If there are no events and the `Ui` does not need updating,
        // wait for the next event.
        if loop_ctxt.winit_events.is_empty() && loop_ctxt.updates_remaining == 0 {
            let events_loop_is_asleep = app.events_loop_is_asleep.clone();
            events_loop_is_asleep.store(true, atomic::Ordering::Relaxed);
            app.events_loop.run_forever(|event| {
                events_loop_is_asleep.store(false, atomic::Ordering::Relaxed);
                loop_ctxt.winit_events.push(event);
                winit::ControlFlow::Break
            });
        }

        // Update the app's durations.
        let now = Instant::now();
        let since_last = now.duration_since(loop_ctxt.last_update).into();
        let since_start = now.duration_since(loop_ctxt.loop_start).into();
        app.duration.since_start = since_start;
        app.duration.since_prev_update = since_last;
        app.time = app.duration.since_start.secs() as _;

        for winit_event in loop_ctxt.winit_events.drain(..) {
            let (new_model, exit) =
                process_and_emit_winit_event(app, model, loop_ctxt.event_fn, winit_event);
            model = new_model;
            if exit {
                let reason = BreakReason::Exit;
                return Break { model, reason };
            }
        }

        // Only `update` and `view` if there are updates remaining.
        if loop_ctxt.updates_remaining > 0 {
            let update = update_event(loop_ctxt.loop_start, &mut loop_ctxt.last_update);
            if let Some(event_fn) = loop_ctxt.event_fn {
                let event = E::from(update.clone());
                event_fn(&app, &mut model, event);
            }
            if let Some(update_fn) = loop_ctxt.update_fn {
                update_fn(&app, &mut model, update);
            }
            loop_ctxt.updates_remaining -= 1;

            // Draw to each window.
            for window_id in app.window_ids() {
                acquire_image_and_view_frame(
                    app,
                    window_id,
                    &model,
                    loop_ctxt.default_view.as_ref(),
                );
            }
        }

        // Sleep if there's still some time left within the interval.
        let now = Instant::now();
        let since_last_loop_end = now.duration_since(loop_ctxt.last_loop_end);
        if since_last_loop_end < update_interval {
            std::thread::sleep(update_interval - since_last_loop_end);
        }
        loop_ctxt.last_loop_end = Instant::now();

        // See if the loop mode has changed. If so, break.
        match app.loop_mode() {
            LoopMode::NTimes {
                update_interval: ui,
                ..
            } => {
                update_interval = ui;
            }
            loop_mode => {
                let reason = BreakReason::NewLoopMode(loop_mode);
                return Break { model, reason };
            }
        };
    }
}
// Run the application loop under the `RefreshSync` mode.
fn run_loop_mode_refresh_sync<M, E>(
    app: &mut App,
    mut model: M,
    loop_ctxt: &mut LoopContext<M, E>,
    mut minimum_update_interval: Duration,
    mut windows: Option<HashSet<window::Id>>,
) -> Break<M>
where
    M: 'static,
    E: LoopEvent,
{
    loop {
        // TODO: Properly consider the impact of an individual window blocking.
        for window_id in app.window_ids() {
            // Skip closed windows.
            if app.window(window_id).is_none() {
                continue;
            }

            cleanup_unused_gpu_resources_for_window(app, window_id);

            // Ensure swapchain dimensions are up to date.
            loop {
                if window_swapchain_needs_recreation(app, window_id) {
                    match recreate_window_swapchain(app, window_id) {
                        Ok(()) => break,
                        Err(vk::SwapchainCreationError::UnsupportedDimensions) => {
                            set_window_swapchain_needs_recreation(app, window_id, true);
                            continue;
                        }
                        Err(err) => panic!("{:?}", err),
                    }
                }
                break;
            }

            // Acquire the next image from the swapchain.
            let timeout = None;
            let swapchain = app.windows.borrow()[&window_id].swapchain.clone();
            let next_img = vk::swapchain::acquire_next_image(swapchain.swapchain.clone(), timeout);
            let (swapchain_image_index, swapchain_image_acquire_future) = match next_img {
                Ok(r) => r,
                Err(vk::swapchain::AcquireError::OutOfDate) => {
                    set_window_swapchain_needs_recreation(app, window_id, true);
                    continue;
                }
                Err(err) => panic!("{:?}", err),
            };

            // Process pending app events.
            let (new_model, exit, event_count) = poll_and_process_events(app, model, loop_ctxt);
            model = new_model;
            if exit {
                let reason = BreakReason::Exit;
                return Break { model, reason };
            }

            // Only emit an `update` if there was some user input or if it's been more than
            // `minimum_update_interval`.
            let now = Instant::now();
            let since_last = now.duration_since(loop_ctxt.last_update).into();
            let should_emit_update = windows
                .as_ref()
                .map(|ws| ws.contains(&window_id))
                .unwrap_or(true)
                && (event_count > 0 || since_last > minimum_update_interval);
            if should_emit_update {
                let since_start = now.duration_since(loop_ctxt.loop_start).into();
                app.duration.since_start = since_start;
                app.duration.since_prev_update = since_last;
                app.time = app.duration.since_start.secs() as _;

                // Emit an update event.
                let update = update_event(loop_ctxt.loop_start, &mut loop_ctxt.last_update);
                if let Some(event_fn) = loop_ctxt.event_fn {
                    let event = E::from(update.clone());
                    event_fn(&app, &mut model, event);
                }
                if let Some(update_fn) = loop_ctxt.update_fn {
                    update_fn(&app, &mut model, update);
                }
            }

            // If the window has been removed, continue.
            if app.window(window_id).is_none() {
                continue;
            }

            view_frame(
                app,
                &model,
                window_id,
                swapchain_image_index,
                swapchain_image_acquire_future,
                loop_ctxt.default_view.as_ref(),
            );
        }

        loop_ctxt.last_loop_end = Instant::now();

        // See if the loop mode has changed. If so, break.
        match app.loop_mode() {
            LoopMode::RefreshSync {
                minimum_update_interval: mli,
                windows: w,
            } => {
                minimum_update_interval = mli;
                windows = w;
            }
            loop_mode => {
                let reason = BreakReason::NewLoopMode(loop_mode);
                return Break { model, reason };
            }
        }
    }
}

// Recreate window swapchains as necessary due to `loop_mode` switch.
fn change_loop_mode(app: &App, loop_mode: &LoopMode) {
    // Re-build the window swapchains so that they are optimal for the new loop mode.
    let mut windows = app.windows.borrow_mut();
    for window in windows.values_mut() {
        change_loop_mode_for_window(window, loop_mode);
    }
}

// Recreate the window swapchain to match the loop mode.
fn change_loop_mode_for_window(window: &mut Window, loop_mode: &LoopMode) {
    let device = window.swapchain.swapchain.device().clone();
    let surface = window.surface.clone();
    let queue = window.queue.clone();

    // Initialise a swapchain builder from the current swapchain's params.
    let mut swapchain_builder =
        window::SwapchainBuilder::from_swapchain(&window.swapchain.swapchain);

    // Let the new present mode and image count be chosen by nannou or the user if
    // they have a preference.
    swapchain_builder.present_mode = window.user_specified_present_mode;
    swapchain_builder.image_count = window.user_specified_image_count;

    // Create the new swapchain.
    let (new_swapchain, new_swapchain_images) = swapchain_builder
        .build(
            device,
            surface,
            &queue,
            &loop_mode,
            None,
            Some(&window.swapchain.swapchain),
        )
        .expect("failed to recreate swapchain for new `LoopMode`");

    // Replace the window's swapchain with the newly created one.
    window.replace_swapchain(new_swapchain, new_swapchain_images);
}

// Each window has its own associated GPU future associated with displaying the last frame.
// This method cleans up any unused resources associated with this GPU future.
fn cleanup_unused_gpu_resources_for_window(app: &App, window_id: window::Id) {
    let windows = app.windows.borrow();
    let mut guard = windows[&window_id]
        .swapchain
        .previous_frame_end
        .lock()
        .expect("failed to lock `previous_frame_end`");
    if let Some(future) = guard.as_mut() {
        future.cleanup_finished();
    }
}

// Returns `true` if the window's swapchain needs to be recreated.
fn window_swapchain_needs_recreation(app: &App, window_id: window::Id) -> bool {
    let windows = app.windows.borrow();
    let window = &windows[&window_id];
    window
        .swapchain
        .needs_recreation
        .load(atomic::Ordering::Relaxed)
}

// Attempt to recreate a window's swapchain with the window's current dimensions.
fn recreate_window_swapchain(
    app: &App,
    window_id: window::Id,
) -> Result<(), vk::SwapchainCreationError> {
    let mut windows = app.windows.borrow_mut();
    let window = windows.get_mut(&window_id).expect("no window for id");

    // Get the new dimensions for the viewport/framebuffers.
    let dimensions = window
        .surface
        .capabilities(window.swapchain.device().physical_device())
        .expect("failed to get surface capabilities")
        .current_extent
        .expect("current_extent was `None`");

    // Recreate the swapchain with the current dimensions.
    let (new_swapchain, new_images) = window
        .swapchain
        .swapchain
        .recreate_with_dimension(dimensions)?;

    // Update the window's swapchain and images.
    window.replace_swapchain(new_swapchain, new_images);

    Ok(())
}

// Shorthand for setting a window's swapchain.needs_recreation atomic bool.
fn set_window_swapchain_needs_recreation(app: &App, window_id: window::Id, b: bool) {
    let windows = app.windows.borrow_mut();
    let window = windows.get(&window_id).expect("no window for id");
    window
        .swapchain
        .needs_recreation
        .store(b, atomic::Ordering::Relaxed);
}

// Poll and process any pending application events.
//
// Returns:
//
// - the resulting state of the model.
// - whether or not an event should cause exiting the application loop.
// - the number of winit events processed processed.
fn poll_and_process_events<M, E>(
    app: &mut App,
    mut model: M,
    loop_ctxt: &mut LoopContext<M, E>,
) -> (M, bool, usize)
where
    M: 'static,
    E: LoopEvent,
{
    let mut event_count = 0;
    app.events_loop
        .poll_events(|event| loop_ctxt.winit_events.push(event));
    for winit_event in loop_ctxt.winit_events.drain(..) {
        event_count += 1;
        let (new_model, exit) =
            process_and_emit_winit_event(app, model, loop_ctxt.event_fn, winit_event);
        model = new_model;
        if exit {
            return (model, exit, event_count);
        }
    }
    (model, false, event_count)
}

// Whether or not the given event should toggle fullscreen.
fn should_toggle_fullscreen(winit_event: &winit::WindowEvent) -> bool {
    let input = match *winit_event {
        winit::WindowEvent::KeyboardInput { ref input, .. } => match input.state {
            event::ElementState::Pressed => input,
            _ => return false,
        },
        _ => return false,
    };

    let key = match input.virtual_keycode {
        None => return false,
        Some(k) => k,
    };
    let mods = &input.modifiers;

    // On linux, check for the F11 key (with no modifiers down).
    //
    // TODO: Somehow add special case for KDE?
    if cfg!(target_os = "linux") {
        if !mods.logo && !mods.shift && !mods.alt && !mods.ctrl {
            if let Key::F11 = key {
                return true;
            }
        }

    // On macos and windows check for the logo key plus `f` with no other modifiers.
    } else if cfg!(target_os = "macos") || cfg!(target_os = "windows") {
        if mods.logo && !mods.shift && !mods.alt && !mods.ctrl {
            if let Key::F = key {
                return true;
            }
        }
    }

    false
}

// A function to simplify the creation of an `Update` event.
//
// Also updates the given `last_update` instant to `Instant::now()`.
fn update_event(loop_start: Instant, last_update: &mut Instant) -> event::Update {
    // Emit an update event.
    let now = Instant::now();
    let since_last = now.duration_since(*last_update).into();
    let since_start = now.duration_since(loop_start).into();
    let update = event::Update {
        since_last,
        since_start,
    };
    *last_update = now;
    update
}

// Event handling boilerplate shared between the `Rate` and `Wait` loop modes.
//
// 1. Checks for exit on escape.
// 2. Removes closed windows from app.
// 3. Emits event via `event_fn`.
// 4. Returns whether or not we should break from the loop.
fn process_and_emit_winit_event<M, E>(
    app: &mut App,
    mut model: M,
    event_fn: Option<EventFn<M, E>>,
    winit_event: winit::Event,
) -> (M, bool)
where
    M: 'static,
    E: LoopEvent,
{
    // Inspect the event to see if it would require closing the App.
    let mut exit_on_escape = false;
    let mut removed_window = None;
    if let winit::Event::WindowEvent {
        window_id,
        ref event,
    } = winit_event
    {
        // If we should exit the app on escape, check for the escape key.
        if app.exit_on_escape() {
            if let winit::WindowEvent::KeyboardInput { input, .. } = *event {
                if let Some(Key::Escape) = input.virtual_keycode {
                    exit_on_escape = true;
                }
            }
        }

        // When a window has been closed, this function is called to remove any state associated
        // with that window so that the state doesn't leak.
        //
        // Returns the `Window` that was removed.
        fn remove_related_window_state(app: &App, window_id: &window::Id) -> Option<Window> {
            app.draw_state.renderers.borrow_mut().remove(window_id);
            app.windows.borrow_mut().remove(window_id)
        }

        if let winit::WindowEvent::Destroyed = *event {
            removed_window = remove_related_window_state(app, &window_id);
        // TODO: We should allow the user to handle this case. E.g. allow for doing things like
        // "would you like to save". We currently do this with the app exit function, but maybe a
        // window `close` function would be useful?
        } else if let winit::WindowEvent::CloseRequested = *event {
            removed_window = remove_related_window_state(app, &window_id);
        } else {
            // Get the size of the window for translating coords and dimensions.
            let (win_w, win_h) = match app.window(window_id) {
                Some(win) => {
                    // If we should toggle fullscreen for this window, do so.
                    if app.fullscreen_on_shortcut() {
                        if should_toggle_fullscreen(event) {
                            if win.is_fullscreen() {
                                win.set_fullscreen(None);
                            } else {
                                let monitor = win.current_monitor();
                                win.set_fullscreen(Some(monitor));
                            }
                        }
                    }

                    win.inner_size_points()
                }
                None => (0.0, 0.0),
            };

            // Translate the coordinates from top-left-origin-with-y-down to centre-origin-with-y-up.
            let tx = |x: geom::scalar::Default| x - win_w as geom::scalar::Default / 2.0;
            let ty = |y: geom::scalar::Default| -(y - win_h as geom::scalar::Default / 2.0);

            // If the window ID has changed, ensure the dimensions are up to date.
            if *app.focused_window.borrow() != Some(window_id) {
                if app.window(window_id).is_some() {
                    *app.focused_window.borrow_mut() = Some(window_id);
                }
            }

            // Check for events that would update either mouse, keyboard or window state.
            match *event {
                winit::WindowEvent::CursorMoved { position, .. } => {
                    let (x, y): (f64, f64) = position.into();
                    let x = tx(x as _);
                    let y = ty(y as _);
                    app.mouse.x = x;
                    app.mouse.y = y;
                    app.mouse.window = Some(window_id);
                }

                winit::WindowEvent::MouseInput { state, button, .. } => {
                    match state {
                        event::ElementState::Pressed => {
                            let p = app.mouse.position();
                            app.mouse.buttons.press(button, p);
                        }
                        event::ElementState::Released => {
                            app.mouse.buttons.release(button);
                        }
                    }
                    app.mouse.window = Some(window_id);
                }

                winit::WindowEvent::KeyboardInput { input, .. } => {
                    app.keys.mods = input.modifiers;
                    if let Some(key) = input.virtual_keycode {
                        match input.state {
                            event::ElementState::Pressed => {
                                app.keys.down.keys.insert(key);
                            }
                            event::ElementState::Released => {
                                app.keys.down.keys.remove(&key);
                            }
                        }
                    }
                }

                _ => (),
            }

            // See if the event could be interpreted as a `ui::Input`. If so, submit it to the
            // `Ui`s associated with this window.
            if let Some(window) = app.windows.borrow().get(&window_id) {
                if let Some(input) = ui::winit_window_event_to_input(event.clone(), window) {
                    if let Some(handles) = app.ui.windows.borrow().get(&window_id) {
                        for handle in handles {
                            if let Some(ref tx) = handle.input_tx {
                                tx.try_send(input.clone()).ok();
                            }
                        }
                    }
                }
            }
        }
    }

    // If the user provided an event function and winit::Event could be interpreted as some event
    // `E`, use it to update the model.
    if let Some(event_fn) = event_fn {
        if let Some(event) = E::from_winit_event(winit_event.clone(), app) {
            event_fn(&app, &mut model, event);
        }
    }

    // If the event was a window event, and the user specified an event function for this window,
    // call it.
    if let winit::Event::WindowEvent { window_id, event } = winit_event {
        // Raw window events.
        if let Some(raw_window_event_fn) = {
            let windows = app.windows.borrow();
            windows
                .get(&window_id)
                .and_then(|w| w.user_functions.raw_event.clone())
                .or_else(|| {
                    removed_window
                        .as_ref()
                        .and_then(|w| w.user_functions.raw_event.clone())
                })
        } {
            let raw_window_event_fn = raw_window_event_fn
                .to_fn_ptr::<M>()
                .expect("unexpected model argument given to window event function");
            (*raw_window_event_fn)(&app, &mut model, event.clone());
        }

        let (win_w, win_h) = {
            let windows = app.windows.borrow();
            windows
                .get(&window_id)
                .and_then(|w| w.surface.window().get_inner_size().map(|size| size.into()))
                .unwrap_or((0f64, 0f64))
        };

        // If the event can be represented by a simplified nannou event, check for relevant user
        // functions to be called.
        if let Some(simple) = event::WindowEvent::from_winit_window_event(event, win_w, win_h) {
            // Nannou window events.
            if let Some(window_event_fn) = {
                let windows = app.windows.borrow();
                windows
                    .get(&window_id)
                    .and_then(|w| w.user_functions.event.clone())
                    .or_else(|| {
                        removed_window
                            .as_ref()
                            .and_then(|w| w.user_functions.event.clone())
                    })
            } {
                let window_event_fn = window_event_fn
                    .to_fn_ptr::<M>()
                    .expect("unexpected model argument given to window event function");
                (*window_event_fn)(&app, &mut model, simple.clone());
            }

            // A macro to simplify calling event-specific user functions.
            macro_rules! call_user_function {
                ($fn_name:ident $(,$arg:expr)*) => {{
                    if let Some(event_fn) = {
                        let windows = app.windows.borrow();
                        windows
                            .get(&window_id)
                            .and_then(|w| w.user_functions.$fn_name.clone())
                            .or_else(|| {
                                removed_window
                                    .as_ref()
                                    .and_then(|w| w.user_functions.$fn_name.clone())
                            })
                    } {
                        let event_fn = event_fn
                            .to_fn_ptr::<M>()
                            .unwrap_or_else(|| {
                                panic!(
                                    "unexpected model argument given to {} function",
                                    stringify!($fn_name),
                                );
                            });
                        (*event_fn)(&app, &mut model, $($arg),*);
                    }
                }};
            }

            // Check for more specific event functions.
            match simple {
                event::WindowEvent::KeyPressed(key) => call_user_function!(key_pressed, key),
                event::WindowEvent::KeyReleased(key) => call_user_function!(key_released, key),
                event::WindowEvent::MouseMoved(pos) => call_user_function!(mouse_moved, pos),
                event::WindowEvent::MousePressed(button) => {
                    call_user_function!(mouse_pressed, button)
                }
                event::WindowEvent::MouseReleased(button) => {
                    call_user_function!(mouse_released, button)
                }
                event::WindowEvent::MouseEntered => call_user_function!(mouse_entered),
                event::WindowEvent::MouseExited => call_user_function!(mouse_exited),
                event::WindowEvent::MouseWheel(amount, phase) => {
                    call_user_function!(mouse_wheel, amount, phase)
                }
                event::WindowEvent::Moved(pos) => call_user_function!(moved, pos),
                event::WindowEvent::Resized(size) => call_user_function!(resized, size),
                event::WindowEvent::Touch(touch) => call_user_function!(touch, touch),
                event::WindowEvent::TouchPressure(pressure) => {
                    call_user_function!(touchpad_pressure, pressure)
                }
                event::WindowEvent::HoveredFile(path) => call_user_function!(hovered_file, path),
                event::WindowEvent::HoveredFileCancelled => {
                    call_user_function!(hovered_file_cancelled)
                }
                event::WindowEvent::DroppedFile(path) => call_user_function!(dropped_file, path),
                event::WindowEvent::Focused => call_user_function!(focused),
                event::WindowEvent::Unfocused => call_user_function!(unfocused),
                event::WindowEvent::Closed => call_user_function!(closed),
            }
        }
    }

    // If exit on escape was triggered, we're done.
    let exit = if exit_on_escape || app.windows.borrow().is_empty() {
        true
    } else {
        false
    };

    (model, exit)
}

// Draw the state of the model to the swapchain image associated with the given index..
//
// This calls the `view` function specified by the user.
fn view_frame<M>(
    app: &mut App,
    model: &M,
    window_id: window::Id,
    swapchain_image_index: usize,
    swapchain_image_acquire_future: window::SwapchainAcquireFuture,
    default_view: Option<&View<M>>,
) where
    M: 'static,
{
    // Retrieve the queue and swapchain associated with this window.
    let (queue, swapchain) = {
        let windows = app.windows.borrow();
        let window = &windows[&window_id];
        (window.queue.clone(), window.swapchain.clone())
    };

    // Draw the state of the model to the screen.
    let (swapchain_image, nth_frame, swapchain_frame_created) = {
        let mut windows = app.windows.borrow_mut();
        let window = windows.get_mut(&window_id).expect("no window for id");
        let swapchain_image = window.swapchain.images[swapchain_image_index].clone();
        let frame_count = window.frame_count;
        let swapchain_frame_created = window.swapchain.frame_created;
        window.frame_count += 1;
        (swapchain_image, frame_count, swapchain_frame_created)
    };

    // Construct and emit a frame via `view` for receiving the user's graphics commands.
    let raw_frame = RawFrame::new_empty(
        queue.clone(),
        window_id,
        nth_frame,
        swapchain_image_index,
        swapchain_image,
        swapchain_frame_created,
    )
    .expect("failed to create `Frame`");
    // If the user specified a view function specifically for this window, use it.
    // Otherwise, use the fallback, default view passed to the app if there was one.
    let window_view = {
        let windows = app.windows.borrow();
        windows
            .get(&window_id)
            .and_then(|w| w.user_functions.view.clone())
    };

    // A function to simplify taking a window's render data.
    fn take_window_frame_render_data(app: &App, window_id: window::Id) -> Option<RenderData> {
        let mut windows = app.windows.borrow_mut();
        windows
            .get_mut(&window_id)
            .and_then(|w| w.frame_render_data.take())
    }

    // A function to simplify giving the frame render data back to the window.
    fn set_window_frame_render_data(app: &App, window_id: window::Id, render_data: RenderData) {
        let mut windows = app.windows.borrow_mut();
        if let Some(window) = windows.get_mut(&window_id) {
            window.frame_render_data = Some(render_data);
        }
    }

    let command_buffer = match window_view {
        Some(window::View::Sketch(view)) => {
            let render_data = take_window_frame_render_data(app, window_id)
                .expect("failed to take window's `frame_render_data`");
            let frame = Frame::new_empty(raw_frame, render_data).expect("failed to create `Frame`");
            view(app, &frame);
            let (render_data, raw_frame) = frame
                .finish()
                .expect("failed to resolve frame's intermediary_image to the swapchain_image");
            set_window_frame_render_data(app, window_id, render_data);
            raw_frame
                .finish()
                .build()
                .expect("failed to build command buffer")
        }
        Some(window::View::WithModel(view)) => {
            let render_data = take_window_frame_render_data(app, window_id)
                .expect("failed to take window's `frame_render_data`");
            let frame = Frame::new_empty(raw_frame, render_data).expect("failed to create `Frame`");
            let view = view
                .to_fn_ptr::<M>()
                .expect("unexpected model argument given to window view function");
            (*view)(app, model, &frame);
            let (render_data, raw_frame) = frame
                .finish()
                .expect("failed to resolve frame's intermediary_image to the swapchain_image");
            set_window_frame_render_data(app, window_id, render_data);
            raw_frame
                .finish()
                .build()
                .expect("failed to build command buffer")
        }
        Some(window::View::WithModelRaw(raw_view)) => {
            let raw_view = raw_view
                .to_fn_ptr::<M>()
                .expect("unexpected model argument given to window raw_view function");
            (*raw_view)(app, model, &raw_frame);
            raw_frame
                .finish()
                .build()
                .expect("failed to build command buffer")
        }
        None => match default_view {
            Some(View::Sketch(view)) => {
                let render_data = take_window_frame_render_data(app, window_id)
                    .expect("failed to take window's `frame_render_data`");
                let frame =
                    Frame::new_empty(raw_frame, render_data).expect("failed to create `Frame`");
                view(app, &frame);
                let (render_data, raw_frame) = frame
                    .finish()
                    .expect("failed to resolve frame's intermediary_image to the swapchain_image");
                set_window_frame_render_data(app, window_id, render_data);
                raw_frame
                    .finish()
                    .build()
                    .expect("failed to build command buffer")
            }
            Some(View::WithModel(view)) => {
                let render_data = take_window_frame_render_data(app, window_id)
                    .expect("failed to take window's `frame_render_data`");
                let frame =
                    Frame::new_empty(raw_frame, render_data).expect("failed to create `Frame`");
                view(app, &model, &frame);
                let (render_data, raw_frame) = frame
                    .finish()
                    .expect("failed to resolve frame's intermediary_image to the swapchain_image");
                set_window_frame_render_data(app, window_id, render_data);
                raw_frame
                    .finish()
                    .build()
                    .expect("failed to build command buffer")
            }
            None => raw_frame
                .finish()
                .build()
                .expect("failed to build command buffer"),
        },
    };

    let mut windows = app.windows.borrow_mut();
    let window = windows.get_mut(&window_id).expect("no window for id");

    // Wait for the previous frame presentation to be finished to avoid out-pacing the GPU on macos.
    if let Some(mut previous_frame_fence_signal_future) = window
        .swapchain
        .previous_frame_end
        .lock()
        .expect("failed to lock `previous_frame_end`")
        .take()
    {
        previous_frame_fence_signal_future.cleanup_finished();
        previous_frame_fence_signal_future
            .wait(None)
            .expect("failed to wait for `previous_frame_end` future to signal fence");
    }

    // The future associated with the end of the current frame.
    let future_result = {
        let present_future = swapchain_image_acquire_future
            .then_execute(queue.clone(), command_buffer)
            .expect("failed to execute future")
            .then_swapchain_present(
                queue.clone(),
                swapchain.swapchain.clone(),
                swapchain_image_index,
            );
        (Box::new(present_future) as Box<dyn GpuFuture>).then_signal_fence_and_flush()
    };

    // Handle the result of the future.
    let current_frame_end = match future_result {
        Ok(future) => Some(future),
        Err(vk::sync::FlushError::OutOfDate) => {
            window
                .swapchain
                .needs_recreation
                .store(true, atomic::Ordering::Relaxed);
            None
        }
        Err(e) => {
            println!("{:?}", e);
            None
        }
    };

    *window
        .swapchain
        .previous_frame_end
        .lock()
        .expect("failed to acquire `previous_frame_end` lock") = current_frame_end;
}

// Acquire the next swapchain image for the given window and draw to it using the user's
// view function.
//
// Returns whether or not `view_frame` was called. This will be `false` if the given window
// no longer exists or if the swapchain is `OutOfDate` and needs recreation by the time
// `acquire_next_image` is called.
fn acquire_image_and_view_frame<M>(
    app: &mut App,
    window_id: window::Id,
    model: &M,
    view: Option<&View<M>>,
) -> bool
where
    M: 'static,
{
    // Skip closed windows.
    if app.window(window_id).is_none() {
        return false;
    }
    cleanup_unused_gpu_resources_for_window(app, window_id);

    // Ensure swapchain dimensions are up to date.
    loop {
        if window_swapchain_needs_recreation(app, window_id) {
            match recreate_window_swapchain(app, window_id) {
                Ok(()) => break,
                Err(vk::SwapchainCreationError::UnsupportedDimensions) => {
                    set_window_swapchain_needs_recreation(app, window_id, true);
                    continue;
                }
                Err(err) => panic!("{:?}", err),
            }
        }
        break;
    }

    // Acquire the next image from the swapchain.
    let timeout = None;
    let swapchain = app.windows.borrow()[&window_id].swapchain.clone();
    let next_img = vk::swapchain::acquire_next_image(swapchain.swapchain.clone(), timeout);
    let (swapchain_image_index, swapchain_image_acquire_future) = match next_img {
        Ok(r) => r,
        Err(vk::swapchain::AcquireError::OutOfDate) => {
            set_window_swapchain_needs_recreation(app, window_id, true);
            return false;
        }
        Err(err) => panic!("{:?}", err),
    };

    view_frame(
        app,
        model,
        window_id,
        swapchain_image_index,
        swapchain_image_acquire_future,
        view,
    );
    true
}