summaryrefslogtreecommitdiff
path: root/qutebrowser/browser/browsertab.py
blob: b1827dbf4f7fcc875f9336a13852c9d3d57bf160 (plain)
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
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:

# Copyright 2016-2021 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# This file is part of qutebrowser.
#
# qutebrowser 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, either version 3 of the License, or
# (at your option) any later version.
#
# qutebrowser 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 qutebrowser.  If not, see <https://www.gnu.org/licenses/>.

"""Base class for a wrapper over QWebView/QWebEngineView."""

import enum
import itertools
import functools
import dataclasses
from typing import (cast, TYPE_CHECKING, Any, Callable, Iterable, List, Optional,
                    Sequence, Set, Type, Union)

from PyQt5.QtCore import (pyqtSignal, pyqtSlot, QUrl, QObject, QSizeF, Qt,
                          QEvent, QPoint, QRect)
from PyQt5.QtGui import QKeyEvent, QIcon, QPixmap
from PyQt5.QtWidgets import QWidget, QApplication, QDialog
from PyQt5.QtPrintSupport import QPrintDialog, QPrinter
from PyQt5.QtNetwork import QNetworkAccessManager

if TYPE_CHECKING:
    from PyQt5.QtWebKit import QWebHistory, QWebHistoryItem
    from PyQt5.QtWebKitWidgets import QWebPage
    from PyQt5.QtWebEngineWidgets import (
        QWebEngineHistory, QWebEngineHistoryItem, QWebEnginePage)

from qutebrowser.keyinput import modeman
from qutebrowser.config import config
from qutebrowser.utils import (utils, objreg, usertypes, log, qtutils,
                               urlutils, message, jinja)
from qutebrowser.misc import miscwidgets, objects, sessions
from qutebrowser.browser import eventfilter, inspector
from qutebrowser.qt import sip

if TYPE_CHECKING:
    from qutebrowser.browser import webelem
    from qutebrowser.browser.inspector import AbstractWebInspector


tab_id_gen = itertools.count(0)


def create(win_id: int,
           private: bool,
           parent: QWidget = None) -> 'AbstractTab':
    """Get a QtWebKit/QtWebEngine tab object.

    Args:
        win_id: The window ID where the tab will be shown.
        private: Whether the tab is a private/off the record tab.
        parent: The Qt parent to set.
    """
    # Importing modules here so we don't depend on QtWebEngine without the
    # argument and to avoid circular imports.
    mode_manager = modeman.instance(win_id)
    if objects.backend == usertypes.Backend.QtWebEngine:
        from qutebrowser.browser.webengine import webenginetab
        tab_class: Type[AbstractTab] = webenginetab.WebEngineTab
    elif objects.backend == usertypes.Backend.QtWebKit:
        from qutebrowser.browser.webkit import webkittab
        tab_class = webkittab.WebKitTab
    else:
        raise utils.Unreachable(objects.backend)
    return tab_class(win_id=win_id, mode_manager=mode_manager, private=private,
                     parent=parent)


class WebTabError(Exception):

    """Base class for various errors."""


class UnsupportedOperationError(WebTabError):

    """Raised when an operation is not supported with the given backend."""


class TerminationStatus(enum.Enum):

    """How a QtWebEngine renderer process terminated.

    Also see QWebEnginePage::RenderProcessTerminationStatus
    """

    #: Unknown render process status value gotten from Qt.
    unknown = -1
    #: The render process terminated normally.
    normal = 0
    #: The render process terminated with with a non-zero exit status.
    abnormal = 1
    #: The render process crashed, for example because of a segmentation fault.
    crashed = 2
    #: The render process was killed, for example by SIGKILL or task manager kill.
    killed = 3


@dataclasses.dataclass
class TabData:

    """A simple namespace with a fixed set of attributes.

    Attributes:
        keep_icon: Whether the (e.g. cloned) icon should not be cleared on page
                   load.
        inspector: The QWebInspector used for this webview.
        viewing_source: Set if we're currently showing a source view.
                        Only used when sources are shown via pygments.
        open_target: Where to open the next link.
                     Only used for QtWebKit.
        override_target: Override for open_target for fake clicks (like hints).
                         Only used for QtWebKit.
        pinned: Flag to pin the tab.
        fullscreen: Whether the tab has a video shown fullscreen currently.
        netrc_used: Whether netrc authentication was performed.
        input_mode: current input mode for the tab.
        splitter: InspectorSplitter used to show inspector inside the tab.
    """

    keep_icon: bool = False
    viewing_source: bool = False
    inspector: Optional['AbstractWebInspector'] = None
    open_target: usertypes.ClickTarget = usertypes.ClickTarget.normal
    override_target: Optional[usertypes.ClickTarget] = None
    pinned: bool = False
    fullscreen: bool = False
    netrc_used: bool = False
    input_mode: usertypes.KeyMode = usertypes.KeyMode.normal
    last_navigation: Optional[usertypes.NavigationRequest] = None
    splitter: Optional[miscwidgets.InspectorSplitter] = None

    def should_show_icon(self) -> bool:
        return (config.val.tabs.favicons.show == 'always' or
                config.val.tabs.favicons.show == 'pinned' and self.pinned)


class AbstractAction:

    """Attribute ``action`` of AbstractTab for Qt WebActions."""

    action_class: Type[Union['QWebPage', 'QWebEnginePage']]
    action_base: Type[Union['QWebPage.WebAction', 'QWebEnginePage.WebAction']]

    def __init__(self, tab: 'AbstractTab') -> None:
        self._widget = cast(QWidget, None)
        self._tab = tab

    def exit_fullscreen(self) -> None:
        """Exit the fullscreen mode."""
        raise NotImplementedError

    def save_page(self) -> None:
        """Save the current page."""
        raise NotImplementedError

    def run_string(self, name: str) -> None:
        """Run a webaction based on its name."""
        member = getattr(self.action_class, name, None)
        if not isinstance(member, self.action_base):
            raise WebTabError("{} is not a valid web action!".format(name))
        self._widget.triggerPageAction(member)

    def show_source(self, pygments: bool = False) -> None:
        """Show the source of the current page in a new tab."""
        raise NotImplementedError

    def _show_html_source(self, html: str) -> None:
        """Show the given HTML as source page."""
        tb = objreg.get('tabbed-browser', scope='window', window=self._tab.win_id)
        new_tab = tb.tabopen(background=False, related=True)
        new_tab.set_html(html, self._tab.url())
        new_tab.data.viewing_source = True

    def _show_source_fallback(self, source: str) -> None:
        """Show source with pygments unavailable."""
        html = jinja.render(
            'pre.html',
            title='Source',
            content=source,
            preamble="Note: The optional Pygments dependency wasn't found - "
            "showing unhighlighted source.",
        )
        self._show_html_source(html)

    def _show_source_pygments(self) -> None:

        def show_source_cb(source: str) -> None:
            """Show source as soon as it's ready."""
            try:
                import pygments
                import pygments.lexers
                import pygments.formatters
            except ImportError:
                # Pygments is an optional dependency
                self._show_source_fallback(source)
                return

            try:
                lexer = pygments.lexers.HtmlLexer()
                formatter = pygments.formatters.HtmlFormatter(
                    full=True, linenos='table')
            except AttributeError:
                # Remaining namespace package from Pygments
                self._show_source_fallback(source)
                return

            html = pygments.highlight(source, lexer, formatter)
            self._show_html_source(html)

        self._tab.dump_async(show_source_cb)


class AbstractPrinting:

    """Attribute ``printing`` of AbstractTab for printing the page."""

    def __init__(self, tab: 'AbstractTab') -> None:
        self._widget = cast(QWidget, None)
        self._tab = tab

    def check_pdf_support(self) -> None:
        """Check whether writing to PDFs is supported.

        If it's not supported (by the current Qt version), a WebTabError is
        raised.
        """
        raise NotImplementedError

    def check_preview_support(self) -> None:
        """Check whether showing a print preview is supported.

        If it's not supported (by the current Qt version), a WebTabError is
        raised.
        """
        raise NotImplementedError

    def to_pdf(self, filename: str) -> bool:
        """Print the tab to a PDF with the given filename."""
        raise NotImplementedError

    def to_printer(self, printer: QPrinter,
                   callback: Callable[[bool], None] = None) -> None:
        """Print the tab.

        Args:
            printer: The QPrinter to print to.
            callback: Called with a boolean
                      (True if printing succeeded, False otherwise)
        """
        raise NotImplementedError

    def show_dialog(self) -> None:
        """Print with a QPrintDialog."""
        def print_callback(ok: bool) -> None:
            """Called when printing finished."""
            if not ok:
                message.error("Printing failed!")
            diag.deleteLater()

        def do_print() -> None:
            """Called when the dialog was closed."""
            self.to_printer(diag.printer(), print_callback)

        diag = QPrintDialog(self._tab)
        if utils.is_mac:
            # For some reason we get a segfault when using open() on macOS
            ret = diag.exec()
            if ret == QDialog.Accepted:
                do_print()
        else:
            diag.open(do_print)


class AbstractSearch(QObject):

    """Attribute ``search`` of AbstractTab for doing searches.

    Attributes:
        text: The last thing this view was searched for.
        search_displayed: Whether we're currently displaying search results in
                          this view.
        _flags: The flags of the last search (needs to be set by subclasses).
        _widget: The underlying WebView widget.
    """

    #: Signal emitted when a search was finished
    #: (True if the text was found, False otherwise)
    finished = pyqtSignal(bool)
    #: Signal emitted when an existing search was cleared.
    cleared = pyqtSignal()

    _Callback = Callable[[bool], None]

    def __init__(self, tab: 'AbstractTab', parent: QWidget = None):
        super().__init__(parent)
        self._tab = tab
        self._widget = cast(QWidget, None)
        self.text: Optional[str] = None
        self.search_displayed = False

    def _is_case_sensitive(self, ignore_case: usertypes.IgnoreCase) -> bool:
        """Check if case-sensitivity should be used.

        This assumes self.text is already set properly.

        Arguments:
            ignore_case: The ignore_case value from the config.
        """
        assert self.text is not None
        mapping = {
            usertypes.IgnoreCase.smart: not self.text.islower(),
            usertypes.IgnoreCase.never: True,
            usertypes.IgnoreCase.always: False,
        }
        return mapping[ignore_case]

    def search(self, text: str, *,
               ignore_case: usertypes.IgnoreCase = usertypes.IgnoreCase.never,
               reverse: bool = False,
               wrap: bool = True,
               result_cb: _Callback = None) -> None:
        """Find the given text on the page.

        Args:
            text: The text to search for.
            ignore_case: Search case-insensitively.
            reverse: Reverse search direction.
            wrap: Allow wrapping at the top or bottom of the page.
            result_cb: Called with a bool indicating whether a match was found.
        """
        raise NotImplementedError

    def clear(self) -> None:
        """Clear the current search."""
        raise NotImplementedError

    def prev_result(self, *, result_cb: _Callback = None) -> None:
        """Go to the previous result of the current search.

        Args:
            result_cb: Called with a bool indicating whether a match was found.
        """
        raise NotImplementedError

    def next_result(self, *, result_cb: _Callback = None) -> None:
        """Go to the next result of the current search.

        Args:
            result_cb: Called with a bool indicating whether a match was found.
        """
        raise NotImplementedError


class AbstractZoom(QObject):

    """Attribute ``zoom`` of AbstractTab for controlling zoom."""

    def __init__(self, tab: 'AbstractTab', parent: QWidget = None) -> None:
        super().__init__(parent)
        self._tab = tab
        self._widget = cast(QWidget, None)
        # Whether zoom was changed from the default.
        self._default_zoom_changed = False
        self._init_neighborlist()
        config.instance.changed.connect(self._on_config_changed)
        self._zoom_factor = float(config.val.zoom.default) / 100

    @pyqtSlot(str)
    def _on_config_changed(self, option: str) -> None:
        if option in ['zoom.levels', 'zoom.default']:
            if not self._default_zoom_changed:
                factor = float(config.val.zoom.default) / 100
                self.set_factor(factor)
            self._init_neighborlist()

    def _init_neighborlist(self) -> None:
        """Initialize self._neighborlist.

        It is a NeighborList with the zoom levels."""
        levels = config.val.zoom.levels
        self._neighborlist: usertypes.NeighborList[float] = usertypes.NeighborList(
            levels, mode=usertypes.NeighborList.Modes.edge)
        self._neighborlist.fuzzyval = config.val.zoom.default

    def apply_offset(self, offset: int) -> float:
        """Increase/Decrease the zoom level by the given offset.

        Args:
            offset: The offset in the zoom level list.

        Return:
            The new zoom level.
        """
        level = self._neighborlist.getitem(offset)
        self.set_factor(float(level) / 100, fuzzyval=False)
        return level

    def _set_factor_internal(self, factor: float) -> None:
        raise NotImplementedError

    def set_factor(self, factor: float, *, fuzzyval: bool = True) -> None:
        """Zoom to a given zoom factor.

        Args:
            factor: The zoom factor as float.
            fuzzyval: Whether to set the NeighborLists fuzzyval.
        """
        if fuzzyval:
            self._neighborlist.fuzzyval = int(factor * 100)
        if factor < 0:
            raise ValueError("Can't zoom to factor {}!".format(factor))

        default_zoom_factor = float(config.val.zoom.default) / 100
        self._default_zoom_changed = (factor != default_zoom_factor)

        self._zoom_factor = factor
        self._set_factor_internal(factor)

    def factor(self) -> float:
        return self._zoom_factor

    def apply_default(self) -> None:
        self._set_factor_internal(float(config.val.zoom.default) / 100)

    def reapply(self) -> None:
        self._set_factor_internal(self._zoom_factor)


class SelectionState(enum.Enum):

    """Possible states of selection in caret mode.

    NOTE: Names need to line up with SelectionState in caret.js!
    """

    none = enum.auto()
    normal = enum.auto()
    line = enum.auto()


class AbstractCaret(QObject):

    """Attribute ``caret`` of AbstractTab for caret browsing."""

    #: Signal emitted when the selection was toggled.
    selection_toggled = pyqtSignal(SelectionState)
    #: Emitted when a ``follow_selection`` action is done.
    follow_selected_done = pyqtSignal()

    def __init__(self,
                 tab: 'AbstractTab',
                 mode_manager: modeman.ModeManager,
                 parent: QWidget = None) -> None:
        super().__init__(parent)
        self._widget = cast(QWidget, None)
        self._mode_manager = mode_manager
        mode_manager.entered.connect(self._on_mode_entered)
        mode_manager.left.connect(self._on_mode_left)
        self._tab = tab

    def _on_mode_entered(self, mode: usertypes.KeyMode) -> None:
        raise NotImplementedError

    def _on_mode_left(self, mode: usertypes.KeyMode) -> None:
        raise NotImplementedError

    def move_to_next_line(self, count: int = 1) -> None:
        raise NotImplementedError

    def move_to_prev_line(self, count: int = 1) -> None:
        raise NotImplementedError

    def move_to_next_char(self, count: int = 1) -> None:
        raise NotImplementedError

    def move_to_prev_char(self, count: int = 1) -> None:
        raise NotImplementedError

    def move_to_end_of_word(self, count: int = 1) -> None:
        raise NotImplementedError

    def move_to_next_word(self, count: int = 1) -> None:
        raise NotImplementedError

    def move_to_prev_word(self, count: int = 1) -> None:
        raise NotImplementedError

    def move_to_start_of_line(self) -> None:
        raise NotImplementedError

    def move_to_end_of_line(self) -> None:
        raise NotImplementedError

    def move_to_start_of_next_block(self, count: int = 1) -> None:
        raise NotImplementedError

    def move_to_start_of_prev_block(self, count: int = 1) -> None:
        raise NotImplementedError

    def move_to_end_of_next_block(self, count: int = 1) -> None:
        raise NotImplementedError

    def move_to_end_of_prev_block(self, count: int = 1) -> None:
        raise NotImplementedError

    def move_to_start_of_document(self) -> None:
        raise NotImplementedError

    def move_to_end_of_document(self) -> None:
        raise NotImplementedError

    def toggle_selection(self, line: bool = False) -> None:
        raise NotImplementedError

    def drop_selection(self) -> None:
        raise NotImplementedError

    def selection(self, callback: Callable[[str], None]) -> None:
        raise NotImplementedError

    def reverse_selection(self) -> None:
        raise NotImplementedError

    def _follow_enter(self, tab: bool) -> None:
        """Follow a link by faking an enter press."""
        if tab:
            self._tab.fake_key_press(Qt.Key_Enter, modifier=Qt.ControlModifier)
        else:
            self._tab.fake_key_press(Qt.Key_Enter)

    def follow_selected(self, *, tab: bool = False) -> None:
        raise NotImplementedError


class AbstractScroller(QObject):

    """Attribute ``scroller`` of AbstractTab to manage scroll position."""

    #: Signal emitted when the scroll position changed (int, int)
    perc_changed = pyqtSignal(int, int)
    #: Signal emitted before the user requested a jump.
    #: Used to set the special ' mark so the user can return.
    before_jump_requested = pyqtSignal()

    def __init__(self, tab: 'AbstractTab', parent: QWidget = None):
        super().__init__(parent)
        self._tab = tab
        self._widget = cast(QWidget, None)
        if 'log-scroll-pos' in objects.debug_flags:
            self.perc_changed.connect(self._log_scroll_pos_change)

    @pyqtSlot()
    def _log_scroll_pos_change(self) -> None:
        log.webview.vdebug(  # type: ignore[attr-defined]
            "Scroll position changed to {}".format(self.pos_px()))

    def _init_widget(self, widget: QWidget) -> None:
        self._widget = widget

    def pos_px(self) -> int:
        raise NotImplementedError

    def pos_perc(self) -> int:
        raise NotImplementedError

    def to_perc(self, x: int = None, y: int = None) -> None:
        raise NotImplementedError

    def to_point(self, point: QPoint) -> None:
        raise NotImplementedError

    def to_anchor(self, name: str) -> None:
        raise NotImplementedError

    def delta(self, x: int = 0, y: int = 0) -> None:
        raise NotImplementedError

    def delta_page(self, x: float = 0, y: float = 0) -> None:
        raise NotImplementedError

    def up(self, count: int = 1) -> None:
        raise NotImplementedError

    def down(self, count: int = 1) -> None:
        raise NotImplementedError

    def left(self, count: int = 1) -> None:
        raise NotImplementedError

    def right(self, count: int = 1) -> None:
        raise NotImplementedError

    def top(self) -> None:
        raise NotImplementedError

    def bottom(self) -> None:
        raise NotImplementedError

    def page_up(self, count: int = 1) -> None:
        raise NotImplementedError

    def page_down(self, count: int = 1) -> None:
        raise NotImplementedError

    def at_top(self) -> bool:
        raise NotImplementedError

    def at_bottom(self) -> bool:
        raise NotImplementedError


class AbstractHistoryPrivate:

    """Private API related to the history."""

    def serialize(self) -> bytes:
        """Serialize into an opaque format understood by self.deserialize."""
        raise NotImplementedError

    def deserialize(self, data: bytes) -> None:
        """Deserialize from a format produced by self.serialize."""
        raise NotImplementedError

    def load_items(self, items: Sequence[sessions.TabHistoryItem]) -> None:
        """Deserialize from a list of TabHistoryItems."""
        raise NotImplementedError


class AbstractHistory:

    """The history attribute of a AbstractTab."""

    def __init__(self, tab: 'AbstractTab') -> None:
        self._tab = tab
        self._history = cast(Union['QWebHistory', 'QWebEngineHistory'], None)
        self.private_api = AbstractHistoryPrivate()

    def __len__(self) -> int:
        raise NotImplementedError

    def __iter__(self) -> Iterable[Union['QWebHistoryItem', 'QWebEngineHistoryItem']]:
        raise NotImplementedError

    def _check_count(self, count: int) -> None:
        """Check whether the count is positive."""
        if count < 0:
            raise WebTabError("count needs to be positive!")

    def current_idx(self) -> int:
        raise NotImplementedError

    def back(self, count: int = 1) -> None:
        """Go back in the tab's history."""
        self._check_count(count)
        idx = self.current_idx() - count
        if idx >= 0:
            self._go_to_item(self._item_at(idx))
        else:
            self._go_to_item(self._item_at(0))
            raise WebTabError("At beginning of history.")

    def forward(self, count: int = 1) -> None:
        """Go forward in the tab's history."""
        self._check_count(count)
        idx = self.current_idx() + count
        if idx < len(self):
            self._go_to_item(self._item_at(idx))
        else:
            self._go_to_item(self._item_at(len(self) - 1))
            raise WebTabError("At end of history.")

    def can_go_back(self) -> bool:
        raise NotImplementedError

    def can_go_forward(self) -> bool:
        raise NotImplementedError

    def _item_at(self, i: int) -> Any:
        raise NotImplementedError

    def _go_to_item(self, item: Any) -> None:
        raise NotImplementedError

    def back_items(self) -> List[Any]:
        raise NotImplementedError

    def forward_items(self) -> List[Any]:
        raise NotImplementedError


class AbstractElements:

    """Finding and handling of elements on the page."""

    _MultiCallback = Callable[[Sequence['webelem.AbstractWebElement']], None]
    _SingleCallback = Callable[[Optional['webelem.AbstractWebElement']], None]
    _ErrorCallback = Callable[[Exception], None]

    def __init__(self, tab: 'AbstractTab') -> None:
        self._widget = cast(QWidget, None)
        self._tab = tab

    def find_css(self, selector: str,
                 callback: _MultiCallback,
                 error_cb: _ErrorCallback, *,
                 only_visible: bool = False) -> None:
        """Find all HTML elements matching a given selector async.

        If there's an error, the callback is called with a webelem.Error
        instance.

        Args:
            callback: The callback to be called when the search finished.
            error_cb: The callback to be called when an error occurred.
            selector: The CSS selector to search for.
            only_visible: Only show elements which are visible on screen.
        """
        raise NotImplementedError

    def find_id(self, elem_id: str, callback: _SingleCallback) -> None:
        """Find the HTML element with the given ID async.

        Args:
            callback: The callback to be called when the search finished.
                      Called with a WebEngineElement or None.
            elem_id: The ID to search for.
        """
        raise NotImplementedError

    def find_focused(self, callback: _SingleCallback) -> None:
        """Find the focused element on the page async.

        Args:
            callback: The callback to be called when the search finished.
                      Called with a WebEngineElement or None.
        """
        raise NotImplementedError

    def find_at_pos(self, pos: QPoint, callback: _SingleCallback) -> None:
        """Find the element at the given position async.

        This is also called "hit test" elsewhere.

        Args:
            pos: The QPoint to get the element for.
            callback: The callback to be called when the search finished.
                      Called with a WebEngineElement or None.
        """
        raise NotImplementedError


class AbstractAudio(QObject):

    """Handling of audio/muting for this tab."""

    muted_changed = pyqtSignal(bool)
    recently_audible_changed = pyqtSignal(bool)

    def __init__(self, tab: 'AbstractTab', parent: QWidget = None) -> None:
        super().__init__(parent)
        self._widget = cast(QWidget, None)
        self._tab = tab

    def set_muted(self, muted: bool, override: bool = False) -> None:
        """Set this tab as muted or not.

        Arguments:
            override: If set to True, muting/unmuting was done manually and
                      overrides future automatic mute/unmute changes based on
                      the URL.
        """
        raise NotImplementedError

    def is_muted(self) -> bool:
        raise NotImplementedError

    def is_recently_audible(self) -> bool:
        """Whether this tab has had audio playing recently."""
        raise NotImplementedError


class AbstractTabPrivate:

    """Tab-related methods which are only needed in the core.

    Those methods are not part of the API which is exposed to extensions, and
    should ideally be removed at some point in the future.
    """

    def __init__(self, mode_manager: modeman.ModeManager,
                 tab: 'AbstractTab') -> None:
        self._widget = cast(QWidget, None)
        self._tab = tab
        self._mode_manager = mode_manager

    def event_target(self) -> QWidget:
        """Return the widget events should be sent to."""
        raise NotImplementedError

    def handle_auto_insert_mode(self, ok: bool) -> None:
        """Handle `input.insert_mode.auto_load` after loading finished."""
        if not ok or not config.cache['input.insert_mode.auto_load']:
            return

        cur_mode = self._mode_manager.mode
        if cur_mode == usertypes.KeyMode.insert:
            return

        def _auto_insert_mode_cb(
                elem: Optional['webelem.AbstractWebElement']
        ) -> None:
            """Called from JS after finding the focused element."""
            if elem is None:
                log.webview.debug("No focused element!")
                return
            if elem.is_editable():
                modeman.enter(self._tab.win_id, usertypes.KeyMode.insert,
                              'load finished', only_if_normal=True)

        self._tab.elements.find_focused(_auto_insert_mode_cb)

    def clear_ssl_errors(self) -> None:
        raise NotImplementedError

    def networkaccessmanager(self) -> Optional[QNetworkAccessManager]:
        """Get the QNetworkAccessManager for this tab.

        This is only implemented for QtWebKit.
        For QtWebEngine, always returns None.
        """
        raise NotImplementedError

    def shutdown(self) -> None:
        raise NotImplementedError

    def run_js_sync(self, code: str) -> None:
        """Run javascript sync.

        Result will be returned when running JS is complete.
        This is only implemented for QtWebKit.
        For QtWebEngine, always raises UnsupportedOperationError.
        """
        raise NotImplementedError

    def _recreate_inspector(self) -> None:
        """Recreate the inspector when detached to a window.

        This is needed to circumvent a QtWebEngine bug (which wasn't
        investigated further) which sometimes results in the window not
        appearing anymore.
        """
        self._tab.data.inspector = None
        self.toggle_inspector(inspector.Position.window)

    def toggle_inspector(self, position: inspector.Position) -> None:
        """Show/hide (and if needed, create) the web inspector for this tab."""
        tabdata = self._tab.data
        if tabdata.inspector is None:
            assert tabdata.splitter is not None
            tabdata.inspector = self._init_inspector(
                splitter=tabdata.splitter,
                win_id=self._tab.win_id)
            self._tab.shutting_down.connect(tabdata.inspector.shutdown)
            tabdata.inspector.recreate.connect(self._recreate_inspector)
            tabdata.inspector.inspect(self._widget.page())
        tabdata.inspector.set_position(position)

    def _init_inspector(self, splitter: 'miscwidgets.InspectorSplitter',
           win_id: int,
           parent: QWidget = None) -> 'AbstractWebInspector':
        """Get a WebKitInspector/WebEngineInspector.

        Args:
            splitter: InspectorSplitter where the inspector can be placed.
            win_id: The window ID this inspector is associated with.
            parent: The Qt parent to set.
        """
        raise NotImplementedError


class AbstractTab(QWidget):

    """An adapter for QWebView/QWebEngineView representing a single tab."""

    #: Signal emitted when a website requests to close this tab.
    window_close_requested = pyqtSignal()
    #: Signal emitted when a link is hovered (the hover text)
    link_hovered = pyqtSignal(str)
    #: Signal emitted when a page started loading
    load_started = pyqtSignal()
    #: Signal emitted when a page is loading (progress percentage)
    load_progress = pyqtSignal(int)
    #: Signal emitted when a page finished loading (success as bool)
    load_finished = pyqtSignal(bool)
    #: Signal emitted when a page's favicon changed (icon as QIcon)
    icon_changed = pyqtSignal(QIcon)
    #: Signal emitted when a page's title changed (new title as str)
    title_changed = pyqtSignal(str)
    #: Signal emitted when this tab was pinned/unpinned (new pinned state as bool)
    pinned_changed = pyqtSignal(bool)
    #: Signal emitted when a new tab should be opened (url as QUrl)
    new_tab_requested = pyqtSignal(QUrl)
    #: Signal emitted when a page's URL changed (url as QUrl)
    url_changed = pyqtSignal(QUrl)
    #: Signal emitted when a tab's content size changed
    #: (new size as QSizeF)
    contents_size_changed = pyqtSignal(QSizeF)
    #: Signal emitted when a page requested full-screen (bool)
    fullscreen_requested = pyqtSignal(bool)
    #: Signal emitted before load starts (URL as QUrl)
    before_load_started = pyqtSignal(QUrl)

    # Signal emitted when a page's load status changed
    # (argument: usertypes.LoadStatus)
    load_status_changed = pyqtSignal(usertypes.LoadStatus)
    # Signal emitted before shutting down
    shutting_down = pyqtSignal()
    # Signal emitted when a history item should be added
    history_item_triggered = pyqtSignal(QUrl, QUrl, str)
    # Signal emitted when the underlying renderer process terminated.
    # arg 0: A TerminationStatus member.
    # arg 1: The exit code.
    renderer_process_terminated = pyqtSignal(TerminationStatus, int)

    # Hosts for which a certificate error happened. Shared between all tabs.
    #
    # Note that we remember hosts here, without scheme/port:
    # QtWebEngine/Chromium also only remembers hostnames, and certificates are
    # for a given hostname anyways.
    _insecure_hosts: Set[str] = set()

    def __init__(self, *, win_id: int,
                 mode_manager: 'modeman.ModeManager',
                 private: bool,
                 parent: QWidget = None) -> None:
        utils.unused(mode_manager)  # needed for mypy
        self.is_private = private
        self.win_id = win_id
        self.tab_id = next(tab_id_gen)
        super().__init__(parent)

        self.registry = objreg.ObjectRegistry()
        tab_registry = objreg.get('tab-registry', scope='window',
                                  window=win_id)
        tab_registry[self.tab_id] = self
        objreg.register('tab', self, registry=self.registry)

        self.data = TabData()
        self._layout = miscwidgets.WrapperLayout(self)
        self._widget = cast(QWidget, None)
        self._progress = 0
        self._load_status = usertypes.LoadStatus.none
        self._tab_event_filter = eventfilter.TabEventFilter(
            self, parent=self)
        self.backend: Optional[usertypes.Backend] = None

        # If true, this tab has been requested to be removed (or is removed).
        self.pending_removal = False
        self.shutting_down.connect(functools.partial(
            setattr, self, 'pending_removal', True))

        self.before_load_started.connect(self._on_before_load_started)

    def _set_widget(self, widget: QWidget) -> None:
        # pylint: disable=protected-access
        self._widget = widget
        self.data.splitter = miscwidgets.InspectorSplitter(
            win_id=self.win_id, main_webview=widget)
        self._layout.wrap(self, self.data.splitter)
        self.history._history = widget.history()
        self.history.private_api._history = widget.history()
        self.scroller._init_widget(widget)
        self.caret._widget = widget
        self.zoom._widget = widget
        self.search._widget = widget
        self.printing._widget = widget
        self.action._widget = widget
        self.elements._widget = widget
        self.audio._widget = widget
        self.private_api._widget = widget
        self.settings._settings = widget.settings()

        self._install_event_filter()
        self.zoom.apply_default()

    def _install_event_filter(self) -> None:
        raise NotImplementedError

    def _set_load_status(self, val: usertypes.LoadStatus) -> None:
        """Setter for load_status."""
        if not isinstance(val, usertypes.LoadStatus):
            raise TypeError("Type {} is no LoadStatus member!".format(val))
        log.webview.debug("load status for {}: {}".format(repr(self), val))
        self._load_status = val
        self.load_status_changed.emit(val)

    def send_event(self, evt: QEvent) -> None:
        """Send the given event to the underlying widget.

        The event will be sent via QApplication.postEvent.
        Note that a posted event must not be re-used in any way!
        """
        # This only gives us some mild protection against re-using events, but
        # it's certainly better than a segfault.
        if getattr(evt, 'posted', False):
            raise utils.Unreachable("Can't re-use an event which was already "
                                    "posted!")

        recipient = self.private_api.event_target()
        if recipient is None:
            # https://github.com/qutebrowser/qutebrowser/issues/3888
            log.webview.warning("Unable to find event target!")
            return

        evt.posted = True  # type: ignore[attr-defined]
        QApplication.postEvent(recipient, evt)

    def navigation_blocked(self) -> bool:
        """Test if navigation is allowed on the current tab."""
        return self.data.pinned and config.val.tabs.pinned.frozen

    @pyqtSlot(QUrl)
    def _on_before_load_started(self, url: QUrl) -> None:
        """Adjust the title if we are going to visit a URL soon."""
        qtutils.ensure_valid(url)
        url_string = url.toDisplayString()
        log.webview.debug("Going to start loading: {}".format(url_string))
        self.title_changed.emit(url_string)

    @pyqtSlot(QUrl)
    def _on_url_changed(self, url: QUrl) -> None:
        """Update title when URL has changed and no title is available."""
        if url.isValid() and not self.title():
            self.title_changed.emit(url.toDisplayString())
        self.url_changed.emit(url)

    @pyqtSlot()
    def _on_load_started(self) -> None:
        self._progress = 0
        self.data.viewing_source = False
        self._set_load_status(usertypes.LoadStatus.loading)
        self.load_started.emit()

    @pyqtSlot(usertypes.NavigationRequest)
    def _on_navigation_request(
            self,
            navigation: usertypes.NavigationRequest
    ) -> None:
        """Handle common acceptNavigationRequest code."""
        url = utils.elide(navigation.url.toDisplayString(), 100)
        log.webview.debug("navigation request: url {}, type {}, is_main_frame "
                          "{}".format(url,
                                      navigation.navigation_type,
                                      navigation.is_main_frame))

        if navigation.is_main_frame:
            self.data.last_navigation = navigation

        if not navigation.url.isValid():
            if navigation.navigation_type == navigation.Type.link_clicked:
                msg = urlutils.get_errstring(navigation.url,
                                             "Invalid link clicked")
                message.error(msg)
                self.data.open_target = usertypes.ClickTarget.normal

            log.webview.debug("Ignoring invalid URL {} in "
                              "acceptNavigationRequest: {}".format(
                                  navigation.url.toDisplayString(),
                                  navigation.url.errorString()))
            navigation.accepted = False

    @pyqtSlot(bool)
    def _on_load_finished(self, ok: bool) -> None:
        assert self._widget is not None
        if sip.isdeleted(self._widget):
            # https://github.com/qutebrowser/qutebrowser/issues/3498
            return

        if sessions.session_manager is not None:
            sessions.session_manager.save_autosave()

        self.load_finished.emit(ok)

        if not self.title():
            self.title_changed.emit(self.url().toDisplayString())

        self.zoom.reapply()

    def _update_load_status(self, ok: bool) -> None:
        """Update the load status after a page finished loading.

        Needs to be called by subclasses to trigger a load status update, e.g.
        as a response to a loadFinished signal.
        """
        url = self.url()
        is_https = url.scheme() == 'https'

        if not ok:
            loadstatus = usertypes.LoadStatus.error
        elif is_https and url.host() in self._insecure_hosts:
            loadstatus = usertypes.LoadStatus.warn
        elif is_https:
            loadstatus = usertypes.LoadStatus.success_https
        else:
            loadstatus = usertypes.LoadStatus.success

        self._set_load_status(loadstatus)

    @pyqtSlot()
    def _on_history_trigger(self) -> None:
        """Emit history_item_triggered based on backend-specific signal."""
        raise NotImplementedError

    @pyqtSlot(int)
    def _on_load_progress(self, perc: int) -> None:
        self._progress = perc
        self.load_progress.emit(perc)

    def url(self, *, requested: bool = False) -> QUrl:
        raise NotImplementedError

    def progress(self) -> int:
        return self._progress

    def load_status(self) -> usertypes.LoadStatus:
        return self._load_status

    def _load_url_prepare(self, url: QUrl) -> None:
        qtutils.ensure_valid(url)
        self.before_load_started.emit(url)

    def load_url(self, url: QUrl) -> None:
        raise NotImplementedError

    def reload(self, *, force: bool = False) -> None:
        raise NotImplementedError

    def stop(self) -> None:
        raise NotImplementedError

    def fake_key_press(self,
                       key: Qt.Key,
                       modifier: Qt.KeyboardModifier = Qt.NoModifier) -> None:
        """Send a fake key event to this tab."""
        press_evt = QKeyEvent(QEvent.KeyPress, key, modifier, 0, 0, 0)
        release_evt = QKeyEvent(QEvent.KeyRelease, key, modifier,
                                0, 0, 0)
        self.send_event(press_evt)
        self.send_event(release_evt)

    def dump_async(self,
                   callback: Callable[[str], None], *,
                   plain: bool = False) -> None:
        """Dump the current page's html asynchronously.

        The given callback will be called with the result when dumping is
        complete.
        """
        raise NotImplementedError

    def run_js_async(
            self,
            code: str,
            callback: Callable[[Any], None] = None, *,
            world: Union[usertypes.JsWorld, int] = None
    ) -> None:
        """Run javascript async.

        The given callback will be called with the result when running JS is
        complete.

        Args:
            code: The javascript code to run.
            callback: The callback to call with the result, or None.
            world: A world ID (int or usertypes.JsWorld member) to run the JS
                   in the main world or in another isolated world.
        """
        raise NotImplementedError

    def title(self) -> str:
        raise NotImplementedError

    def icon(self) -> None:
        raise NotImplementedError

    def set_html(self, html: str, base_url: QUrl = QUrl()) -> None:
        raise NotImplementedError

    def set_pinned(self, pinned: bool) -> None:
        self.data.pinned = pinned
        self.pinned_changed.emit(pinned)

    def renderer_process_pid(self) -> Optional[int]:
        """Get the PID of the underlying renderer process.

        Returns None if the PID can't be determined or if getting the PID isn't
        supported.
        """
        raise NotImplementedError

    def grab_pixmap(self, rect: QRect = None) -> Optional[QPixmap]:
        """Grab a QPixmap of the displayed page.

        Returns None if we got a null pixmap from Qt.
        """
        if rect is None:
            pic = self._widget.grab()
        else:
            qtutils.ensure_valid(rect)
            pic = self._widget.grab(rect)

        if pic.isNull():
            return None

        return pic

    def __repr__(self) -> str:
        try:
            qurl = self.url()
            url = qurl.toDisplayString(
                QUrl.EncodeUnicode)  # type: ignore[arg-type]
        except (AttributeError, RuntimeError) as exc:
            url = '<{}>'.format(exc.__class__.__name__)
        else:
            url = utils.elide(url, 100)
        return utils.get_repr(self, tab_id=self.tab_id, url=url)

    def is_deleted(self) -> bool:
        assert self._widget is not None
        return sip.isdeleted(self._widget)