This file is indexed.

/usr/share/webbrowser-app/webbrowser/Browser.qml is in webbrowser-app 0.23+16.04.20160413-0ubuntu1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

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

import QtQuick 2.4
import QtQuick.Window 2.2
import Qt.labs.settings 1.0
import com.canonical.Oxide 1.8 as Oxide
import Ubuntu.Components 1.3
import Ubuntu.Components.Popups 1.3
import Unity.InputInfo 0.1
import webbrowserapp.private 0.1
import webbrowsercommon.private 0.1
import "../actions" as Actions
import "../UrlUtils.js" as UrlUtils
import ".."
import "."
import "." as Local

BrowserView {
    id: browser

    // Should be true when the containing window is fullscreen.
    property bool fullscreen: false

    currentWebview: tabsModel && tabsModel.currentTab ? tabsModel.currentTab.webview : null

    readonly property var downloadManager: (downloadHandlerLoader.status == Loader.Ready) ? downloadHandlerLoader.item : null

    property bool newSession: false

    property bool incognito: false

    readonly property var tabsModel: incognito ? privateTabsModelLoader.item : publicTabsModel

    // Restore only the n most recent tabs at startup,
    // to limit the overhead of instantiating too many
    // tab objects (see http://pad.lv/1376433).
    readonly property int maxTabsToRestore: 10

    onTabsModelChanged: {
        if (incognito && privateTabsModelLoader.item) {
            browser.openUrlInNewTab("", true)
        } else if (!incognito && tabsModel.currentTab) {
            // If the system is low on memory, the current public tab might
            // have been unloaded while browsing incognito, so reload it.
            tabsModel.currentTab.load()
        }
    }

    Connections {
        target: currentWebview

        /* Note that we are connecting the mediaAccessPermissionRequested signal
           on the current webview only because we want all the tabs that are not
           visible to automatically deny the request but emit the signal again
           if the same origin requests permissions (which is the default
           behavior in oxide if we don't connect a signal handler), so that we
           can pop-up a dialog asking the user for permission.

           Design is working on a new component that allows per-tab non-modal
           dialogs that will allow asking permission to the user without blocking
           interaction with the rest of the page or the window. When ready all
           tabs will have their mediaAccessPermissionRequested signal handled by
           creating one of these new dialogs.
        */
        onMediaAccessPermissionRequested: PopupUtils.open(mediaAccessDialogComponent, null, { request: request })
    }

    InputDeviceModel {
        id: miceModel
        deviceFilter: InputInfo.Mouse
    }

    InputDeviceModel {
        id: touchPadModel
        deviceFilter: InputInfo.TouchPad
    }

    InputDeviceModel {
        id: touchScreenModel
        deviceFilter: InputInfo.TouchScreen
    }

    FilteredKeyboardModel {
        id: keyboardModel
    }

    Component {
        id: mediaAccessDialogComponent
        MediaAccessDialog { }
    }

    actions: [
        Actions.GoTo {
            onTriggered: currentWebview.url = value
        },
        Actions.Back {
            enabled: currentWebview ? currentWebview.canGoBack : false
            onTriggered: currentWebview.goBack()
        },
        Actions.Forward {
            enabled: currentWebview ? currentWebview.canGoForward : false
            onTriggered: currentWebview.goForward()
        },
        Actions.Reload {
            enabled: currentWebview
            onTriggered: currentWebview.reload()
        },
        Actions.Bookmark {
            enabled: currentWebview
            onTriggered: internal.addBookmark(currentWebview.url, currentWebview.title, currentWebview.icon)
        },
        Actions.NewTab {
            onTriggered: browser.openUrlInNewTab("", true)
        },
        Actions.ClearHistory {
            onTriggered: HistoryModel.clearAll()
        },
        Actions.FindInPage {
            enabled: !chrome.findInPageMode && !newTabViewLoader.active
            onTriggered: {
                chrome.findInPageMode = true
                chrome.focus = true
            }
        }
    ]

    Settings {
        id: settings

        property url homepage: settingsDefaults.homepage
        property string searchEngine: settingsDefaults.searchEngine
        property bool restoreSession: settingsDefaults.restoreSession
        property int newTabDefaultSection: settingsDefaults.newTabDefaultSection
        property string defaultAudioDevice
        property string defaultVideoDevice

        function restoreDefaults() {
            homepage  = settingsDefaults.homepage
            searchEngine = settingsDefaults.searchEngine
            restoreSession = settingsDefaults.restoreSession
            newTabDefaultSection = settingsDefaults.newTabDefaultSection
            defaultAudioDevice = settingsDefaults.defaultAudioDevice
            defaultVideoDevice = settingsDefaults.defaultVideoDevice
        }
    }

    QtObject {
        id: settingsDefaults

        readonly property url homepage: "http://start.ubuntu.com"
        readonly property string searchEngine: "google"
        readonly property bool restoreSession: true
        readonly property int newTabDefaultSection: 0
        readonly property string defaultAudioDevice: ""
        readonly property string defaultVideoDevice: ""
    }

    FocusScope {
        id: contentsContainer
        anchors.fill: parent
        visible: !settingsViewLoader.active && !historyViewLoader.active && !bookmarksViewLoader.active && !downloadsViewLoader.active

        FocusScope {
            id: tabContainer
            anchors {
                left: parent.left
                right: parent.right
                top: parent.top
            }
            height: parent.height - osk.height - bottomEdgeBar.height

            focus: !errorSheetLoader.focus &&
                   !invalidCertificateErrorSheetLoader.focus &&
                   !newTabViewLoader.focus &&
                   !sadTabLoader.focus

            Keys.onPressed: {
                if (tabContainer.visible && (event.key == Qt.Key_Backspace)) {
                    // Not handled as a window-level shortcut as it would take
                    // precedence over backspace events in HTML text fields
                    // (https://launchpad.net/bugs/1569938).
                    if (event.modifiers == Qt.NoModifier) {
                        internal.historyGoBack()
                        event.accepted = true
                    } else if (event.modifiers == Qt.ShiftModifier) {
                        internal.historyGoForward()
                        event.accepted = true
                    }
                }
            }
        }

        Loader {
            id: errorSheetLoader
            anchors {
                fill: tabContainer
                topMargin: (chrome.state == "shown") ? chrome.height : 0
            }
            sourceComponent: ErrorSheet {
                visible: currentWebview ? currentWebview.lastLoadFailed : false
                url: currentWebview ? currentWebview.url : ""
                onRefreshClicked: currentWebview.reload()
            }
            focus: item.visible
            asynchronous: true
        }

        Loader {
            id: invalidCertificateErrorSheetLoader
            anchors {
                fill: tabContainer
                topMargin: (chrome.state == "shown") ? chrome.height : 0
            }
            sourceComponent: InvalidCertificateErrorSheet {
                visible: currentWebview && currentWebview.certificateError != null
                certificateError: currentWebview ? currentWebview.certificateError : null
                onAllowed: {
                    // Automatically allow future requests involving this
                    // certificate for the duration of the session.
                    internal.allowCertificateError(currentWebview.certificateError)
                    currentWebview.resetCertificateError()
                }
                onDenied: {
                    currentWebview.resetCertificateError()
                }
            }
            focus: item.visible
            asynchronous: true
        }

        Loader {
            id: newTabViewLoader

            anchors {
                fill: tabContainer
                topMargin: (chrome.state == "shown") ? chrome.height : 0
            }

            // Avoid loading the new tab view if the webview is about to load
            // content. Since WebView.restoreState is not a notifyable property,
            // this can’t be achieved with a simple property binding.
            Connections {
                target: currentWebview
                onUrlChanged: {
                    newTabViewLoader.active = false
                }
            }
            active: false
            focus: active
            asynchronous: true

            Connections {
                target: browser
                onCurrentWebviewChanged: {
                    if (currentWebview) {
                        var tab = tabsModel.currentTab
                        newTabViewLoader.active = !tab.url.toString() && !tab.restoreState
                    }
                }
            }

            sourceComponent: browser.incognito ? newPrivateTabView :
                             (browser.wide ? newTabViewWide : newTabView)

            Component {
                id: newTabView

                NewTabView {
                    anchors.fill: parent
                    settingsObject: settings
                    focus: true
                    onBookmarkClicked: {
                        chrome.requestedUrl = url
                        currentWebview.url = url
                        tabContainer.forceActiveFocus()
                    }
                    onBookmarkRemoved: BookmarksModel.remove(url)
                    onHistoryEntryClicked: {
                        chrome.requestedUrl = url
                        currentWebview.url = url
                        tabContainer.forceActiveFocus()
                    }
                    Keys.onUpPressed: chrome.focus = true
                }
            }

            Component {
                id: newTabViewWide

                NewTabViewWide {
                    anchors.fill: parent
                    settingsObject: settings
                    focus: true
                    onBookmarkClicked: {
                        chrome.requestedUrl = url
                        currentWebview.url = url
                        tabContainer.forceActiveFocus()
                    }
                    onBookmarkRemoved: BookmarksModel.remove(url)
                    onHistoryEntryClicked: {
                        chrome.requestedUrl = url
                        currentWebview.url = url
                        tabContainer.forceActiveFocus()
                    }
                    Keys.onUpPressed: chrome.focus = true
                }
            }

            Component {
                id: newPrivateTabView

                NewPrivateTabView { anchors.fill: parent }
            }
        }

        Loader {
            id: sadTabLoader
            anchors {
                fill: tabContainer
                topMargin: (chrome.state == "shown") ? chrome.height : 0
            }

            active: webProcessMonitor.crashed || (webProcessMonitor.killed && !currentWebview.loading)
            focus: active

            sourceComponent: SadTab {
                webview: currentWebview
                onCloseTabRequested: internal.closeCurrentTab()
            }

            WebProcessMonitor {
                id: webProcessMonitor
                webview: currentWebview
            }

            asynchronous: true
        }
    }

    FocusScope {
        id: recentView
        objectName: "recentView"

        anchors.fill: parent
        visible: bottomEdgeHandle.dragging || tabslist.animating || (state == "shown")
        onVisibleChanged: chrome.hidden = visible

        states: State {
            name: "shown"
        }

        function closeAndSwitchToTab(index) {
            recentView.reset()
            internal.switchToTab(index, false)
        }

        Keys.onEscapePressed: closeAndSwitchToTab(0)

        TabsList {
            id: tabslist
            anchors.fill: parent
            model: tabsModel
            readonly property real delegateMinHeight: units.gu(20)
            delegateHeight: {
                if (recentView.state == "shown") {
                    return Math.max(height / 3, delegateMinHeight)
                } else if (bottomEdgeHandle.stage == 0) {
                    return height
                } else if (bottomEdgeHandle.stage == 1) {
                    return (1 - 1.8 * bottomEdgeHandle.dragFraction) * height
                } else if (bottomEdgeHandle.stage >= 2) {
                    return Math.max(height / 3, delegateMinHeight)
                } else {
                    return delegateMinHeight
                }
            }
            chromeHeight: chrome.height
            onScheduleTabSwitch: {
                chrome.hidden = false
                internal.nextTabIndex = index
            }
            onTabSelected: recentView.closeAndSwitchToTab(index)
            onTabClosed: internal.closeTab(index)
        }

        Local.Toolbar {
            id: recentToolbar
            objectName: "recentToolbar"

            anchors {
                left: parent.left
                right: parent.right
            }
            height: units.gu(7)
            state: "hidden"

            color: browser.incognito ? UbuntuColors.darkGrey : "#f6f6f6"

            Button {
                objectName: "doneButton"
                anchors {
                    left: parent.left
                    leftMargin: units.gu(2)
                    verticalCenter: parent.verticalCenter
                }

                strokeColor: browser.incognito? "#f6f6f6" : UbuntuColors.darkGrey

                text: i18n.tr("Done")

                onClicked: recentView.closeAndSwitchToTab(0)
            }

            ToolbarAction {
                objectName: "newTabButton"
                anchors {
                    right: parent.right
                    rightMargin: units.gu(2)
                    verticalCenter: parent.verticalCenter
                }
                height: parent.height - units.gu(2)

                text: i18n.tr("New Tab")

                iconName: browser.incognito ? "private-tab-new" : "add"
                color: browser.incognito ? "#f6f6f6" : "#808080"

                onClicked: {
                    recentView.reset()
                    browser.openUrlInNewTab("", true)
                }
            }
        }

        function reset() {
            state = ""
            recentToolbar.state = "hidden"
            tabslist.reset()
            internal.resetFocus()
        }
    }

    SearchEngine {
        id: currentSearchEngine
        searchPaths: searchEnginesSearchPaths
        filename: settings.searchEngine
    }

    ChromeController {
        id: chromeController
        webview: browser.currentWebview
        forceHide: browser.fullscreen
        forceShow: recentView.visible
        defaultMode: (internal.hasMouse && !internal.hasTouchScreen)
                         ? Oxide.LocationBarController.ModeShown
                         : Oxide.LocationBarController.ModeAuto
    }

    Chrome {
        id: chrome

        tab: internal.nextTab || tabsModel.currentTab
        webview: tab ? tab.webview : null
        tabsModel: browser.tabsModel
        searchUrl: currentSearchEngine.urlTemplate

        incognito: browser.incognito

        showTabsBar: browser.wide
        showFaviconInAddressBar: !browser.wide

        availableHeight: tabContainer.height - height - y

        touchEnabled: internal.hasTouchScreen

        property bool hidden: false
        y: hidden ? -height : webview ? webview.locationBarController.offset : 0
        Behavior on y {
            enabled: recentView.visible
            NumberAnimation {
                duration: UbuntuAnimation.FastDuration
            }
        }

        function isCurrentUrlBookmarked() {
            return tab ? BookmarksModel.contains(tab.url) : false
        }
        bookmarked: isCurrentUrlBookmarked()
        onToggleBookmark: {
            if (isCurrentUrlBookmarked()) BookmarksModel.remove(tab.url)
            else internal.addBookmark(tab.url, tab.title, tab.icon)
        }
        onWebviewChanged: bookmarked = isCurrentUrlBookmarked()
        Connections {
            target: chrome.tab
            onUrlChanged: chrome.bookmarked = chrome.isCurrentUrlBookmarked()
        }
        Connections {
            target: BookmarksModel
            onCountChanged: chrome.bookmarked = chrome.isCurrentUrlBookmarked()
        }

        onSwitchToTab: internal.switchToTab(index, true)
        onRequestNewTab: browser.openUrlInNewTab("", makeCurrent, true, index)
        onTabClosed: internal.closeTab(index)

        onFindInPageModeChanged: {
            if (!chrome.findInPageMode) internal.resetFocus()
            else chrome.forceActiveFocus()
        }

        anchors {
            left: parent.left
            right: parent.right
        }

        drawerActions: [
            Action {
                objectName: "share"
                text: i18n.tr("Share")
                iconName: "share"
                enabled: (contentHandlerLoader.status == Loader.Ready) &&
                         chrome.tab && chrome.tab.url.toString()
                onTriggered: internal.shareLink(chrome.tab.url, chrome.tab.title)
            },
            Action {
                objectName: "bookmarks"
                text: i18n.tr("Bookmarks")
                iconName: "bookmark"
                onTriggered: bookmarksViewLoader.active = true
            },
            Action {
                objectName: "history"
                text: i18n.tr("History")
                iconName: "history"
                onTriggered: historyViewLoader.active = true
            },
            Action {
                objectName: "findinpage"
                text: i18n.tr("Find in page")
                iconName: "search"
                enabled: !chrome.findInPageMode && !newTabViewLoader.active
                onTriggered: chrome.findInPageMode = true
            },
            Action {
                objectName: "downloads"
                text: i18n.tr("Downloads")
                iconName: "save"
                enabled: downloadHandlerLoader.status == Loader.Ready && contentHandlerLoader.status == Loader.Ready
                onTriggered: downloadsViewLoader.active = true
            },
            Action {
                objectName: "privatemode"
                text: browser.incognito ? i18n.tr("Leave Private Mode") : i18n.tr("Private Mode")
                iconName: "private-browsing"
                iconSource: browser.incognito ? Qt.resolvedUrl("assets/private-browsing-exit.svg") : ""
                onTriggered: {
                    if (browser.incognito) {
                        if (tabsModel.count > 1) {
                            PopupUtils.open(leavePrivateModeDialog)
                        } else {
                            browser.incognito = false
                            internal.resetFocus()
                        }
                    } else {
                        browser.incognito = true
                    }
                }
            },
            Action {
                objectName: "settings"
                text: i18n.tr("Settings")
                iconName: "settings"
                onTriggered: settingsViewLoader.active = true
            }
        ]

        canSimplifyText: !browser.wide
        editing: activeFocus || suggestionsList.activeFocus

        Keys.onDownPressed: {
            if (suggestionsList.count) suggestionsList.focus = true
            else if (newTabViewLoader.status == Loader.Ready) {
                newTabViewLoader.forceActiveFocus()
            }
        }

        Keys.onEscapePressed: {
            if (chrome.findInPageMode) {
                chrome.findInPageMode = false
            } else {
                internal.resetFocus()
            }
        }
    }

    Suggestions {
        id: suggestionsList
        opacity: ((chrome.state == "shown") && (activeFocus || chrome.activeFocus) &&
                  (count > 0) && !chrome.drawerOpen && !chrome.findInPageMode) ? 1.0 : 0.0
        Behavior on opacity {
            UbuntuNumberAnimation {}
        }
        enabled: opacity > 0
        anchors {
            top: chrome.bottom
            horizontalCenter: parent.horizontalCenter
        }
        width: chrome.width - units.gu(5)
        height: enabled ? Math.min(contentHeight, tabContainer.height - chrome.height - units.gu(2)) : 0

        searchTerms: chrome.text.split(/\s+/g).filter(function(term) { return term.length > 0 })

        Keys.onUpPressed: chrome.focus = true
        Keys.onEscapePressed: internal.resetFocus()

        models: searchTerms && searchTerms.length > 0 ?
                [historySuggestions,
                 bookmarksSuggestions,
                 searchSuggestions.limit(4)] : []

        LimitProxyModel {
            id: historySuggestions
            limit: 2
            readonly property string icon: "history"
            readonly property bool displayUrl: true
            sourceModel: TextSearchFilterModel {
                sourceModel: HistoryModel
                terms: suggestionsList.searchTerms
                searchFields: ["url", "title"]
            }
        }

        LimitProxyModel {
            id: bookmarksSuggestions
            limit: 2
            readonly property string icon: "non-starred"
            readonly property bool displayUrl: true
            sourceModel: TextSearchFilterModel {
                sourceModel: BookmarksModel
                terms: suggestionsList.searchTerms
                searchFields: ["url", "title"]
            }
        }

        SearchSuggestions {
            id: searchSuggestions
            terms: suggestionsList.searchTerms
            searchEngine: currentSearchEngine
            active: (chrome.activeFocus || suggestionsList.activeFocus) &&
                     !browser.incognito && !chrome.findInPageMode &&
                     !UrlUtils.looksLikeAUrl(chrome.text.replace(/ /g, "+"))

            function limit(number) {
                var slice = results.slice(0, number)
                slice.icon = 'search'
                slice.displayUrl = false
                return slice
            }
        }

        onActivated: {
            browser.currentWebview.url = url
            tabContainer.forceActiveFocus()
            chrome.requestedUrl = url
        }
    }

    onWideChanged: {
        if (wide) {
            recentView.reset()
        } else {
            // In narrow mode, the tabslist is a stack: the current tab is always at the top.
            tabsModel.move(tabsModel.currentIndex, 0)
        }
    }

    BottomEdgeHandle {
        id: bottomEdgeHandle
        objectName: "bottomEdgeHandle"

        anchors {
            left: parent.left
            right: parent.right
            bottom: parent.bottom
        }
        height: units.gu(2)

        enabled: !browser.wide && (recentView.state == "") &&
                 browser.currentWebview &&
                 (Screen.orientation == Screen.primaryOrientation)

        onDraggingChanged: {
            if (dragging) {
                if (browser.currentWebview) {
                    browser.currentWebview.fullscreen = false
                }
            } else {
                if (stage == 1) {
                    if (tabsModel.count > 1) {
                        tabslist.selectAndAnimateTab(1)
                    } else {
                        recentView.state = "shown"
                        recentToolbar.state = "shown"
                    }
                } else if (stage == 2) {
                    recentView.state = "shown"
                    recentToolbar.state = "shown"
                } else if (stage >= 3) {
                    recentView.state = "shown"
                    recentToolbar.state = "shown"
                }
            }
        }
    }

    Image {
        id: bottomEdgeHint
        source: "assets/bottom_edge_hint.png"
        property bool forceShow: false
        anchors {
            horizontalCenter: parent.horizontalCenter
            bottom: parent.bottom
            bottomMargin: (((chrome.state == "shown") && browser.currentWebview && !browser.currentWebview.fullscreen) || forceShow) ? 0 : -height
            Behavior on bottomMargin {
                UbuntuNumberAnimation {}
            }
        }
        visible: bottomEdgeHandle.enabled && !internal.hasMouse
        opacity: recentView.visible ? 0 : 1
        Behavior on opacity {
            UbuntuNumberAnimation {}
        }

        Label {
            anchors {
                horizontalCenter: parent.horizontalCenter
                verticalCenter: parent.verticalCenter
                verticalCenterOffset: units.dp(2)
            }

            fontSize: "small"
            // TRANSLATORS: %1 refers to the current number of tabs opened
            text: i18n.tr("(%1)").arg(tabsModel ? tabsModel.count : 0)
        }
    }

    MouseArea {
        id: bottomEdgeBar
        objectName: "bottomEdgeBar"
        anchors {
            left: parent.left
            right: parent.right
            bottom: parent.bottom
        }
        enabled: !browser.wide && internal.hasMouse &&
                 (osk.state == "hidden") && (recentView.state == "")
        visible: enabled
        height: visible ? units.gu(4) : 0
        // Ensure that this ends up below the chrome, so that the
        // drawer menu’s inverse mouse area covers it.
        z: -1

        onClicked: {
            recentView.state = "shown"
            recentToolbar.state = "shown"
        }

        Rectangle {
            anchors.fill: parent
            color: "#f7f7f7"
            border {
                width: units.dp(1)
                color: "#cdcdcd"
            }
        }

        Label {
            anchors.centerIn: parent
            color: "#5d5d5d"
            // TRANSLATORS: %1 refers to the current number of tabs opened
            text: i18n.tr("(%1)").arg(tabsModel ? tabsModel.count : 0)
        }
    }

    Loader {
        id: bookmarksViewLoader

        anchors.fill: parent
        active: false
        sourceComponent: browser.wide ? bookmarksViewWideComponent : bookmarksViewComponent

        onStatusChanged: {
            if (status == Loader.Ready) {
                bookmarksViewLoader.item.forceActiveFocus()
            } else {
                internal.resetFocus()
            }
        }

        Keys.onEscapePressed: bookmarksViewLoader.active = false

        onActiveChanged: {
            if (active) {
                chrome.findInPageMode = false
                forceActiveFocus()
            }
        }

        Connections {
            target: bookmarksViewLoader.item

            onBookmarkEntryClicked: {
                browser.openUrlInNewTab(url, true)
                bookmarksViewLoader.active = false
            }
            onDone: bookmarksViewLoader.active = false
            onNewTabClicked: {
                browser.openUrlInNewTab("", true)
                bookmarksViewLoader.active = false
            }
        }

        Component {
            id: bookmarksViewComponent

            BookmarksView {
                anchors.fill: parent

                homepageUrl: settings.homepage
            }
        }

        Component {
            id: bookmarksViewWideComponent

            BookmarksViewWide {
                anchors.fill: parent

                homepageUrl: settings.homepage
            }
        }
    }

    Loader {
        id: historyViewLoader

        anchors.fill: parent
        active: false
        sourceComponent: browser.wide ? historyViewWideComponent : historyViewComponent

        onStatusChanged: {
            if (status == Loader.Ready) {
                historyViewLoader.item.loadModel()
                historyViewLoader.item.forceActiveFocus()
            } else {
                internal.resetFocus()
            }
        }

        Keys.onEscapePressed: historyViewLoader.active = false

        onActiveChanged: {
            if (active) {
                chrome.findInPageMode = false
                forceActiveFocus()
            }
        }

        Component {
            id: historyViewComponent

            FocusScope {
                signal loadModel()
                onLoadModel: children[0].loadModel()

                HistoryView {
                    anchors.fill: parent
                    focus: !expandedHistoryViewLoader.focus
                    visible: focus
                    onSeeMoreEntriesClicked: {
                        expandedHistoryViewLoader.model = model
                        expandedHistoryViewLoader.active = true
                    }
                    onNewTabRequested: browser.openUrlInNewTab("", true)
                    onDone: historyViewLoader.active = false
                }

                Loader {
                    id: expandedHistoryViewLoader
                    asynchronous: true
                    anchors.fill: parent
                    active: false
                    focus: active
                    property var model: null
                    sourceComponent: ExpandedHistoryView {
                        focus: true
                        model: expandedHistoryViewLoader.model
                        onHistoryEntryClicked: {
                            browser.openUrlInNewTab(url, true)
                            historyViewLoader.active = false
                        }
                        onHistoryEntryRemoved: {
                            if (count == 1) {
                                done()
                            }
                            HistoryModel.removeEntryByUrl(url)
                        }
                        onDone: expandedHistoryViewLoader.active = false
                    }
                }
            }
        }

        Component {
            id: historyViewWideComponent

            HistoryViewWide {
                anchors.fill: parent

                Keys.onEscapePressed: {
                    historyViewLoader.active = false
                    internal.resetFocus()
                }

                onHistoryEntryClicked: {
                    browser.openUrlInNewTab(url, true)
                    done()
                }

                onNewTabRequested: browser.openUrlInNewTab("", true)
                onDone: historyViewLoader.active = false
            }
        }
    }

    Loader {
        id: settingsViewLoader

        anchors.fill: parent
        active: false

        onStatusChanged: {
            if (status == Loader.Ready) {
                settingsViewLoader.item.forceActiveFocus()
            } else {
                internal.resetFocus()
            }
        }

        Keys.onEscapePressed: settingsViewLoader.active = false

        onActiveChanged: {
            if (active) {
                chrome.findInPageMode = false
                forceActiveFocus()
            }
        }

        sourceComponent: SettingsPage {
            anchors.fill: parent
            focus: true
            settingsObject: settings
            onDone: settingsViewLoader.active = false
        }
    }

    Loader {
        id: downloadsViewLoader

        anchors.fill: parent
        active: false
        source: "DownloadsPage.qml"

        onStatusChanged: {
            if (status == Loader.Ready) {
                item.forceActiveFocus()
            } else {
                internal.resetFocus()
            }
        }

        Keys.onEscapePressed: active = false

        onActiveChanged: {
            if (active) {
                forceActiveFocus()
            }
        }

        Binding {
            target: downloadsViewLoader.item
            property: "downloadManager"
            value: browser.downloadManager
        }

        Connections {
            target: downloadsViewLoader.item
            onDone: downloadsViewLoader.active = false
        }
    }

    TabsModel {
        id: publicTabsModel
    }

    Loader {
        id: privateTabsModelLoader

        sourceComponent: browser.incognito ? privateTabsModelComponent : undefined

        Component {
            id: privateTabsModelComponent

            TabsModel {
                Component.onDestruction: {
                    while (count > 0) {
                        var tab = remove(count - 1)
                        if (tab) {
                            tab.close()
                        }
                    }
                }
            }
        }
    }

    Loader {
        id: downloadHandlerLoader
        source: "DownloadHandler.qml"
        asynchronous: true
    }

    Component {
        id: tabComponent

        BrowserTab {
            anchors.fill: parent
            current: tabsModel && tabsModel.currentTab === this
            focus: current

            Item {
                id: contextualMenuTarget
                visible: false
            }

            webviewComponent: WebViewImpl {
                id: webviewimpl

                property BrowserTab tab
                readonly property bool current: tab.current

                currentWebview: browser.currentWebview
                filePicker: filePickerLoader.item

                anchors.fill: parent
                focus: true

                enabled: current && !bottomEdgeHandle.dragging && !recentView.visible

                locationBarController {
                    height: chrome.height
                    mode: chromeController.defaultMode
                }

                //experimental.preferences.developerExtrasEnabled: developerExtrasEnabled
                preferences.localStorageEnabled: true
                preferences.appCacheEnabled: true

                property QtObject contextModel: null
                contextualActions: ActionList {
                    Actions.OpenLinkInNewTab {
                        objectName: "OpenLinkInNewTabContextualAction"
                        enabled: contextModel && contextModel.linkUrl.toString()
                        onTriggered: browser.openUrlInNewTab(contextModel.linkUrl, true)
                    }
                    Actions.OpenLinkInNewBackgroundTab {
                        objectName: "OpenLinkInNewBackgroundTabContextualAction"
                        enabled: contextModel && contextModel.linkUrl.toString()
                        onTriggered: browser.openUrlInNewTab(contextModel.linkUrl, false)
                    }
                    Actions.BookmarkLink {
                        objectName: "BookmarkLinkContextualAction"
                        enabled: contextModel && contextModel.linkUrl.toString()
                                 && !BookmarksModel.contains(contextModel.linkUrl)
                        onTriggered: {
                            // position the menu target with a one-off assignement instead of a binding
                            // since the contents of the contextModel have meaning only while the context
                            // menu is active
                            contextualMenuTarget.x = contextModel.position.x
                            contextualMenuTarget.y = contextModel.position.y + locationBarController.height + locationBarController.offset
                            internal.addBookmark(contextModel.linkUrl, contextModel.linkText,
                                                 "", contextualMenuTarget)
                        }
                    }
                    Actions.CopyLink {
                        objectName: "CopyLinkContextualAction"
                        enabled: contextModel && contextModel.linkUrl.toString()
                        onTriggered: Clipboard.push(["text/plain", contextModel.linkUrl.toString()])
                    }
                    Actions.SaveLink {
                        objectName: "SaveLinkContextualAction"
                        enabled: contextModel && contextModel.linkUrl.toString()
                        onTriggered: contextModel.saveLink()
                    }
                    Actions.Share {
                        objectName: "ShareContextualAction"
                        enabled: (contentHandlerLoader.status == Loader.Ready) && contextModel &&
                                 (contextModel.linkUrl.toString() || contextModel.selectionText)
                        onTriggered: {
                            if (contextModel.linkUrl.toString()) {
                                internal.shareLink(contextModel.linkUrl.toString(), contextModel.linkText)
                            } else if (contextModel.selectionText) {
                                internal.shareText(contextModel.selectionText)
                            }
                        }
                    }
                    Actions.OpenImageInNewTab {
                        objectName: "OpenImageInNewTabContextualAction"
                        enabled: contextModel &&
                                 (contextModel.mediaType === Oxide.WebView.MediaTypeImage) &&
                                 contextModel.srcUrl.toString()
                        onTriggered: browser.openUrlInNewTab(contextModel.srcUrl, true)
                    }
                    Actions.CopyImage {
                        objectName: "CopyImageContextualAction"
                        enabled: contextModel &&
                                 (contextModel.mediaType === Oxide.WebView.MediaTypeImage) &&
                                 contextModel.srcUrl.toString()
                        onTriggered: Clipboard.push(["text/plain", contextModel.srcUrl.toString()])
                    }
                    Actions.SaveImage {
                        objectName: "SaveImageContextualAction"
                        enabled: contextModel &&
                                 ((contextModel.mediaType === Oxide.WebView.MediaTypeImage) ||
                                  (contextModel.mediaType === Oxide.WebView.MediaTypeCanvas)) &&
                                 contextModel.hasImageContents
                        onTriggered: contextModel.saveMedia()
                    }
                    Actions.OpenVideoInNewTab {
                        objectName: "OpenVideoInNewTabContextualAction"
                        enabled: contextModel &&
                                 (contextModel.mediaType === Oxide.WebView.MediaTypeVideo) &&
                                 contextModel.srcUrl.toString()
                        onTriggered: browser.openUrlInNewTab(contextModel.srcUrl, true)
                    }
                    Actions.SaveVideo {
                        objectName: "SaveVideoContextualAction"
                        enabled: contextModel &&
                                 (contextModel.mediaType === Oxide.WebView.MediaTypeVideo) &&
                                 contextModel.srcUrl.toString()
                        onTriggered: contextModel.saveMedia()
                    }
                    Actions.Undo {
                        objectName: "UndoContextualAction"
                        enabled: contextModel && contextModel.isEditable &&
                                 (contextModel.editFlags & Oxide.WebView.UndoCapability)
                        onTriggered: webviewimpl.executeEditingCommand(Oxide.WebView.EditingCommandUndo)
                    }
                    Actions.Redo {
                        objectName: "RedoContextualAction"
                        enabled: contextModel && contextModel.isEditable &&
                                 (contextModel.editFlags & Oxide.WebView.RedoCapability)
                        onTriggered: webviewimpl.executeEditingCommand(Oxide.WebView.EditingCommandRedo)
                    }
                    Actions.Cut {
                        objectName: "CutContextualAction"
                        enabled: contextModel && contextModel.isEditable &&
                                 (contextModel.editFlags & Oxide.WebView.CutCapability)
                        onTriggered: webviewimpl.executeEditingCommand(Oxide.WebView.EditingCommandCut)
                    }
                    Actions.Copy {
                        objectName: "CopyContextualAction"
                        enabled: contextModel && (contextModel.selectionText ||
                                 (contextModel.isEditable &&
                                 (contextModel.editFlags & Oxide.WebView.CopyCapability)))
                        onTriggered: webviewimpl.executeEditingCommand(Oxide.WebView.EditingCommandCopy)
                    }
                    Actions.Paste {
                        objectName: "PasteContextualAction"
                        enabled: contextModel && contextModel.isEditable &&
                                 (contextModel.editFlags & Oxide.WebView.PasteCapability)
                        onTriggered: webviewimpl.executeEditingCommand(Oxide.WebView.EditingCommandPaste)
                    }
                    Actions.Erase {
                        objectName: "EraseContextualAction"
                        enabled: contextModel && contextModel.isEditable &&
                                 (contextModel.editFlags & Oxide.WebView.EraseCapability)
                        onTriggered: webviewimpl.executeEditingCommand(Oxide.WebView.EditingCommandErase)
                    }
                    Actions.SelectAll {
                        objectName: "SelectAllContextualAction"
                        enabled: contextModel && contextModel.isEditable &&
                                 (contextModel.editFlags & Oxide.WebView.SelectAllCapability)
                        onTriggered: webviewimpl.executeEditingCommand(Oxide.WebView.EditingCommandSelectAll)
                    }
                }

                function contextMenuOnCompleted(menu) {
                    contextModel = menu.contextModel
                    if (contextModel.linkUrl.toString() ||
                        contextModel.srcUrl.toString() ||
                        contextModel.selectionText ||
                        (contextModel.isEditable && contextModel.editFlags) ||
                        (((contextModel.mediaType == Oxide.WebView.MediaTypeImage) ||
                          (contextModel.mediaType == Oxide.WebView.MediaTypeCanvas)) &&
                         contextModel.hasImageContents)) {
                        menu.show()
                    } else {
                        contextModel.close()
                    }
                }

                Component {
                    id: contextMenuNarrowComponent
                    ContextMenuMobile {
                        actions: contextualActions
                        Component.onCompleted: webviewimpl.contextMenuOnCompleted(this)
                    }
                }
                Component {
                    id: contextMenuWideComponent
                    ContextMenuWide {
                        webview: webviewimpl
                        parent: browser
                        actions: contextualActions
                        Component.onCompleted: webviewimpl.contextMenuOnCompleted(this)
                    }
                }
                contextMenu: browser.wide ? contextMenuWideComponent : contextMenuNarrowComponent

                onNewViewRequested: {
                    var tab = tabComponent.createObject(tabContainer, {"request": request, 'incognito': browser.incognito})
                    var setCurrent = (request.disposition == Oxide.NewViewRequest.DispositionNewForegroundTab)
                    internal.addTab(tab, setCurrent)
                    if (setCurrent) tabContainer.forceActiveFocus()
                }

                onCloseRequested: prepareToClose()
                onPrepareToCloseResponse: {
                    if (proceed) {
                        if (tab) {
                            for (var i = 0; i < tabsModel.count; ++i) {
                                if (tabsModel.get(i) === tab) {
                                    tabsModel.remove(i)
                                    break
                                }
                            }
                            tab.close()
                        }
                        if (tabsModel.count === 0) {
                            browser.openUrlInNewTab("", true, true)
                        }
                    }
                }

                QtObject {
                    id: webviewInternal
                    property url storedUrl: ""
                    property bool titleSet: false
                    property string title: ""
                }
                onLoadEvent: {
                    if (event.type == Oxide.LoadEvent.TypeCommitted) {
                        chrome.findInPageMode = false
                        webviewInternal.titleSet = false
                        webviewInternal.title = title
                    }

                    if (webviewimpl.incognito) {
                        return
                    }

                    if ((event.type == Oxide.LoadEvent.TypeCommitted) &&
                        !event.isError &&
                        (300 > event.httpStatusCode) && (event.httpStatusCode >= 200)) {
                        webviewInternal.storedUrl = event.url
                        HistoryModel.add(event.url, title, icon)
                    }
                }
                onTitleChanged: {
                    if (!webviewInternal.titleSet && webviewInternal.storedUrl.toString()) {
                        // Record the title to avoid updating the history database
                        // every time the page dynamically updates its title.
                        // We don’t want pages that update their title every second
                        // to achieve an ugly "scrolling title" effect to flood the
                        // history database with updates.
                        webviewInternal.titleSet = true
                        webviewInternal.title = title
                        HistoryModel.update(webviewInternal.storedUrl, title, icon)
                    }
                }
                onIconChanged: {
                    if (webviewInternal.storedUrl.toString()) {
                        HistoryModel.update(webviewInternal.storedUrl, webviewInternal.title, icon)
                    }
                }

                onGeolocationPermissionRequested: requestGeolocationPermission(request)

                property var certificateError
                function resetCertificateError() {
                    certificateError = null
                }
                onCertificateError: {
                    if (!error.isMainFrame || error.isSubresource) {
                        // Not a main frame document error, just block the content
                        // (it’s not overridable anyway).
                        return
                    }
                    if (internal.isCertificateErrorAllowed(error)) {
                        error.allow()
                    } else {
                        certificateError = error
                        error.onCancelled.connect(webviewimpl.resetCertificateError)
                    }
                }

                onFullscreenChanged: {
                    if (fullscreen) {
                        fullscreenExitHintComponent.createObject(webviewimpl)
                    }
                }
                Component {
                    id: fullscreenExitHintComponent

                    Rectangle {
                        id: fullscreenExitHint
                        objectName: "fullscreenExitHint"

                        anchors.centerIn: parent
                        height: units.gu(6)
                        width: Math.min(units.gu(50), parent.width - units.gu(12))
                        radius: units.gu(1)
                        color: "#3e3b39"
                        opacity: 0.85

                        Behavior on opacity {
                            UbuntuNumberAnimation {
                                duration: UbuntuAnimation.SlowDuration
                            }
                        }
                        onOpacityChanged: {
                            if (opacity == 0.0) {
                                fullscreenExitHint.destroy()
                            }
                        }

                        // Delay showing the hint to prevent it from jumping up while the
                        // webview is being resized (https://launchpad.net/bugs/1454097).
                        visible: false
                        Timer {
                            running: true
                            interval: 250
                            onTriggered: fullscreenExitHint.visible = true
                        }

                        Label {
                            color: "white"
                            font.weight: Font.Light
                            anchors.centerIn: parent
                            text: bottomEdgeHandle.enabled
                                      ? i18n.tr("Swipe Up To Exit Full Screen")
                                      : i18n.tr("Press ESC To Exit Full Screen")
                        }

                        Timer {
                            running: fullscreenExitHint.visible
                            interval: 2000
                            onTriggered: fullscreenExitHint.opacity = 0
                        }

                        Connections {
                            target: webviewimpl
                            onFullscreenChanged: {
                                if (!webviewimpl.fullscreen) {
                                    fullscreenExitHint.destroy()
                                }
                            }
                        }

                        Component.onCompleted: bottomEdgeHint.forceShow = true
                        Component.onDestruction: bottomEdgeHint.forceShow = false
                    }
                }

                onShowDownloadDialog: {
                    if (downloadDialogLoader.status === Loader.Ready) {
                        var downloadDialog = PopupUtils.open(downloadDialogLoader.item, browser, {"contentType" : contentType,
                                                                                                  "downloadId" : downloadId,
                                                                                                  "singleDownload" : downloader,
                                                                                                  "filename" : filename,
                                                                                                  "mimeType" : mimeType})
                        downloadDialog.startDownload.connect(startDownload)
                    }
                }

                function showDownloadsPage() {
                    downloadsViewLoader.active = true
                    return downloadsViewLoader.item
                }

                function startDownload(downloadId, download, mimeType) {
                    DownloadsModel.add(downloadId, download.url, mimeType)
                    download.start()
                    downloadsViewLoader.active = true
                }

            }
        }
    }

    Component {
        id: bookmarkOptionsComponent
        BookmarkOptions {
            folderModel: BookmarksFolderListModel {
                sourceModel: BookmarksModel
            }

            Component.onCompleted: forceActiveFocus()

            onVisibleChanged: {
                if (!visible) {
                    BookmarksModel.remove(bookmarkUrl)
                }
            }

            Component.onDestruction: {
                if (BookmarksModel.contains(bookmarkUrl)) {
                    BookmarksModel.update(bookmarkUrl, bookmarkTitle, bookmarkFolder)
                }
            }

            // Fragile workaround for https://launchpad.net/bugs/1546677.
            // By destroying the popover, its visibility isn’t changed to
            // false, and thus the bookmark is not removed.
            Keys.onEnterPressed: destroy()
            Keys.onReturnPressed: destroy()
        }
    }

    QtObject {
        id: internal
        property var closedTabHistory: []

        property int nextTabIndex: -1
        readonly property var nextTab: (nextTabIndex > -1) ? tabsModel.get(nextTabIndex) : null
        onNextTabChanged: {
            if (nextTab) {
                nextTab.aboutToShow()
            }
        }

        readonly property bool hasMouse: (miceModel.count + touchPadModel.count) > 0
        readonly property bool hasTouchScreen: touchScreenModel.count > 0

        readonly property real freeMemRatio: (MemInfo.total > 0) ? (MemInfo.free / MemInfo.total) : 1.0
        // Under that threshold, available memory is considered "low", and the
        // browser is going to try and free up memory from unused tabs. This
        // value was chosen empirically, it is subject to change to better
        // reflect what a system under memory pressure might look like.
        readonly property real lowOnMemoryThreshold: 0.3
        readonly property bool lowOnMemory: freeMemRatio < lowOnMemoryThreshold

        function getOpenPages() {
            var urls = []
            for (var i = 0; i < tabsModel.count; i++) {
                var url = tabsModel.get(i).url
                if (url.toString()) urls.push(url) // exclude "new tab" tabs
            }
            return urls
        }

        function instantiateShareComponent() {
            var component = Qt.createComponent("../Share.qml")
            if (component.status == Component.Ready) {
                var share = component.createObject(browser)
                share.onDone.connect(share.destroy)
                return share
            }
            return null
        }

        function shareLink(url, title) {
            var share = instantiateShareComponent()
            if (share) share.shareLink(url, title)
        }

        function shareText(text) {
            var share = instantiateShareComponent()
            if (share) share.shareText(text)
        }

        function addTab(tab, setCurrent, index) {
            if (index === undefined) index = tabsModel.add(tab)
            else index = tabsModel.insert(tab, index)
            if (setCurrent) {
                chrome.requestedUrl = tab.initialUrl
                switchToTab(index, true)
            }
        }

        function closeTab(index) {
            // Save the incognito state before removing the tab, because
            // removing the last tab in the model will switch out incognito
            // mode, thus causing the check below to fail and save the tab
            // into the undo stack when it should be forgotten instead.
            var wasIncognito = incognito
            var tab = tabsModel.remove(index)
            if (tab) {
                if (!wasIncognito && tab.url.toString().length > 0) {
                    closedTabHistory.push({
                        state: session.serializeTabState(tab),
                        index: index
                    })
                }
                tab.close()
            }
            if (tabsModel.count === 0) {
                browser.openUrlInNewTab("", true)
                recentView.reset()
            }
        }

        function closeCurrentTab() {
            if (tabsModel.count > 0) {
                closeTab(tabsModel.currentIndex)
            }
        }

        function undoCloseTab() {
            if (!incognito && closedTabHistory.length > 0) {
                var tabInfo = closedTabHistory.pop()
                var tab = session.createTabFromState(tabInfo.state)
                addTab(tab, true, tabInfo.index)
            }
        }

        function switchToPreviousTab() {
            if (browser.wide) {
                internal.switchToTab((tabsModel.currentIndex - 1 + tabsModel.count) % tabsModel.count, true)
            } else {
                internal.switchToTab(tabsModel.count - 1, true)
            }
        }

        function switchToNextTab() {
            if (browser.wide) {
                internal.switchToTab((tabsModel.currentIndex + 1) % tabsModel.count, true)
            } else {
                internal.switchToTab(tabsModel.count - 1, true)
            }
        }

        function switchToTab(index, delayed) {
            if (delayed) {
                nextTabIndex = index
                delayedTabSwitcher.restart()
            } else {
                tabsModel.currentIndex = index
                nextTabIndex = -1
                var tab = tabsModel.currentTab
                if (recentView.visible) {
                    recentView.focus = true
                } else if (tab) {
                    if (!tab.url.toString() && !tab.initialUrl.toString()) {
                        maybeFocusAddressBar()
                    } else {
                        tabContainer.forceActiveFocus()
                    }
                }
            }
        }

        function focusAddressBar(selectContent) {
            chrome.forceActiveFocus()
            Qt.inputMethod.show() // work around http://pad.lv/1316057
            if (selectContent) chrome.selectAll()
        }

        function resetFocus() {
            if (browser.currentWebview) {
                if (!browser.currentWebview.url.toString()) {
                    internal.maybeFocusAddressBar()
                } else {
                    contentsContainer.forceActiveFocus()
                }
            }
        }

        function maybeFocusAddressBar() {
            if (keyboardModel.count > 0) {
                focusAddressBar()
            } else {
                contentsContainer.forceActiveFocus()
            }
        }

        // Invalid certificates the user has explicitly allowed for this session
        property var allowedCertificateErrors: []

        function allowCertificateError(error) {
            var host = UrlUtils.extractHost(error.url)
            var code = error.certError
            var fingerprint = error.certificate.fingerprintSHA1
            allowedCertificateErrors.push([host, code, fingerprint])
        }

        function isCertificateErrorAllowed(error) {
            var host = UrlUtils.extractHost(error.url)
            var code = error.certError
            var fingerprint = error.certificate.fingerprintSHA1
            for (var i in allowedCertificateErrors) {
                var allowed = allowedCertificateErrors[i]
                if ((host == allowed[0]) &&
                    (code == allowed[1]) &&
                    (fingerprint == allowed[2])) {
                    return true
                }
            }
            return false
        }

        function historyGoBack() {
            if (currentWebview && currentWebview.canGoBack) {
                internal.resetFocus()
                currentWebview.goBack()
            }
        }

        function historyGoForward() {
            if (currentWebview && currentWebview.canGoForward) {
                internal.resetFocus()
                currentWebview.goForward()
            }
        }

        property var currentBookmarkOptionsDialog: null
        function addBookmark(url, title, icon, location) {
            if (title == "") title = UrlUtils.removeScheme(url)
            BookmarksModel.add(url, title, icon, "")
            if (location === undefined) location = chrome.bookmarkTogglePlaceHolder
            var properties = {"bookmarkUrl": url, "bookmarkTitle": title}
            currentBookmarkOptionsDialog = PopupUtils.open(bookmarkOptionsComponent,
                                                           location, properties)
        }
    }

    // Work around https://launchpad.net/bugs/1502675 by delaying the switch to
    // the next tab for a fraction of a second to avoid a black flash.
    Timer {
        id: delayedTabSwitcher
        interval: 50
        onTriggered: internal.switchToTab(internal.nextTabIndex, false)
    }

    function openUrlInNewTab(url, setCurrent, load, index) {
        load = typeof load !== 'undefined' ? load : true
        var tab = tabComponent.createObject(tabContainer, {"initialUrl": url, 'incognito': browser.incognito})
        internal.addTab(tab, setCurrent, index)
        if (load) {
            tab.load()
        }
        if (!url.toString()) {
            internal.maybeFocusAddressBar()
        }
    }

    SessionStorage {
        id: session

        dataFile: dataLocation + "/session.json"

        function save() {
            if (!locked) {
                return
            }
            var tabs = []
            for (var i = 0; i < publicTabsModel.count; ++i) {
                var tab = publicTabsModel.get(i)
                tabs.push(serializeTabState(tab))
            }
            store(JSON.stringify({tabs: tabs, currentIndex: publicTabsModel.currentIndex}))
        }

        function restore() {
            if (!locked) {
                return
            }
            var state = null
            try {
                state = JSON.parse(retrieve())
            } catch (e) {
                return
            }
            if (state) {
                var tabs = state.tabs
                if (tabs) {
                    for (var i = 0; i < Math.min(tabs.length, browser.maxTabsToRestore); ++i) {
                        var tab = createTabFromState(tabs[i])
                        internal.addTab(tab, i == 0)
                    }
                }
                if ('currentIndex' in state) {
                    internal.switchToTab(state.currentIndex, true)
                }
            }
        }

        // Those two functions are used to save/restore the current state of a tab.
        function serializeTabState(tab) {
            var state = {}
            state.uniqueId = tab.uniqueId
            state.url = tab.url.toString()
            state.title = tab.title
            state.icon = tab.icon.toString()
            state.preview = tab.preview.toString()
            state.savedState = tab.webview ? tab.webview.currentState : tab.restoreState
            return state
        }

        function createTabFromState(state) {
            var properties = {'initialUrl': state.url, 'initialTitle': state.title}
            if ('uniqueId' in state) {
                properties["uniqueId"] = state.uniqueId
            }
            if ('icon' in state) {
                properties["initialIcon"] = state.icon
            }
            if ('preview' in state) {
                properties["preview"] = state.preview
            }
            if ('savedState' in state) {
                properties['restoreState'] = state.savedState
                properties['restoreType'] = Oxide.WebView.RestoreLastSessionExitedCleanly
            }
            return tabComponent.createObject(tabContainer, properties)
        }
    }
    Timer {
        id: delayedSessionSaver
        interval: 500
        onTriggered: session.save()
    }
    Timer {
        // Save session periodically to mitigate state loss when the application crashes
        interval: 60000 // every minute
        repeat: true
        running: !browser.incognito
        onTriggered: delayedSessionSaver.restart()
    }
    Timer {
        id: exitFullscreenOnLostFocus
        interval: 500
        onTriggered: {
            if (browser.currentWebview) browser.currentWebview.fullscreen = false
        }
    }
    Connections {
        target: Qt.application
        onStateChanged: {
            if (Qt.application.state != Qt.ApplicationActive) {
                if (!browser.incognito) {
                    session.save()
                }
                if (browser.currentWebview) {
                    // Workaround for a desktop bug where changing volume causes
                    // the app to briefly lose focus to notify-osd, and therefore
                    // exit fullscreen mode. We prevent this by exiting fullscreen
                    // only if the focus remains lost for longer than a certain
                    // threshold. See: https://launchpad.net/bugs/694224.
                    if (__platformName == "xcb") exitFullscreenOnLostFocus.start()
                    else browser.currentWebview.fullscreen = false
                }
            } else exitFullscreenOnLostFocus.stop()
        }
        onAboutToQuit: {
            if (!browser.incognito) {
                session.save()
            }
        }
    }
    Connections {
        target: browser.incognito ? null : publicTabsModel
        onCurrentTabChanged: delayedSessionSaver.restart()
        onCountChanged: delayedSessionSaver.restart()
    }
    onIncognitoChanged: {
        if (incognito) {
            // When going incognito, save the current session right
            // away, as periodic session saving is disabled.
            session.save()
        }
    }

    // Schedule various expensive tasks to a point after the initialization and
    // first rendering of the application have already happened.
    //
    // Scheduling a Timer with the shortest non-zero interval possible (1ms) will
    // effectively queue its onTriggered function to run immediately after anything
    // that is currently in the event loop queue at the moment the Timer starts.
    //
    // The tasks are:
    // - creating the webviews for all initial tabs. This should ideally be done
    //   asynchronously via object incubation, but http://pad.lv/1359911 prevents it
    // - loading the HistoryModel and BookmarksModel from the database
    // - deleting any page screenshots that are no longer needed
    Timer {
        running: true
        interval: 1
        onTriggered: {
            if (!browser.newSession && settings.restoreSession) {
                session.restore()
            }

            // Sanity check
            console.assert(tabsModel.count <= browser.maxTabsToRestore,
                           "WARNING: too many tabs were restored")
            for (var i in browser.initialUrls) {
                browser.openUrlInNewTab(browser.initialUrls[i], true, false)
            }
            if (tabsModel.count == 0) {
                browser.openUrlInNewTab(settings.homepage, true, false)
            }
            tabsModel.currentTab.load()
            if (!tabsModel.currentTab.url.toString() && !tabsModel.currentTab.restoreState) {
                internal.maybeFocusAddressBar()
            }

            BookmarksModel.databasePath = dataLocation + "/bookmarks.sqlite"
            HistoryModel.databasePath = dataLocation + "/history.sqlite"
            DownloadsModel.databasePath = dataLocation + "/downloads.sqlite"

            // Note that the property setter for databasePath won't return until
            // the entire model has been loaded, so it is safe to call this here
            PreviewManager.cleanUnusedPreviews(internal.getOpenPages())
        }
    }

    Connections {
        target: internal
        onFreeMemRatioChanged: {
            if (internal.lowOnMemory) {
                // Unload an inactive tab to (hopefully) free up some memory
                function getCandidate(model) {
                    // Naive implementation that only takes into account the
                    // last time a tab was current. In the future we might
                    // want to take into account other parameters such as
                    // whether the tab is currently playing audio/video.
                    var candidate = null
                    for (var i = 0; i < model.count; ++i) {
                        var tab = model.get(i)
                        if (tab.current || !tab.webview) {
                            continue
                        }
                        if (!candidate || (candidate.lastCurrent > tab.lastCurrent)) {
                            candidate = tab
                        }
                    }
                    return candidate
                }
                var candidate = getCandidate(publicTabsModel)
                if (candidate) {
                    console.warn("Unloading background tab (%1) to free up some memory".arg(candidate.url))
                    candidate.unload()
                    return
                } else if (browser.incognito) {
                    candidate = getCandidate(privateTabsModelLoader.item)
                    if (candidate) {
                        console.warn("Unloading a background incognito tab to free up some memory")
                        candidate.unload()
                        return
                    }
                }
                console.warn("System low on memory, but unable to pick a tab to unload")
            }
        }
    }

    Connections {
        target: tabsModel
        onCurrentIndexChanged: {
            // In narrow mode, the tabslist is a stack:
            // the current tab is always at the top.
            if (!browser.wide) {
                tabsModel.move(tabsModel.currentIndex, 0)
            }
        }
        onCurrentTabChanged: {
            chrome.findInPageMode = false
            var tab = tabsModel.currentTab
            if (tab) {
                tab.load()
            }
            internal.resetFocus()
        }
        onCountChanged: {
            if (tabsModel.count == 0) {
                if (browser.incognito) {
                    browser.incognito = false
                    internal.resetFocus()
                } else if (browser.wide) {
                    Qt.quit()
                }
            }
        }
    }

    Component {
        id: leavePrivateModeDialog

        LeavePrivateModeDialog {
            id: dialogue
            objectName: "leavePrivateModeDialog"

            // This dialog inherits from PopupBase, which has a restoreActiveFocus
            // function that is called when the dialog is hidden. That keeps the
            // focus in the address bar/webview when we leave private mode. So any
            // change on the active focus should be done after the run of such
            // function
            Component.onDestruction: {
                if (!browser.incognito) {
                    internal.resetFocus()
                }
            }

            onCancelButtonClicked: PopupUtils.close(dialogue)
            onOkButtonClicked: {
                PopupUtils.close(dialogue)
                browser.incognito = false
            }
        }
    }

    // TODO: internationalize non-standard key sequences?

    // Ctrl+Tab or Ctrl+PageDown: cycle through open tabs
    Shortcut {
        sequence: StandardKey.NextChild
        enabled: tabContainer.visible || recentView.visible
        onActivated: internal.switchToNextTab()
    }
    Shortcut {
        sequence: "Ctrl+PgDown"
        enabled: tabContainer.visible || recentView.visible
        onActivated: internal.switchToNextTab()
    }

    // Ctrl+Shift+Tab or Ctrl+PageUp: cycle through open tabs in reverse order
    Shortcut {
        sequence: StandardKey.PreviousChild
        enabled: tabContainer.visible || recentView.visible
        onActivated: internal.switchToPreviousTab()
    }
    Shortcut {
        sequence: "Ctrl+Shift+Tab"
        enabled: tabContainer.visible || recentView.visible
        onActivated: internal.switchToPreviousTab()
    }
    Shortcut {
        sequence: "Ctrl+PgUp"
        enabled: tabContainer.visible || recentView.visible
        onActivated: internal.switchToPreviousTab()
    }

    // Ctrl+W or Ctrl+F4: Close the current tab
    Shortcut {
        sequence: StandardKey.Close
        enabled: tabContainer.visible || recentView.visible
        onActivated: internal.closeCurrentTab()
    }
    Shortcut {
        sequence: "Ctrl+F4"
        enabled: tabContainer.visible || recentView.visible
        onActivated: internal.closeCurrentTab()
    }

    // Ctrl+Shift+W or Ctrl+Shift+T: Undo close tab
    Shortcut {
        sequence: "Ctrl+Shift+W"
        enabled: tabContainer.visible || recentView.visible
        onActivated: internal.undoCloseTab()
    }
    Shortcut {
        sequence: "Ctrl+Shift+T"
        enabled: tabContainer.visible || recentView.visible
        onActivated: internal.undoCloseTab()
    }

    // Ctrl+T: Open a new Tab
    Shortcut {
        sequence: StandardKey.AddTab
        enabled: tabContainer.visible || recentView.visible ||
                 bookmarksViewLoader.active || historyViewLoader.active
        onActivated: {
            openUrlInNewTab("", true)
            if (recentView.visible) recentView.reset()
            bookmarksViewLoader.active = false
            historyViewLoader.active = false
        }
    }

    // F6 or Ctrl+L or Alt+D: Select the content in the address bar
    Shortcut {
        sequence: "F6"
        enabled: tabContainer.visible
        onActivated: internal.focusAddressBar(true)
    }
    Shortcut {
        sequence: "Ctrl+L"
        enabled: tabContainer.visible
        onActivated: internal.focusAddressBar(true)
    }
    Shortcut {
        sequence: "Alt+D"
        enabled: tabContainer.visible
        onActivated: internal.focusAddressBar(true)
    }

    // Ctrl+D: Toggle bookmarked state on current Tab
    Shortcut {
        sequence: "Ctrl+D"
        enabled: tabContainer.visible
        onActivated: {
            if (internal.currentBookmarkOptionsDialog) {
                internal.currentBookmarkOptionsDialog.hide()
            } else if (currentWebview) {
                if (BookmarksModel.contains(currentWebview.url)) {
                    BookmarksModel.remove(currentWebview.url)
                } else {
                    internal.addBookmark(currentWebview.url, currentWebview.title, currentWebview.icon)
                }
            }
        }
    }

    // Ctrl+H: Show History
    Shortcut {
        sequence: "Ctrl+H"
        enabled: tabContainer.visible
        onActivated: historyViewLoader.active = true
    }

    // Ctrl+Shift+O: Show Bookmarks
    Shortcut {
        sequence: "Ctrl+Shift+O"
        enabled: tabContainer.visible
        onActivated: bookmarksViewLoader.active = true
    }

    // Alt+← or Backspace: Goes to the previous page in history
    Shortcut {
        sequence: StandardKey.Back
        enabled: tabContainer.visible
        onActivated: internal.historyGoBack()
    }

    // Alt+→ or Shift+Backspace: Goes to the next page in history
    Shortcut {
        sequence: StandardKey.Forward
        enabled: tabContainer.visible
        onActivated: internal.historyGoForward()
    }

    // F5 or Ctrl+R: Reload current Tab
    Shortcut {
        sequence: StandardKey.Refresh
        enabled: tabContainer.visible
        onActivated: if (currentWebview) currentWebview.reload()
    }
    Shortcut {
        sequence: "F5"
        enabled: tabContainer.visible
        onActivated: if (currentWebview) currentWebview.reload()
    }

    // Ctrl+F: Find in Page
    Shortcut {
        sequence: StandardKey.Find
        enabled: tabContainer.visible && !newTabViewLoader.active
        onActivated: chrome.findInPageMode = true
    }

    // Ctrl+J: Show downloads page
    Shortcut {
        sequence: "Ctrl+J"
        enabled: chrome.visible &&
                 downloadHandlerLoader.status == Loader.Ready &&
                 contentHandlerLoader.status == Loader.Ready &&
                 !downloadsViewLoader.active
        onActivated: downloadsViewLoader.active = true
    }

    // Ctrl+G: Find next
    Shortcut {
        sequence: StandardKey.FindNext
        enabled: currentWebview && chrome.findInPageMode
        onActivated: currentWebview.findController.next()
    }

    // Ctrl+Shift+G: Find previous
    Shortcut {
        sequence: StandardKey.FindPrevious
        enabled: currentWebview && chrome.findInPageMode
        onActivated: currentWebview.findController.previous()
    }

    Loader {
        id: contentHandlerLoader
        source: "../ContentHandler.qml"
        asynchronous: true
    }

    Connections {
        target: contentHandlerLoader.item
        onExportFromDownloads: {
            if (downloadHandlerLoader.status == Loader.Ready) {
                downloadsViewLoader.active = true
                downloadsViewLoader.item.mimetypeFilter = mimetypeFilter
                downloadsViewLoader.item.activeTransfer = transfer
                downloadsViewLoader.item.multiSelect = multiSelect
                downloadsViewLoader.item.pickingMode = true
            }
        }
    }

    Loader {
        id: downloadDialogLoader
        source: "ContentDownloadDialog.qml"
        asynchronous: true
    }

    Loader {
        id: filePickerLoader
        source: "ContentPickerDialog.qml"
        asynchronous: true
    }
}