~nhoad/roland

ref: d7fbf88565552f72677caa836d76ffa427288c76 roland/roland/core.py -rw-r--r-- 66.9 KiB View raw
d7fbf885 — Nathan Hoad In practice, related webviews are basically always available, so this creates a single enormous webview. 2 years ago
                                                                                
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
#!/usr/bin/env python3

import base64
import code
import collections
import datetime
import faulthandler
import fnmatch
import functools
import html
import itertools
import os
import pathlib
import random
import shlex
import threading
from urllib import parse as urlparse

import logbook
import msgpack

from gi.repository import GObject, Gdk, Gio, Gtk, Pango, GLib, WebKit2, GdkPixbuf

from .api import Mode
from .utils import (
    cache_path, config_path, runtime_path, get_keyname, get_pretty_size,
    init_logging, RolandConfigBase)


faulthandler.enable()
log = logbook.Logger('roland')

HTMLNotification = collections.namedtuple('HTMLNotification', 'id title body')

DEFAULT_STYLE = b'''
    GtkEntry, GtkLabel {
        background: black;
        color: white;
    }
'''


def rename(name):
    def callable(func):
        func.__name__ = name
        return func
    return callable


def requires(*extensions):
    def inner(func):
        func.extensions = extensions
        return func
    return inner


def private(func):
    """Decorator for methods on BrowserCommands that shouldn't be displayed in
    the command suggestions.
    """
    func.private = True
    return func


request_counter = itertools.count(1)


def message_webprocess(command, *, page_id, profile, callback, **kwargs):
    # FIXME: make this whole thing asyncio friendly, getting rid of callback
    # and everything..

    request_id = next(request_counter)
    p = runtime_path('webprocess.{{}}.{}'.format(page_id), profile)
    addr = Gio.UnixSocketAddress.new(p)
    client = Gio.SocketClient.new()

    unpacker = msgpack.Unpacker()

    def connect_callback(obj, result, user_data):
        conn = client.connect_finish(result)
        ostream = conn.get_output_stream()

        # FIXME: make write async
        r = msgpack.dumps([request_id, command, kwargs])
        ostream.write_bytes(GLib.Bytes(r))

        istream = conn.get_input_stream()
        istream.read_bytes_async(8192, 1, None, read_callback, conn)

    def read_callback(obj, result, conn):
        istream = conn.get_input_stream()
        bytes = istream.read_bytes_finish(result)
        if not bytes.get_data():
            conn.close(None)

            response_id, notes = unpacker.unpack()
            if callback is not None:
                callback(notes)
        else:
            unpacker.feed(bytes.get_data())
            istream.read_bytes_async(8192, 1, None, read_callback, conn)

    client.connect_async(addr, None, connect_callback, None)


class BrowserCommands:
    def font(self, *font):
        self.roland.change_font(' '.join(font))

    @rename('tab-bar-width')
    def tab_bar_width(self, width):
        width = int(width)
        for b in self.roland.get_browsers():
            b.tab_title.set_width_chars(width)
            b.tab_title.set_max_width_chars(width)
        self.roland.config.tab_width = width

    @rename('move-tab')
    def move_tab(self, position):
        # FIXME: this also needs to reorder it in Roland's list as well
        notebook = self.roland.window.notebook
        notebook.reorder_child(self, int(position))

    @rename('toggle-tab-bar-visibility')
    def toggle_tab_visibility(self):
        notebook = self.roland.window.notebook
        notebook.set_show_tabs(not notebook.get_show_tabs())

    @rename('tab-bar-position')
    def tab_bar_position(self, position):
        self.roland.set_tab_position(position)

    @requires('PasswordManagerExtension')
    @rename('generate-password')
    def generate_password(self, *params):
        ext = self.roland.get_extension('PasswordManagerExtension')
        if not params:
            params = ['len=24', 'chars=all', 'mixed=yes']

        def parse_params():
            nonlocal params

            try:
                params = dict(kv.split('=') for kv in params)
            except Exception as e:
                self.roland.notify("Could not parse generation parameters: {}".format(e))
                params = {}

            params.setdefault('len', '24')
            params.setdefault('chars', 'all')
            params.setdefault('mixed', 'yes')
            return params

        def generate_password():
            params = parse_params()
            # FIXME: lookup domain in db and prompt to use that one or generate another
            allowable_chars = params['chars']
            if allowable_chars == 'all':
                allowable_chars = 'special,alpha'

            available_chars = ''
            if 'special' in allowable_chars:
                available_chars += '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
            if 'numbers' in allowable_chars:
                available_chars += '0123456789'
            if 'alpha' in allowable_chars:
                available_chars += 'abcdefghijklmnopqrstuvwxyz'
            if params['mixed'].lower() == 'yes':
                available_chars += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

            password = ''.join(random.sample(available_chars, int(params['len'])))
            return password

        password = generate_password()

        try:
            ext.unlock(self)
        except ValueError:
            self.roland.notify('Could not generate password')
        else:
            domain = urlparse.urlparse(self.webview.get_uri()).netloc
            description = 'Generated password for {}'.format(domain)
            form = {
                'input[type=password]': password,
            }
            ext.save_form(domain, form, description=description)

            message_webprocess(
                'form_fill',
                profile=self.roland.profile,
                page_id=self.webview.get_page_id(),
                callback=None,
                **{k.decode('utf8'): v for (k, v) in form.items()}
            )

    @requires('PasswordManagerExtension')
    @rename('form-save')
    def form_save(self):
        forms = {}
        ext = self.roland.get_extension('PasswordManagerExtension')

        def serialised_form(form):
            self.remove_overlay()

            domain = urlparse.urlparse(self.webview.get_uri()).netloc

            try:
                ext.unlock(self)
            except ValueError:
                self.roland.notify('Could not save form')
            else:
                ext.save_form(domain, form)

        def display_choices(choices):
            forms.update(choices)
            result = self.entry_line.blocking_prompt(
                prompt='Select form to save',
                suggestions=sorted(k.decode('utf8') for k in forms.keys()),
                force_match=True,
            )
            if result is None:
                return
            form_id = forms[result.encode('utf8')].decode('utf8')

            message_webprocess(
                'serialise_form',
                form_id=form_id,
                profile=self.roland.profile,
                page_id=self.webview.get_page_id(),
                callback=serialised_form,
            )

        message_webprocess(
            'highlight',
            selector='form',
            profile=self.roland.profile,
            page_id=self.webview.get_page_id(),
            callback=display_choices,
        )

    @requires('PasswordManagerExtension')
    @rename('form-fill')
    def form_fill(self):
        ext = self.roland.get_extension('PasswordManagerExtension')

        domain = urlparse.urlparse(self.webview.get_uri()).netloc
        try:
            ext.unlock(self)
        except ValueError:
            return
        else:
            choices = ext.get_for_domain(domain.encode('utf8'))

        if not choices:
            self.roland.notify("No form fills for {}".format(domain))
            return

        suggestions = ['{}: {} (last used {})'.format(i, choice.description.decode('utf8'), choice.last_used)
                       for (i, choice) in enumerate(choices)]

        result = self.entry_line.blocking_prompt(
            prompt='Select form fill for {}'.format(domain),
            suggestions=suggestions,
            force_match=True,
        )

        if result is None:
            return

        index, ignore = result.split(':', 1)
        choice = choices[int(index)]

        form_data = choice.form_data

        ext.update_last_used(choice.id)

        message_webprocess(
            'form_fill',
            profile=self.roland.profile,
            page_id=self.webview.get_page_id(),
            callback=None,
            **{k.decode('utf8'): v for (k, v) in form_data.items()}
        )

    def filter_windows(self):
        browsers = self.roland.get_browsers()
        names = {'%d: %s' % (i, w.get_title()): w for (i, w) in enumerate(browsers, 1)}
        # get text from blocking_prompt, filled with suggestions
        options = self.entry_line.filter_suggestions(
            prompt="Window(s) to close", suggestions=list(names))
        return [names[k] for k in options]

    @private
    def select_window(self, selected=None):
        def present_window(selected):
            try:
                win_id = name_to_id[selected]
                win = id_to_window[win_id]
            except KeyError:
                pass
            else:
                win.present()

        browsers = self.roland.get_browsers()
        name_to_id = {'%d: %s' % (i, w.get_title()): i for (i, w) in enumerate(browsers, 1)}
        id_to_window = {i: w for (i, w) in enumerate(browsers, 1)}

        if selected is not None:
            if selected == -1:
                selected = max(id_to_window)

            try:
                win = id_to_window[selected]
            except KeyError:
                pass
            else:
                win.present()
            return True
        else:
            browsers = self.roland.get_browsers()
            name_to_id = {'%d: %s' % (i, w.get_title()): i for (i, w) in enumerate(browsers, 1)}
            id_to_window = {i: w for (i, w) in enumerate(browsers, 1)}

            self.entry_line.prompt(
                present_window, prompt="Window", force_match=True, glob=True,
                suggestions=sorted(name_to_id))
        return True

    @private
    def open(self, *, url=None, new_window=False, background=False):
        def open_window(url):
            if background or new_window:
                if new_window:
                    log.info("Loading {} in a new window", url)
                elif background:
                    log.info("Loading {} in a background window", url)
                self.roland.new_window(url, background=background)
            else:
                log.info("Loading {}", url)
                self.webview.load_uri(url)

        if not url:
            prompt = 'open'
            if background:
                prompt += ' (new background window)'
            elif new_window:
                prompt += ' (new window)'
            self.entry_line.prompt(
                open_window, prompt=prompt, glob=True,
                suggestions=self.roland.most_popular_urls())
        else:
            open_window(url)
        return True

    @requires('SessionManager')
    @rename('save-session')
    def save_session(self):
        """Save the current session."""
        self.roland.get_extension('SessionManager').save_session()

    @private
    def open_or_search(self, *, text=None, new_window=False, background=False):
        run_search = functools.partial(self.search, new_window=new_window, background=background)
        run_open = functools.partial(self.open, new_window=new_window, background=background)

        def callback(obj, result, text):
            resolver = Gio.Resolver.get_default()

            try:
                resolver.lookup_by_name_finish(result)
            except Exception:
                run_search(text=text)
            else:
                run_open(url='http://'+text)

        def open_or_search(text):
            if urlparse.urlparse(text).scheme:
                run_open(url=text)
            else:
                if '://' not in text:
                    maybe_url = 'http://{}'.format(text)
                else:
                    maybe_url = text

                maybe_hostname = urlparse.urlparse(maybe_url).hostname

                if maybe_hostname and (' ' in maybe_hostname or '_' in maybe_hostname):
                    run_search(text)
                else:
                    resolver = Gio.Resolver.get_default()
                    resolver.lookup_by_name_async(
                        text.split('/')[0].split(':')[0], None, callback, text)

        if text is None:
            prompt = 'open/search'
            if background:
                prompt += ' (new background window)'
            elif new_window:
                prompt += ' (new window)'

            self.entry_line.prompt(
                open_or_search, prompt=prompt, glob=True,
                suggestions=self.roland.most_popular_urls())
        else:
            open_or_search(text)
        return True

    @private
    def open_modify(self, new_window=False):
        def open_window(url):
            self.open(url=url, new_window=new_window)

        prompt = 'open'
        if new_window:
            prompt += ' (new window)'

        self.entry_line.prompt(
            open_window, prompt=prompt, initial=self.webview.get_uri() or '')
        return True

    @private
    def navigate_up(self):
        url = self.webview.get_uri()
        url = urlparse.urlparse(url)
        if url.path not in ('', '/'):
            parent_path = str(pathlib.Path(url.path).parent)
            url = url._replace(path=parent_path).geturl()
            self.open(url=url)

    @private
    def navigate_top(self):
        url = self.webview.get_uri()
        url = urlparse.urlparse(url)._replace(path='').geturl()
        self.open(url=url)

    def close(self):
        """Close the given window. Quits if there's only one window."""
        # explicitly trigger quitting in case downloads are in progress
        if len(self.roland.get_browsers()) == 1:
            self.roland.quit()
            return

        if self.webview is None:
            return

        self.roland.add_close_history(self.webview.get_uri(), self.get_serialised_session_state())

    @private
    def change_user_agent(self, user_agent=None):
        def change_user_agent(user_agent):
            if not user_agent:
                return
            for browser in self.roland.get_browsers():
                browser.web_view.get_settings().props.user_agent = user_agent

        if user_agent is None:
            user_agents = [self.roland.config.default_user_agent] + self.roland.hooks('user_agent_choices', default=[])
            self.entry_line.prompt(change_user_agent, prompt="User Agent", suggestions=user_agents)
        else:
            change_user_agent(user_agent)
        return True

    @private
    def search(self, text=None, new_window=False, background=False):
        def search(text):
            search_url = self.roland.config.search_page.format(text)
            url = self.roland.hooks('search_url', text, default=None) or search_url
            self.open(url=url, new_window=new_window, background=background)

        if text is None:
            self.entry_line.prompt(search, prompt='Search')
        else:
            search(text)
        return True

    def back(self):
        """Go backward in navigation history."""
        self.webview.go_back()

    def forward(self):
        """Go forward in navigation history."""
        self.webview.go_forward()

    def javascript(self, script):
        """Execute given JavaScript."""
        self.webview.run_javascript(script, None, None, None)

    @rename('view-source')
    def view_source(self):
        def have_source(source):
            html = source[b'html'].decode('utf8')

            uri = self.webview.get_uri()

            try:
                import pygments
                import pygments.lexers
                import pygments.formatters
            except ImportError:
                self.roland.new_window(uri, text=html)
            else:
                lexer = pygments.lexers.HtmlLexer()
                formatter = pygments.formatters.HtmlFormatter(
                    full=True, linenos='table')
                highlighted = pygments.highlight(html, lexer, formatter)
                self.roland.new_window(uri, html=highlighted)

        message_webprocess(
            'get_source',
            profile=self.roland.profile,
            page_id=self.webview.get_page_id(),
            callback=have_source
        )

    @private
    def remove_overlay(self):
        message_webprocess(
            'remove_overlay',
            profile=self.roland.profile,
            page_id=self.webview.get_page_id(),
            callback=None,
        )

    @rename('yank-links')
    @requires('ClipboardManager')
    def yank_links(self, selector=None):
        def yank_link(yank_map, key):
            try:
                yank_id = yank_map[key.encode('utf8')].decode('utf8')
            except KeyError:
                self.remove_overlay()
            else:
                message_webprocess(
                    'yank',
                    yank_id=yank_id,
                    profile=self.roland.profile,
                    page_id=self.webview.get_page_id(),
                    callback=None
                )

        return self.follow(open_callback=yank_link, selector='a[href]', prompt='Yank Link')

    @private
    def follow(self, new_window=False, selector=None, open_callback=None, prompt='Follow'):
        def open_link(click_map, key):
            try:
                click_id = click_map[key.encode('utf8')].decode('utf8')
            except KeyError:
                self.remove_overlay()
            else:
                message_webprocess(
                    'click',
                    click_id=click_id,
                    new_window=new_window,
                    profile=self.roland.profile,
                    page_id=self.webview.get_page_id(),
                    callback=None
                )

        def display_choices(choices):
            nonlocal prompt

            click_map.update(choices)

            if new_window:
                prompt += ' (new window)'
            suggestions = sorted([
                s.decode('utf8').replace('\n', ' ')
                for s in click_map.keys()], key=lambda s: int(s.split(':')[0]))
            self.entry_line.prompt(
                functools.partial(open_callback or open_link, click_map), prompt=prompt, cancel=self.remove_overlay,
                suggestions=suggestions, force_match=True, beginning=False)

        click_map = {}

        if selector is not None:
            pass
        elif new_window:
            selector = 'a'
        else:
            selector = "a, input:not([type=hidden]), textarea, select, button"

        message_webprocess(
            'highlight',
            selector=selector,
            profile=self.roland.profile,
            page_id=self.webview.get_page_id(),
            callback=display_choices,
        )

        return True

    @private
    def search_page(self, text=None, forwards=True, case_insensitive=None):
        def search_page(text):
            nonlocal case_insensitive
            if case_insensitive is None:
                case_insensitive = text.lower() == text

            finder = self.webview.get_find_controller()

            if text == '':
                finder.search_finish()
                return

            self.search_forwards = forwards

            options = WebKit2.FindOptions.WRAP_AROUND
            if not forwards:
                options |= WebKit2.FindOptions.BACKWARDS

            if case_insensitive:
                options |= WebKit2.FindOptions.CASE_INSENSITIVE

            max_count = 1000  # FIXME: configurable?
            finder.search(text, options, max_count)

        if text is None:
            self.entry_line.prompt(search_page, prompt='Search page')
        else:
            search_page(text)
        return True

    @private
    def next_search_result(self, forwards=True):
        finder = self.webview.get_find_controller()

        if forwards == self.search_forwards:
            finder.search_next()
        else:
            finder.search_previous()

    @private
    def zoom_in(self):
        self.webview.set_zoom_level(self.webview.get_zoom_level() + 0.1)
        # binding for C-Up scrolls, this stops that
        return True

    @private
    def zoom_out(self):
        zoom_level = self.webview.get_zoom_level() - 0.1
        if zoom_level >= 0.1:
            self.webview.set_zoom_level(zoom_level)
        # binding for C-Down scrolls, this stops that
        return True

    def zoom(self, level):
        """Set zoom to given level, e.g. 'zoom 200' for 200%."""
        self.webview.set_zoom_level(float(level)/100)

    @private
    def zoom_reset(self):
        self.zoom(getattr(self.roland.config, 'default_zoom', 100))

    def stop(self):
        """Stop loading the current page."""
        self.webview.stop_loading()

    @private
    def move(self, x=0, y=0):
        self.javascript('window.scrollBy(%d, %d);' % (x*30, y*30))

    def shell(self):
        """Open a Python REPL on stdout."""
        self.roland.notify('Starting shell...')
        locals = {
            'config': self.roland.config,
            'roland': self.roland,
        }
        t = threading.Thread(target=code.interact, kwargs={'local': locals})
        t.daemon = True
        t.start()

    def quit(self):
        """Close the browser."""
        self.roland.quit()

    def reload(self):
        """Reload the page."""
        self.webview.reload()

    @rename('reload-bypass-cache')
    def reload_bypass_cache(self):
        """Reload the page, ignoring the disk cache."""
        self.webview.reload_bypass_cache()

    @rename('clear-cache')
    def clear_cache(self):
        """Clear the disk cache."""
        context = WebKit2.WebContext.get_default()
        context.clear_cache()

    def help(self):
        """This very informative help."""
        available_commands = sorted(self.roland.get_commands())
        help_info = '\t' + '\n\t'.join('{} - {}'.format(cmd, self.roland.get_help(cmd)) for cmd in available_commands)

        config = self.roland.config

        command_info = '\t' + '\n\t'.join(sorted([
            '{}: {}'.format(key, command)
            for (key, command) in config.commands.items()
        ]))

        misc_info = '\t' + '\n\t'.join([
            'home page: {}'.format(config.home_page),
            'search page: {}'.format(config.search_page),
            'font: {}'.format(config.font),
        ])

        page_info = '\n'.join([
            'Commands',
            help_info,
            '\nBindings:',
            command_info,
            '\nMisc:',
            misc_info
        ])
        self.roland.new_window(None, page_info)

    # FIXME: make host optional - if the current page has an invalid
    # certificate, bypass that instead.
    @requires('TLSErrorByPassExtension')
    def bypass(self, host):
        """Set up a certificate exclusion for a given domain."""
        manager = self.roland.get_extension('TLSErrorByPassExtension')
        manager.bypass(host)

    @requires('DownloadManager')
    @private
    def cancel_download(self):
        if not self.roland.downloads:
            self.roland.notify("No downloads in progress")
            return

        def cancel_download(key):
            try:
                download = self.roland.downloads[key]
            except KeyError:
                self.roland.notify("No download by that name")
            else:
                download.cancel()

        self.entry_line.prompt(
            cancel_download, prompt="Cancel download", force_match=True,
            glob=True, suggestions=list(self.roland.downloads.keys()))

        return True

    @rename('inspector-show')
    def inspector_show(self):
        self.webview.get_inspector().show()

    @rename('inspector-hide')
    def inspector_hide(self):
        self.webview.get_inspector().close()

    @private
    def undo_close(self):
        self.roland.undo_close()

    @private
    def open_from_clipboard(self):
        t = self.get_clipboard()
        if t:
            self.open_or_search(text=t, background=True)

    @requires('DownloadManager')
    @private
    def list_downloads(self):
        if not self.roland.downloads:
            self.roland.notify("No downloads in progress")
            return

        for location, download in self.roland.downloads.items():
            if download.get_progress() == 1.0:
                continue  # completed while we were doing this
            progress = get_pretty_size(download.get_current_size())
            total = get_pretty_size(download.get_total_size())
            self.roland.notify('%s - %s out of %s' % (location, progress, total))

    @private
    def get_certificate_info(self, certificate=None):
        certificate = certificate or self.pem_certificate

        if not certificate:
            return ''
        else:
            from OpenSSL import crypto

            x509 = crypto.load_certificate(
                crypto.FILETYPE_PEM, certificate)

            extensions = [
                x509.get_extension(i) for i in
                range(x509.get_extension_count())
            ]

            keyed_extensions = {}
            for ext in extensions:
                name = ext.get_short_name().decode('utf8')
                try:
                    value = str(ext)
                except Exception:
                    value = 'Value unavailable'
                keyed_extensions[name] = value

            buf = certificate
            buf += '\nsubject:'
            buf += '/'.join(
                b'='.join(kv).decode('utf8') for kv in x509.get_subject().get_components())

            buf += '\nissuer:'
            buf += '/'.join(
                b'='.join(kv).decode('utf8') for kv in x509.get_issuer().get_components())

            buf += '\nsignature algorithm: {}'.format(x509.get_signature_algorithm())

            def time_parse(raw):
                raw = raw.decode('utf8').replace('Z', '')
                return datetime.datetime.strptime(raw, '%Y%m%d%H%M%S')

            start = time_parse(x509.get_notBefore())
            end = time_parse(x509.get_notAfter())
            buf += '\nvalid time range: {} - {}'.format(start, end)

            buf += '\nextensions:'
            buf += ', '.join(sorted(keyed_extensions))

            buf += '\nsubjectAltName:\n\t'
            buf += keyed_extensions.get('subjectAltName', '').replace(', ', '\n\t')
            return buf

    def certificate(self):
        """Display certificate information for the given website, if available."""
        cert_info = self.get_certificate_info()

        if cert_info:
            self.roland.new_window(None, cert_info)
        else:
            self.roland.notify("No certificate information available")


class EntryLine(Gtk.VBox):
    def __init__(self, status_line, browser):
        Gtk.VBox.__init__(self)

        self.status_line = status_line
        self.browser = browser

        self.label = Gtk.Label()
        self.label.set_alignment(0.0, 0.5)

        self.input = Gtk.Entry()
        self.input.set_has_frame(False)

        self.input.connect('key-release-event', self.on_key_release_event)
        self.input.connect('backspace', self.on_key_release_event, None)

        self.input_container = Gtk.HBox()
        self.input_container.pack_start(self.label, False, False, 0)
        self.input_container.pack_start(self.input, True, True, 0)

        self.pack_end(self.input_container, False, False, 0)

    def completion(self, forward=True):
        if not self.lock_suggestions:
            self.lock_suggestions = True
            self.position = -1

        labels = [l.get_text() for l in self.get_children() if isinstance(l, Gtk.Label)]

        if forward:
            self.position = self.position + 1
            if self.position == len(labels):
                self.position = 0
        else:
            self.position = self.position - 1
            if self.position <= -1:
                self.position = len(labels) - 1

        if labels:
            self.input.set_text(labels[self.position])
            self.input.set_position(-1)

    def on_key_release_event(self, widget, event):
        keyname = get_keyname(event)
        if keyname in ('ISO_Left_Tab', 'Tab'):
            return
        self.lock_suggestions = False

        self.remove_completions()
        self.add_completions()

        return False

    def blocking_prompt(self, **kwargs):
        result = None

        def callback(value):
            nonlocal result
            result = value
            loop.stop()

        def cancel():
            loop.stop()

        self.browser.present()
        self.prompt(callback, cancel=cancel, **kwargs)
        import gbulb
        loop = gbulb.get_event_loop()
        loop.run()

        return result

    def prompt(self, callback, suggestions=None, force_match=False,
               glob=False, prompt='', initial='', cancel=None,
               case_sensitive=False, beginning=True, private=False):
        self.callback = callback
        self.suggestions = suggestions or []
        self.force_match = force_match
        self.glob = glob
        self.lock_suggestions = False
        self.cancel = cancel
        self.case_sensitive = case_sensitive
        self.beginning = beginning
        self.input.set_visibility(not private)

        self.label.set_markup('{}:'.format(prompt))
        self.label.show()
        self.show()
        self.input.set_text(initial)
        if initial:
            self.input.set_position(-1)
        self.input.show()
        self.status_line.hide()
        self.get_toplevel().set_focus(self.input)
        self.input.select_region(-1, -1)

        self.remove_completions()
        self.add_completions()
        self.browser.set_mode(Mode.Prompt)

    def filter_suggestions(self, suggestions, prompt):
        result = self.blocking_prompt(
            prompt=prompt, suggestions=suggestions, glob=False, beginning=False)
        if result is None:
            return []
        return [s for s in suggestions if result.casefold() in s.casefold()]

    def fire_cancel_callback(self):
        if self.cancel:
            cancel, self.cancel = self.cancel, None
            cancel()

    def fire_callback(self):
        t = self.input.get_text()
        if self.force_match:
            labels = [l.get_text() for l in self.get_children() if isinstance(l, Gtk.Label)]
            if labels and t not in labels:
                t = labels[0]

        assert self.callback is not None

        callback, self.callback = self.callback, None
        callback(t)

    def hide_input(self):
        self.hide()
        self.status_line.show()
        self.get_toplevel().set_focus(None)

    def add_completions(self):
        t = self.input.get_text()
        if self.glob:
            entries = fnmatch.filter(self.suggestions, '*{}*'.format(t))
        else:
            if self.case_sensitive:
                f = lambda a: a
            else:
                f = str.casefold

            if self.beginning:
                condition = str.startswith
            else:
                condition = str.__contains__

            entries = [e for e in self.suggestions if condition(f(e), f(t))]

        for entry in reversed(entries[:20]):
            # FIXME: highlight matching portion
            l = Gtk.Label()
            l.set_alignment(0.0, 0.5)
            l.set_text(entry)
            self.pack_end(l, False, False, 0)
            l.show()

    def remove_completions(self):
        for child in self.get_children():
            if child != self.input_container:
                self.remove(child)


class StatusLine(Gtk.HBox):
    def __init__(self):
        Gtk.HBox.__init__(self)

        self.left = Gtk.Label()
        self.middle = Gtk.Label()
        self.right = Gtk.Label()

        self.left.set_alignment(0.0, 0.5)
        self.right.set_alignment(1.0, 0.5)

        self.left.set_name('NormalMode')

        for i in [self.left, self.middle, self.right]:
            self.add(i)

        self.info_text = ''
        self.uri = ''
        self.trusted = True

    def set_uri(self, uri):
        self.uri = uri
        self.update_right()

    def set_mode(self, text, name=None):
        self.left.set_markup(text)
        if name is not None:
            self.left.set_name(name)

    def set_trust(self, trusted):
        self.trusted = trusted
        self.update_right()

    def set_info_text(self, text):
        self.info_text = text
        self.update_right()

    def update_right(self):
        text = []
        if self.info_text:
            text.append('<b><span foreground="#01a0e4">{}</span></b>'.format(self.info_text))

        if self.uri:
            uri = ''.join([
                '<span foreground="{color}"><b>'.format(color='limegreen' if self.trusted else 'red'),
                html.escape(self.uri),
                '</b></span>',
            ])
            text.append(uri)

        self.right.set_markup(' '.join(text))


class BrowserTitle:
    title = ''
    progress = 0

    def __str__(self):
        if self.progress < 100:
            return '[{}%] Loading... {}'.format(self.progress, self.title)
        return self.title or 'No title'


class BrowserView(BrowserCommands):
    pem_certificate = None

    def get_serialised_session_state(self):
        session = self.webview.get_session_state().serialize().get_data()
        session = base64.b64encode(session).decode('utf8')
        return session

    def on_decide_policy(self, webview, decision, decision_type):
        if decision_type == WebKit2.PolicyDecisionType.NAVIGATION_ACTION:
            action = decision.get_navigation_action()
            mouse = action.get_mouse_button()
            mod = action.get_modifiers()

            # 1 == left, 2 == middle
            if ((mouse == 1 and mod & Gdk.ModifierType.CONTROL_MASK) or
                    mouse == 2):
                webview = webview.emit('create', action)
                if webview is not None:
                    webview.load_uri(action.get_request().get_uri())
                webview.emit('ready-to-show')

                decision.ignore()
                return True
            return False
        elif decision_type != WebKit2.PolicyDecisionType.RESPONSE:
            return False  # let default action take place

        if decision.is_mime_type_supported():
            decision.use()

            if self.webview == webview:
                self.status_line.set_trust(True)  # assume trust until told otherwise
            return False

        download_manager = self.roland.get_extension('DownloadManager')

        uri = webview.get_uri()

        if download_manager is None:
            self.roland.notify("Cannot display {}, and download manager is not enabled.".format(uri))
            decision.ignore()
        else:
            decision.download()

        return False

    def __init__(self, roland, lazy=False):
        super().__init__()
        self.roland = roland
        self.search_forwards = True
        self.title = BrowserTitle()
        self.webview = None
        self.sub_commands = None
        self.lazy = lazy

    @classmethod
    def from_webview(cls, browser, roland):
        self = cls(roland)
        self.webview = browser
        self.webview.connect('ready-to-show', lambda *args: self.start())
        return self

    def start(self, url=None, session=None):
        self.connect('key-press-event', self.on_key_press_event)

        # will already be initialised for popups
        if self.webview is None:
            self.webview = self.roland.new_webview()

        settings = self.webview.get_settings()
        settings.props.user_agent = self.roland.config.default_user_agent
        settings.props.enable_frame_flattening = getattr(self.roland.config, 'enable_frame_flattening', False)
        settings.props.enable_webgl = getattr(self.roland.config, 'enable_webgl', False)
        settings.props.enable_accelerated_2d_canvas = getattr(self.roland.config, 'enable_accelerated_2d_canvas', False)
        settings.props.enable_developer_extras = True

        self.status_line = StatusLine()
        self.entry_line = EntryLine(self.status_line, self)

        self.set_mode(Mode.Normal)

        self.zoom_reset()

        self.webview.connect('notify::favicon', self.update_window_icon)
        self.webview.connect('notify::title', self.update_title_from_event)
        self.webview.connect('mouse-target-changed', self.mouse_target_changed)
        self.webview.connect('notify::estimated-load-progress', self.update_title_from_event)
        self.webview.connect('authenticate', self.on_authenticate)
        self.webview.connect('load-changed', self.on_load_status)
        self.webview.connect('load-failed-with-tls-errors', self.on_load_failed_with_tls_errors)
        self.webview.connect('close', lambda *args: self.destroy())
        self.webview.connect('create', self.on_create_web_view)
        self.webview.connect('show-notification', self.on_show_notification)
        self.webview.connect('permission-request', self.on_permission_request)
        self.webview.connect('web-process-crashed', self.on_web_process_crashed)
        self.webview.connect('resource-load-started', self.on_resource_load_started)
        self.webview.connect('script-dialog', self.on_script_dialog)
        self.webview.connect('notify::uri', self.update_uri)

        # I never want context menus.
        self.webview.connect('context-menu', lambda *args: True)

        finder = self.webview.get_find_controller()
        finder.connect('failed-to-find-text', self.failed_to_find_text)

        self.webview.connect('decide-policy', self.on_decide_policy)

        main_ui_box = Gtk.VBox()
        scrollable = Gtk.ScrolledWindow()
        scrollable.add(self.webview)
        overlay = Gtk.Overlay()
        overlay.add(scrollable)
        main_ui_box.pack_start(overlay, True, True, 0)

        main_ui_box.pack_end(self.status_line, False, False, 0)
        overlay.add_overlay(self.entry_line)

        self.add(main_ui_box)
        self.show_all()
        self.entry_line.hide_input()

        session = session or getattr(self, 'lazy_session', None)
        url = url or getattr(self, 'lazy_uri', None)

        if session is not None:
            session = base64.b64decode(session.encode('utf8'))
            session = WebKit2.WebViewSessionState(GLib.Bytes(session))
            self.webview.restore_session_state(session)

        # will be None for popups
        if url is not None:
            self.open_or_search(text=url)

        self.lazy = False

    def update_uri(self, webview, event):
        self.status_line.set_uri(webview.get_uri())

    def on_load_failed_with_tls_errors(self, webview, failing_uri, certificate, error):
        if self.webview == webview:
            self.pem_certificate = certificate.props.certificate_pem

        certificate_info = self.get_certificate_info(certificate.props.certificate_pem)

        reasons = []
        if error & Gio.TlsCertificateFlags.UNKNOWN_CA:
            reasons.append('Unknown CA')
        if error & Gio.TlsCertificateFlags.BAD_IDENTITY:
            reasons.append('Bad Identity')
        if error & Gio.TlsCertificateFlags.NOT_ACTIVATED:
            reasons.append('Certificate not activated yet')
        if error & Gio.TlsCertificateFlags.NOT_ACTIVATED:
            reasons.append('Certificate has expired')
        if error & Gio.TlsCertificateFlags.REVOKED:
            reasons.append('Certificate has been revoked')
        if error & Gio.TlsCertificateFlags.REVOKED:
            reasons.append('Certificate algorithm is insecure')
        if error & Gio.TlsCertificateFlags.GENERIC_ERROR:
            reasons.append('Unknown generic error occurred')

        domain = urlparse.urlparse(failing_uri).netloc

        cert_error_path = cache_path(
            '{}/tls/error/{}'.format(self.roland.profile, domain))

        with open(cert_error_path, 'w') as f:
            f.write(certificate.props.certificate_pem)

        help = "To attempt to bypass this error, run `:bypass {}` and reload the page".format(domain)
        html = '<pre>Error going to {}: {}\n{}\n\n{}</pre>'.format(
            failing_uri, ', '.join(reasons), help, certificate_info)
        webview.load_alternate_html(html, failing_uri)

        self.title.title = 'An Error Occurred loading {}'.format(failing_uri)
        self.title.progress = 100
        self.set_title(str(self.title))
        return True

    def on_authenticate(self, webview, request):
        def ask_user():
            prompt = 'Enter username for {}:{} ({})'.format(request.get_host(), request.get_port(), request.get_realm())

            if request.is_retry():
                prompt += ' <span color="red">(retry)</span>'
            username = self.entry_line.blocking_prompt(prompt=prompt)
            if username is None:
                request.cancel()
                return None, None

            prompt = 'Enter password for {}:{} ({})'.format(request.get_host(), request.get_port(), request.get_realm())
            password = self.entry_line.blocking_prompt(
                prompt=prompt,
                private=True
            )
            if password is None:
                request.cancel()
                return None, None

            return username, password

        ext = self.roland.get_extension('PasswordManagerExtension')
        if ext is None:
            username, password = ask_user()
            if username is not None and password is not None:
                cred = WebKit2.Credential.new(
                    username, password, WebKit2.CredentialPersistence.FOR_SESSION)
                request.authenticate(cred)
            return True

        try:
            ext.unlock(self)
        except ValueError:
            self.roland.notify('Could not generate password')
        else:
            domain = ':'.join(map(str, [
                request.get_host(), request.get_port(), request.get_realm()
            ]))

            choices = ext.get_for_domain(domain.encode('utf8'))

            # FIXME: display choices prompt instead of assuming first.
            if choices and not request.is_retry():
                choice = choices[0]

                username = choice.form_data[b'username'].decode('utf8')
                password = choice.form_data[b'password'].decode('utf8')
            else:
                username, password = ask_user()

                if username is not None and password is not None:
                    ext.save_form(domain, dict(username=username, password=password))

            if username is not None and password is not None:
                cred = WebKit2.Credential.new(
                    username, password, WebKit2.CredentialPersistence.FOR_SESSION)
                request.authenticate(cred)
        return True

    def on_load_status(self, webview, load_status):
        if self.webview != webview:
            return
        if load_status == WebKit2.LoadEvent.COMMITTED:
            is_https, certificate, flags = webview.get_tls_info()

            if is_https and certificate is not None:
                self.pem_certificate = certificate.props.certificate_pem
            else:
                self.pem_certificate = None

            if is_https and (certificate is None or int(flags) != 0):
                self.status_line.set_trust(False)
            else:
                self.status_line.set_trust(True)

    def failed_to_find_text(self, finder):
        text = finder.get_search_text()
        if text is None:
            return
        self.roland.notify(
            'No match found for "{}"'.format(text))

    def on_permission_request(self, webview, permission):
        # FIXME: config hook for this.
        if isinstance(permission, WebKit2.NotificationPermissionRequest):
            permission.allow()
        else:
            # FIXME: config hook for this.
            permission.deny()
        return True

    def on_web_process_crashed(self, webview):
        self.roland.notify("Web process for {} crashed.".format(webview.get_uri()), critical=True)
        return False

    def on_resource_load_started(self, webview, resource, request):
        def finished(resource, *ignored):
            response = resource.get_response()

            if response is None:
                return
            headers = response.get_http_headers()

            if headers is None:
                return
            hsts = headers.get_one('Strict-Transport-Security')

            if hsts is not None and self.roland.is_enabled('HSTSExtension'):
                ext = self.roland.get_extension('HSTSExtension')
                ext.add_entry(response.get_uri(), hsts)

        resource.connect('finished', finished)

    def on_script_dialog(self, webview, dialog):
        if dialog.get_dialog_type() == WebKit2.ScriptDialogType.ALERT:
            self.roland.notify(dialog.get_message())
            return True
        elif dialog.get_dialog_type() == WebKit2.ScriptDialogType.PROMPT:
            result = self.entry_line.blocking_prompt(
                initial=dialog.prompt_get_default_text(),
                prompt=dialog.get_message(),
            )
            if result is not None:
                dialog.prompt_set_text(result)
            return True
        elif dialog.get_dialog_type() == WebKit2.ScriptDialogType.CONFIRM:
            result = self.entry_line.blocking_prompt(
                prompt=dialog.get_message(),
                suggestions=['ok', 'cancel'],
                force_match=True,
            )

            dialog.confirm_set_confirmed(result == 'ok')
            return True
        return False

    def update_window_icon(self, widget, event):
        icon = self.webview.get_favicon()
        if icon is not None:
            pixbuf = Gdk.pixbuf_get_from_surface(
                icon, 0, 0, icon.get_width(), icon.get_height())
            self.set_icon(pixbuf)
        else:
            self.set_icon(None)

    def mouse_target_changed(self, webview, hit_test_result, modifiers):
        if hit_test_result.context_is_link():
            p = hit_test_result.get_link_uri()
        elif hit_test_result.context_is_media():
            p = hit_test_result.get_media_uri()
        elif hit_test_result.context_is_image():
            p = hit_test_result.get_image_uri()
        else:
            p = ''

        self.status_line.set_info_text('[{}]'.format(html.escape(p)) if p else '')

    def update_title_from_event(self, widget, event):
        if event.name == 'title':
            title = self.webview.get_title()
            self.title.title = title

        elif event.name == 'estimated-load-progress':
            p = int(self.webview.get_estimated_load_progress() * 100)

            self.title.progress = p

            self.status_line.set_info_text('[{}%]'.format(p) if p < 100 else '')

        self.set_title(str(self.title))

        i = self.roland.window.notebook.get_current_page()
        page = self.roland.window.notebook.get_nth_page(i)
        if page is self:
            self.roland.window.set_title(str(self.title))

    def on_show_notification(self, webview, notification):
        notification = HTMLNotification(
            notification.get_id,
            notification.get_title(),
            notification.get_body(),
        )
        if self.roland.hooks('should_display_notification', notification, default=True):
            self.roland.notify(notification.body, header=notification.title)

    def on_create_web_view(self, webview, navigation_request):
        if self.roland.hooks('should_open_popup', navigation_request.get_request().get_uri(), default=True):
            v = self.roland.new_webview()
            self.roland.add_window(self.roland.browser_view.from_webview(v, self.roland))
            return v

    def on_key_press_event(self, widget, event):
        # keypress event will come to an unloaded window
        if self.lazy:
            self.start()

        keyname = get_keyname(event)
        if keyname in ('Shift_L', 'Shift_R'):
            return

        if self.mode in (Mode.Normal, Mode.SubCommand):
            available_commands = {
                Mode.Normal: self.roland.config.commands,
                Mode.SubCommand: self.sub_commands,
            }[self.mode]

            orig_mode = self.mode

            try:
                command = available_commands[keyname]
            except KeyError:
                pass
            else:
                log.info('running command "{}"', command)
                try:
                    return command(self)
                except Exception as e:
                    self.roland.notify("Error invoking command '{}': {}'".format(keyname, e))
                    log.exception("Error invoking command '{}'", keyname)
            finally:
                if orig_mode == Mode.SubCommand and self.mode != Mode.Prompt:
                    self.set_mode(Mode.Normal)
                    self.sub_commands = None
        elif self.mode == Mode.Prompt:
            if keyname in ('Escape', 'C-c'):
                self.set_mode(Mode.Normal)
                self.entry_line.hide_input()
                self.entry_line.fire_cancel_callback()
            elif keyname == 'Return':
                self.set_mode(Mode.Normal)
                self.entry_line.hide_input()
                try:
                    self.entry_line.fire_callback()
                except Exception as e:
                    self.roland.notify("Error invoking callback: {}'".format(e))
                    log.exception("Error invoking callback")
            elif keyname == 'ISO_Left_Tab':
                self.entry_line.completion(forward=False)
                return True
            elif keyname == 'Tab':
                self.entry_line.completion(forward=True)
                return True
            return False
        elif self.mode == Mode.PassThrough:
            # FIXME: would be great if this was configurable :/
            if keyname == 'Insert':
                self.set_mode(Mode.Normal)
        else:
            assert self.mode == Mode.Insert

            if keyname == 'Escape':
                self.set_mode(Mode.Normal)

    def set_mode(self, mode, *args):
        assert mode in Mode
        self.mode = mode

        log.info("Setting mode to {}", mode)

        if mode == Mode.Normal:
            self.webview.set_can_focus(False)
            self.set_focus(None)
            self.status_line.set_mode('<b>NORMAL</b>', name='NormalMode')
            self.status_line.set_info_text('')
        elif mode == Mode.SubCommand:
            command, self.sub_commands = args

            self.webview.set_can_focus(False)
            self.set_focus(None)
            self.status_line.set_mode('<b>COMMAND</b>', name='CommandMode')
            self.status_line.set_info_text(command)
        elif mode == Mode.Prompt:
            pass
        elif mode == Mode.PassThrough:
            self.webview.set_can_focus(True)
            self.webview.grab_focus()
            self.status_line.set_mode('<b>PASSTHROUGH</b> (press insert to return to normal mode)', name='PassThroughMode')
            self.status_line.set_info_text('')
            # stop event propagation to prevent dumping 'Insert' into webpage
            return True
        else:
            assert mode == Mode.Insert, "Unknown Mode %s" % mode
            self.webview.set_can_focus(True)
            self.webview.grab_focus()
            self.status_line.set_mode('<b>INSERT</b>', name='InsertMode')
            self.status_line.set_info_text('')
            # stop event propagation to prevent dumping 'i' into webpage
            return True

    def prompt_command(self):
        def run_command(text):
            if not text.strip():
                return
            command = list(shlex.split(text))
            command_name, args = command[0], command[1:]
            self.run_command(command_name, *args)

        self.entry_line.prompt(
            run_command, prompt='command', force_match=True,
            suggestions=self.roland.get_commands(), beginning=False)
        return True

    def run_command(self, name, *args):
        log.info('Running "{}" command', name)
        try:
            command = getattr(self, name)
        except AttributeError:
            for command in dir(BrowserCommands):
                func = getattr(self, command)
                if getattr(func, '__name__', None) == name:
                    command = func
                    break
            else:
                self.roland.notify("No such command '{}'".format(name))
                return

        try:
            command(*args)
        except Exception as e:
            self.roland.notify("Error calling '{}': {}".format(name, str(e)))
            log.exception("Error calling '{}'", name)

    def get_clipboard(self):
        clipboards = [Gdk.SELECTION_PRIMARY, Gdk.SELECTION_SECONDARY, Gdk.SELECTION_CLIPBOARD]

        for clip in clipboards:
            clip = Gtk.Clipboard.get(clip)
            if clip.wait_is_text_available():
                return clip.wait_for_text()
        return None


class MultiTabBrowserWindow(Gtk.Window):
    def __init__(self, roland, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.roland = roland
        self.notebook = Gtk.Notebook()
        self.notebook.set_show_border(False)
        # CHeck out Stack, StackSwitcher and StackSidebar
        # FIXME: allow drag and drop?
        # FIXME: middle click to close
        self.notebook.connect('switch-page', self.on_switch_page)
        self.add(self.notebook)
        self.connect('key-press-event', self.on_key_press_event)

    def on_switch_page(self, notebook, page, page_num):
        if page.lazy:
            page.start()

        for browser in self.roland.get_browsers():
            browser.tab_title.get_style_context().remove_class('active-page')

        page.tab_title.get_style_context().add_class('active-page')

        self.roland.window.set_title(page.get_title())

    def on_key_press_event(self, widget, event):
        i = self.notebook.get_current_page()
        page = self.notebook.get_nth_page(i)
        assert isinstance(page, BrowserTab), type(page)
        return page.on_key_press_event(widget, event)

    def add(self, widget):
        if widget is self.notebook:
            super().add(widget)
        else:
            assert isinstance(widget, BrowserTab), type(widget)
            tab_widget = Gtk.HBox()
            if getattr(self.roland.config, 'show_favicons', True):
                tab_widget.pack_start(widget.tab_icon, False, False, 5)
            tab_widget.pack_start(widget.tab_title, True, True, 0)
            event_box = Gtk.EventBox()
            event_box.add(tab_widget)

            def middle_click_close(_widget, event):
                if event.get_button().button == Gdk.BUTTON_MIDDLE:
                    widget.close()

            event_box.connect('button-press-event', middle_click_close)
            event_box.add_events(Gdk.EventMask.BUTTON_PRESS_MASK)
            event_box.show_all()
            self.notebook.append_page(widget, event_box)


class BrowserTab(BrowserView, Gtk.VBox):
    def __init__(self, *args, **kwargs):
        title = kwargs.pop('title', None)

        super().__init__(*args, **kwargs)

        if title:
            title = '(unloaded) {}'.format(title)

        self.tab_title = Gtk.Label()
        self.set_title(title or 'empty tab')
        self.tab_icon = Gtk.Image()
        self.tab_title.set_ellipsize(Pango.EllipsizeMode.END)
        self.tab_title.set_line_wrap(False)

        tab_width = getattr(self.roland.config, 'tab_width', 30)
        self.tab_title.set_width_chars(tab_width)
        self.tab_title.set_max_width_chars(tab_width)

    def set_title(self, text):
        self.tab_title.set_text(text)
        self.tab_title.set_tooltip_text(text)

    def get_title(self):
        title = self.tab_title.get_text()
        if self.lazy:
            title = title[len('(unloaded) '):]
        return title

    def set_icon(self, icon):
        if icon is None:
            self.tab_icon.set_from_pixbuf(None)
        else:
            size = int(16 * (getattr(self.roland.config, 'default_zoom', 100) / 100))
            self.tab_icon.set_from_pixbuf(
                icon.scale_simple(size, size, GdkPixbuf.InterpType.HYPER))

    def set_focus(self, widget):
        win = self.get_ancestor(Gtk.Window)
        if win is not None:
            win.set_focus(widget)

    def present(self):
        if self.lazy:
            self.start()
        notebook = self.roland.window.notebook
        notebook.set_current_page(notebook.page_num(self))

    def close(self):
        super().close()
        notebook = self.roland.window.notebook
        notebook.remove_page(notebook.page_num(self))
        self.destroy()


class Roland(RolandConfigBase, Gtk.Application):
    __gsignals__ = {
        'new_browser': (GObject.SIGNAL_RUN_LAST, None, (str, str, str, bool, bool, str, str)),
        'profile_set': (GObject.SIGNAL_RUN_LAST, None, (str,)),
    }

    browser_view = BrowserTab

    def __init__(self):
        Gtk.Application.__init__(
            self, application_id='deschain.roland',
            flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE)

        self.setup_run = False
        self.connect('command-line', self.on_command_line)

        self.previous_sessions = []
        self.load_config()
        self.before_run()

    def get_browsers(self):
        notebook = self.window.notebook
        return [notebook.get_nth_page(i) for i in range(notebook.get_n_pages())]

    def next_tab(self):
        notebook = self.window.notebook
        if notebook.get_current_page() + 1 == notebook.get_n_pages():
            notebook.set_current_page(0)
        else:
            self.window.notebook.next_page()

    def prev_tab(self):
        notebook = self.window.notebook
        if notebook.get_current_page() == 0:
            notebook.set_current_page(-1)
        else:
            self.window.notebook.prev_page()

    def set_tab_position(self, position='cycle'):
        """Set the position of the tab bar. Can be one of top, bottom, left or
        right. Use cycle or reverse-cycle to go through them.
        """
        notebook = self.window.notebook
        if position == 'cycle':
            pos = notebook.get_tab_pos()
            if pos == Gtk.PositionType.LEFT:
                self.set_tab_position('top')
            elif pos == Gtk.PositionType.TOP:
                self.set_tab_position('right')
            elif pos == Gtk.PositionType.RIGHT:
                self.set_tab_position('bottom')
            elif pos == Gtk.PositionType.BOTTOM:
                self.set_tab_position('left')
        elif position == 'reverse-cycle':
            pos = notebook.get_tab_pos()
            if pos == Gtk.PositionType.LEFT:
                self.set_tab_position('bottom')
            elif pos == Gtk.PositionType.BOTTOM:
                self.set_tab_position('right')
            elif pos == Gtk.PositionType.RIGHT:
                self.set_tab_position('top')
            elif pos == Gtk.PositionType.TOP:
                self.set_tab_position('left')
        elif position == 'left':
            notebook.set_tab_pos(Gtk.PositionType.LEFT)
        elif position == 'top':
            notebook.set_tab_pos(Gtk.PositionType.TOP)
        elif position == 'right':
            notebook.set_tab_pos(Gtk.PositionType.RIGHT)
        elif position == 'bottom':
            notebook.set_tab_pos(Gtk.PositionType.BOTTOM)
        elif position == 'hidden':
            notebook.set_show_tabs(False)
        elif position == 'visible':
            notebook.set_show_tabs(True)

    def new_webview(self):
        user_content_manager = self.get_extension('UserContentManager')

        if user_content_manager is not None:
            webview = WebKit2.WebView.new_with_user_content_manager(user_content_manager.manager)
        else:
            webview = WebKit2.WebView()
        return webview

    def before_run(self):
        for ext in self.extensions:
            ext.before_run()

    def find_browser(self, page_id):
        for browser in self.get_browsers():
            if browser.lazy:
                continue
            if browser.webview.get_page_id() == page_id:
                return browser

    def do_new_browser(self, uri, text, html, background, lazy, title, session):
        window = self.browser_view(self, lazy, title=title)

        if text:
            window.start('about:blank')
            window.webview.load_plain_text(text)
        elif html:
            window.start('about:blank')
            window.webview.load_html(html, uri)
        elif not lazy:
            window.start(uri, session)
        else:
            assert lazy
            window.lazy_uri = uri
            window.lazy_session = session
            window.show_all()
        self.add_window(window)

        if lazy:
            background = lazy

        if not background:
            window.present()

    def add_window(self, window):
        if isinstance(window, BrowserTab):
            self.window.add(window)
        else:
            super().add_window(window)

    def add_close_history(self, uri, session):
        if uri == 'about:blank':
            return
        self.previous_sessions.append((uri, session))

    def undo_close(self):
        try:
            previous_uri, previous_session = self.previous_sessions.pop()
        except IndexError:
            pass
        else:
            if previous_uri != 'about:blank':
                self.new_window(previous_uri, session=previous_session)

    def set_profile(self, profile):
        self.profile = profile
        self.set_application_id('{}.{}'.format('deschain.roland', profile))
        self.emit('profile-set', profile)

    def load_config(self):
        super().load_config()
        init_logging()

        if not hasattr(self.config, 'default_user_agent') or self.config.default_user_agent is None:
            self.config.default_user_agent = WebKit2.Settings().props.user_agent
        if not hasattr(self.config, 'enable_disk_cache'):
            self.config.enable_disk_cache = False

        self.browser_view = getattr(self.config, 'browser_view', self.browser_view)

        if self.config.enable_disk_cache:
            self.connect('profile-set', self.set_disk_cache)

        font = getattr(self.config, 'font', '')

        style_text = getattr(self.config, 'style', DEFAULT_STYLE)
        if not isinstance(style_text, bytes):
            style_text = style_text.encode('utf8')
        self.style_provider = Gtk.CssProvider()
        self.style_provider.load_from_data(style_text)
        Gtk.StyleContext.add_provider_for_screen(
            Gdk.Screen.get_default(), self.style_provider,
            Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)

        self.font_style_provider = Gtk.CssProvider()
        Gtk.StyleContext.add_provider_for_screen(
            Gdk.Screen.get_default(), self.font_style_provider,
            Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)

        self.change_font(font)

        context = WebKit2.WebContext.get_default()
        context.set_spell_checking_enabled(getattr(self.config, 'spell_checking_enabled', False))
        context.set_spell_checking_languages(getattr(self.config, 'spell_checking_languages', []))

        self.extensions = sorted([ext(self) for ext in self.config.extensions], key=lambda ext: ext.sort_order)

    def change_font(self, font, size="8pt"):
        if not font:
            font = "Anonymous Pro"
        if not size:
            size = "10pt"

        self.font_style_provider.load_from_data('* {{ font: {} "{}"; }}'.format(size, font).encode('utf8'))

    def set_disk_cache(self, roland, profile):
        context = WebKit2.WebContext.get_default()

        disk_cache = cache_path('{}/web/'.format(self.profile))
        try:
            os.makedirs(disk_cache)
        except FileExistsError:
            pass
        context.set_disk_cache_directory(disk_cache)

        favicon_cache = cache_path('{}/favicon/'.format(self.profile))
        try:
            os.makedirs(favicon_cache)
        except FileExistsError:
            pass
        context.set_favicon_database_directory(favicon_cache)

    def set_web_extensions_info(self, context):
        context.set_web_extensions_initialization_user_data(GLib.Variant.new_string(self.profile))
        context.set_web_extensions_directory(config_path('webextensions/'))

    def setup(self):
        if self.setup_run:
            return

        self.setup_run = True

        WebKit2.WebContext.get_default().connect('initialize-web-extensions', self.set_web_extensions_info)
        WebKit2.WebContext.get_default().set_process_model(
            WebKit2.ProcessModel.MULTIPLE_SECONDARY_PROCESSES)

        try:
            import setproctitle
            setproctitle.setproctitle('roland')
        except Exception:
            pass

        self.window = MultiTabBrowserWindow(self)
        self.set_tab_position(getattr(self.config, 'tab_bar_position', 'left'))
        self.window.show_all()
        self.add_window(self.window)

        for ext in self.extensions:
            try:
                ext.setup()
            except Exception as e:
                log.exception("Failure setting up {}: {}".format(ext.name, e))
                self.notify("Failure setting up {}: {}".format(ext.name, e), critical=True)

    def on_command_line(self, roland, command_line):
        if not command_line.get_is_remote():
            self.setup()

        s = Gtk.Settings.get_default()
        s.props.gtk_key_theme_name = 'Emacs'

        urls = command_line.get_arguments()[1:]
        if not urls:
            # if we're just loading up a new window from a remote invocation,
            # or the session was empty
            if command_line.get_is_remote() or not self.get_browsers():
                urls = [getattr(self.config, 'home_page', 'http://google.com')]

        for url in urls:
            self.new_window(url)

        return 0

    def new_window(self, url, text='', html='', background=False, lazy=False, title=None, session=None):
        self.emit('new-browser', url, text, html, background, lazy, title, session)

    def get_help(self, name):
        command = getattr(BrowserCommands, name, None)

        if command is None:
            # renamed function
            for func in dir(BrowserCommands):
                func = getattr(BrowserCommands, func)
                if getattr(func, '__name__', None) == name:
                    command = func
                    break
        help = getattr(command, '__doc__', None) or 'No help available'
        return help

    def get_commands(self):
        def name(f):
            func = getattr(BrowserCommands, f)
            return getattr(func, '__name__', f)

        def is_private(name):
            if name.startswith('__'):
                return True
            attr = getattr(BrowserCommands, name)
            return getattr(attr, 'private', False)

        def meets_requirements(f):
            func = getattr(BrowserCommands, f)
            extensions = getattr(func, 'extensions', [])
            return all(self.is_enabled(ext) for ext in extensions)

        return [name(f) for f in dir(BrowserCommands) if not is_private(f) and
                meets_requirements(f)]

    def most_popular_urls(self):
        if not self.is_enabled('HistoryManager'):
            return []
        return self.get_extension('HistoryManager').most_popular_urls()

    def hooks(self, name, *args, default=None):
        return getattr(self.config, name, lambda *args: default)(*args)

    def quit(self):
        if self.is_enabled('DownloadManager') and self.downloads:
            self.notify("Not quitting, {} downloads in progress.".format(len(self.downloads)))
            return

        Gtk.Application.quit(self)