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

# Copyright 2015-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 QtWebKit/QtWebEngine web inspector."""

import base64
import binascii
import enum
from typing import cast, Optional

from PyQt5.QtWidgets import QWidget
from PyQt5.QtCore import pyqtSignal, pyqtSlot, QObject, QEvent
from PyQt5.QtGui import QCloseEvent

from qutebrowser.browser import eventfilter
from qutebrowser.config import configfiles
from qutebrowser.utils import log, usertypes
from qutebrowser.keyinput import modeman
from qutebrowser.misc import miscwidgets


class Position(enum.Enum):

    """Where the inspector is shown."""

    right = enum.auto()
    left = enum.auto()
    top = enum.auto()
    bottom = enum.auto()
    window = enum.auto()


class Error(Exception):

    """Raised when the inspector could not be initialized."""


class _EventFilter(QObject):

    """Event filter to enter insert mode when inspector was clicked.

    We need to use this with a ChildEventFilter (rather than just overriding
    mousePressEvent) for two reasons:

    - For QtWebEngine, we need to listen for mouse events on its focusProxy(),
      which can change when another page loads (which might be possible with an
      inspector as well?)

    - For QtWebKit, we need to listen for mouse events on the QWebView used by
      the QWebInspector.
    """

    clicked = pyqtSignal()

    def eventFilter(self, _obj: QObject, event: QEvent) -> bool:
        """Translate mouse presses to a clicked signal."""
        if event.type() == QEvent.MouseButtonPress:
            self.clicked.emit()
        return False


class AbstractWebInspector(QWidget):

    """Base class for QtWebKit/QtWebEngine inspectors.

    Attributes:
        _position: position of the inspector (right/left/top/bottom/window)
        _splitter: InspectorSplitter where the inspector can be placed.

    Signals:
        recreate: Emitted when the inspector should be recreated.
    """

    recreate = pyqtSignal()

    def __init__(self, splitter: 'miscwidgets.InspectorSplitter',
                 win_id: int,
                 parent: QWidget = None) -> None:
        super().__init__(parent)
        self._widget = cast(QWidget, None)
        self._layout = miscwidgets.WrapperLayout(self)
        self._splitter = splitter
        self._position: Optional[Position] = None
        self._win_id = win_id

        self._event_filter = _EventFilter(parent=self)
        self._event_filter.clicked.connect(self._on_clicked)
        self._child_event_filter = eventfilter.ChildEventFilter(
            eventfilter=self._event_filter,
            parent=self)

    def _set_widget(self, widget: QWidget) -> None:
        self._widget = widget
        self._widget.setWindowTitle("Web Inspector")
        self._widget.installEventFilter(self._child_event_filter)
        self._layout.wrap(self, self._widget)

    def _load_position(self) -> Position:
        """Get the last position the inspector was in."""
        pos = configfiles.state['inspector'].get('position', 'right')
        return Position[pos]

    def _save_position(self, position: Position) -> None:
        """Save the last position the inspector was in."""
        configfiles.state['inspector']['position'] = position.name

    def _needs_recreate(self) -> bool:
        """Whether the inspector needs recreation when detaching to a window.

        This is done due to an unknown QtWebEngine bug which sometimes prevents
        inspector windows from showing up.

        Needs to be overridden by subclasses.
        """
        return False

    @pyqtSlot()
    def _on_clicked(self) -> None:
        """Enter insert mode if a docked inspector was clicked."""
        if self._position != Position.window:
            modeman.enter(self._win_id, usertypes.KeyMode.insert,
                          reason='Inspector clicked', only_if_normal=True)

    def set_position(self, position: Optional[Position]) -> None:
        """Set the position of the inspector.

        If the position is None, the last known position is used.
        """
        if position is None:
            position = self._load_position()
        else:
            self._save_position(position)

        if position == self._position:
            self.toggle()
            return

        if (position == Position.window and
                self._position is not None and
                self._needs_recreate()):
            # Detaching to window
            self.recreate.emit()
            self.shutdown()
            return
        elif position == Position.window:
            self.setParent(None)  # type: ignore[call-overload]
            self._load_state_geometry()
        else:
            self._splitter.set_inspector(self, position)

        self._position = position

        self._widget.show()
        self.show()

    def toggle(self) -> None:
        """Toggle visibility of the inspector."""
        if self.isVisible():
            self.hide()
        else:
            self.show()

    def _load_state_geometry(self) -> None:
        """Load the geometry from the state file."""
        try:
            data = configfiles.state['inspector']['window']
            geom = base64.b64decode(data, validate=True)
        except KeyError:
            # First start
            pass
        except binascii.Error:
            log.misc.exception("Error while reading geometry")
        else:
            log.init.debug("Loading geometry from {!r}".format(geom))
            ok = self._widget.restoreGeometry(geom)
            if not ok:
                log.init.warning("Error while loading geometry.")

    def closeEvent(self, _e: QCloseEvent) -> None:
        """Save the geometry when closed."""
        data = self._widget.saveGeometry().data()
        geom = base64.b64encode(data).decode('ASCII')
        configfiles.state['inspector']['window'] = geom

    def inspect(self, page: QWidget) -> None:
        """Inspect the given QWeb(Engine)Page."""
        raise NotImplementedError

    @pyqtSlot()
    def shutdown(self) -> None:
        """Clean up the inspector."""
        self.close()
        self.deleteLater()