File: webenginepreview.py

package info (click to toggle)
retext 8.1.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,780 kB
  • sloc: python: 5,363; xml: 149; makefile: 20; sh: 8
file content (247 lines) | stat: -rw-r--r-- 9,880 bytes parent folder | download
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
# vim: ts=4:sw=4:expandtab

# This file is part of ReText
# Copyright: 2017-2025 Dmitry Shachnev
#
# This program 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 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from PyQt6.QtCore import QEvent, Qt
from PyQt6.QtGui import (
    QColor,
    QCursor,
    QDesktopServices,
    QFontInfo,
    QGuiApplication,
    QPalette,
    QTextDocument,
)
from PyQt6.QtWebEngineCore import (
    QWebEnginePage,
    QWebEngineSettings,
    QWebEngineUrlRequestInfo,
    QWebEngineUrlRequestInterceptor,
)
from PyQt6.QtWebEngineWidgets import QWebEngineView
from PyQt6.QtWidgets import QApplication, QLabel

from ReText import globalCache, globalSettings
from ReText.editor import getColor
from ReText.syncscroll import SyncScroll


class ReTextWebEngineUrlRequestInterceptor(QWebEngineUrlRequestInterceptor):
    def interceptRequest(self, info):
        if (info.resourceType() == QWebEngineUrlRequestInfo.ResourceType.ResourceTypeXhr
                and info.requestUrl().isLocalFile()):
            # For security reasons, disable XMLHttpRequests to local files
            info.block(True)


def str_rgba(color: QColor):
    """ Todo: More elegant use of QColor with alpha in stylesheet """
    return f"rgba({color.red()}, {color.green()}, {color.blue()}, {color.alpha()})"

class UrlPopup(QLabel):
    def __init__(self, window):
        super().__init__(window)
        self.window = window

        self.setStyleSheet('''
            border: 1px solid {:s};
            border-radius: 3px;
            background: {:s};
            '''.format(str_rgba(getColor('urlPopupBorder')),
                       str_rgba(getColor('urlPopupArea'))))
        self.fontHeight = self.fontMetrics().height()
        self.setVisible(False)

    def pop(self, url: str):
        """ Show link target on mouse hover

        QWebEnginePage emits signal 'linkHovered' which provides
        url: str -- target of link hovered (or empty on mouse-release)
        """
        if url:
            self.setText(url)
            windowBottom = self.window.rect().bottom()
            textWidth = self.fontMetrics().horizontalAdvance(url)
            self.setGeometry(-2, windowBottom-self.fontHeight-6,
                    textWidth+10, self.fontHeight+10)
            self.setVisible(True)
        else:
            self.setVisible(False)


class ReTextWebEnginePage(QWebEnginePage):
    def __init__(self, parent, tab):
        QWebEnginePage.__init__(self, parent)
        self.tab = tab
        self.interceptor = ReTextWebEngineUrlRequestInterceptor(self)
        self.setUrlRequestInterceptor(self.interceptor)
        self.urlPopup = UrlPopup(self.tab.p)
        self.linkHovered.connect(self.urlPopup.pop)

    def setScrollPosition(self, pos):
        self.runJavaScript(f"window.scrollTo({pos.x()}, {pos.y()});")

    def getPositionMap(self, callback):
        def resultCallback(result):
            if result:
                return callback({int(a): b for a, b in result.items()})

        script = """
        var elements = document.querySelectorAll('[data-posmap]');
        var result = {};
        var bodyTop = document.body.getBoundingClientRect().top;
        for (var i = 0; i < elements.length; ++i) {
            var element = elements[i];
            value = element.getAttribute('data-posmap');
            bottom = element.getBoundingClientRect().bottom - bodyTop;
            result[value] = bottom;
        }
        result;
        """
        self.runJavaScript(script, resultCallback)

    def javaScriptConsoleMessage(self, level, message, lineNumber, sourceId):
        print(f"level={level!r} message={message!r} lineNumber={lineNumber!r} sourceId={sourceId!r}")

    def acceptNavigationRequest(self, url, type, isMainFrame):
        if not isMainFrame:
            return True
        if url.scheme() == "data":
            return True
        if url.isLocalFile():
            localFile = url.toLocalFile()
            if localFile == self.tab.fileName:
                self.tab.startPendingConversion()
                return False
            if self.tab.openSourceFile(localFile):
                return False
        if globalSettings.handleWebLinks:
            return True
        QDesktopServices.openUrl(url)
        return False


class ReTextWebEnginePreview(QWebEngineView):

    def __init__(self, tab,
                 editorPositionToSourceLineFunc,
                 sourceLineToEditorPositionFunc):

        QWebEngineView.__init__(self, parent=tab)
        webPage = ReTextWebEnginePage(self, tab)

        handCursor = QCursor(Qt.CursorShape.PointingHandCursor)
        arrowCursor = QCursor(Qt.CursorShape.ArrowCursor)
        webPage.linkHovered.connect(lambda value: self.setCursor(handCursor if value else arrowCursor))

        self.setPage(webPage)

        self.syncscroll = SyncScroll(webPage,
                                     editorPositionToSourceLineFunc,
                                     sourceLineToEditorPositionFunc)
        self.editBox = tab.editBox

        settings = self.settings()
        settings.setDefaultTextEncoding('utf-8')
        settings.setAttribute(QWebEngineSettings.WebAttribute.LocalContentCanAccessRemoteUrls, True)
        if hasattr(QWebEngineSettings.WebAttribute, 'ForceDarkMode'):  # Qt >= 6.7
            # QGuiApplication.instance().styleHints().colorScheme() does not seem to
            # work properly on KDE Plasma, so let's re-use the same approach as our
            # editor uses.
            palette = QApplication.palette()
            windowColor = palette.color(QPalette.ColorRole.Window)
            if windowColor.lightness() <= 150:
                settings.setAttribute(QWebEngineSettings.WebAttribute.ForceDarkMode, True)

        # Events relevant to sync scrolling
        self.editBox.cursorPositionChanged.connect(self._handleCursorPositionChanged)
        self.editBox.verticalScrollBar().valueChanged.connect(self.syncscroll.handleEditorScrolled)
        self.editBox.resized.connect(self._handleEditorResized)

        # Scroll the preview when the mouse wheel is used to scroll
        # beyond the beginning/end of the editor
        self.editBox.scrollLimitReached.connect(self._handleWheelEvent)

    def setFont(self, font):
        settings = self.settings()
        settings.setFontFamily(QWebEngineSettings.FontFamily.StandardFont,
                               font.family())
        settings.setFontSize(QWebEngineSettings.FontSize.DefaultFontSize,
                             QFontInfo(font).pixelSize())

    def setHtml(self, html, baseUrl):
        # A hack to prevent WebEngine from stealing the focus
        self.setEnabled(False)
        super().setHtml(html, baseUrl)
        self.setEnabled(True)

    def _handleWheelEvent(self, event):
        # Only pass wheelEvents on to the preview if syncscroll is
        # controlling the position of the preview
        if self.syncscroll.isActive():
            QGuiApplication.sendEvent(self.focusProxy(), event)

    def event(self, event):
        # Work-around https://bugreports.qt.io/browse/QTBUG-43602
        if event.type() == QEvent.Type.ChildAdded:
            event.child().installEventFilter(self)
        elif event.type() == QEvent.Type.ChildRemoved:
            event.child().removeEventFilter(self)
        return super().event(event)

    def eventFilter(self, object, event):
        if event.type() == QEvent.Type.Wheel:
            if QGuiApplication.keyboardModifiers() == Qt.KeyboardModifier.ControlModifier:
                self.wheelEvent(event)
                return True
        return False

    def findText(self, text, flags):
        options = QWebEnginePage.FindFlag(0)
        if flags & QTextDocument.FindFlag.FindBackward:
            options |= QWebEnginePage.FindFlag.FindBackward
        if flags & QTextDocument.FindFlag.FindCaseSensitively:
            options |= QWebEnginePage.FindFlag.FindCaseSensitively
        super().findText(text, options)
        return True

    def disconnectExternalSignals(self):
        self.editBox.cursorPositionChanged.disconnect(self._handleCursorPositionChanged)
        self.editBox.verticalScrollBar().valueChanged.disconnect(self.syncscroll.handleEditorScrolled)
        self.editBox.resized.disconnect(self._handleEditorResized)

        self.editBox.scrollLimitReached.disconnect(self._handleWheelEvent)

    def _handleCursorPositionChanged(self):
        editorCursorPosition = self.editBox.verticalScrollBar().value() + \
                       self.editBox.cursorRect().top()
        self.syncscroll.handleCursorPositionChanged(editorCursorPosition)

    def _handleEditorResized(self, rect):
        self.syncscroll.handleEditorResized(rect.height())

    def wheelEvent(self, event):
        if QGuiApplication.keyboardModifiers() == Qt.KeyboardModifier.ControlModifier:
            newZoomFactor = globalCache.webEngineZoomFactor * (1.001 ** event.angleDelta().y())
            # Valid values are within the range from 0.25 to 5.0.
            globalCache.webEngineZoomFactor = max(min(newZoomFactor, 5.0), 0.25)
            self.setZoomFactor(globalCache.webEngineZoomFactor)
        return super().wheelEvent(event)

    def showEvent(self, event):
        self.setZoomFactor(globalCache.webEngineZoomFactor)
        return super().showEvent(event)