File: magnifier.py

package info (click to toggle)
python-qpageview 1.0.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 788 kB
  • sloc: python: 5,125; makefile: 22
file content (321 lines) | stat: -rw-r--r-- 11,757 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
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
# -*- coding: utf-8 -*-
#
# This file is part of the qpageview package.
#
# Copyright (c) 2010 - 2019 by Wilbert Berendsen
#
# 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 3
# 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, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
# See http://www.gnu.org/licenses/ for more information.


"""
The Magnifier magnifies a part of the displayed document.
"""

from PyQt6.QtCore import QEvent, QPoint, QRect, Qt
from PyQt6.QtGui import (
    QColor, QCursor, QPainter, QPalette, QPen, QRegion, QTransform)
from PyQt6.QtWidgets import QWidget


DRAG_SHORT = 1      # visible only while keeping the mouse button pressed
DRAG_LONG  = 2      # remain visible and drag when picked up with the mouse



class Magnifier(QWidget):
    """A Magnifier is added to a View with view.setMagnifier().

    It is shown when a mouse button is pressed together with a modifier
    (by default Ctrl). It can then be resized by moving the mouse is with
    two buttons pressed, or by wheeling with resizemodifier pressed.

    Its size can be changed with resize() and the scale (defaulting to 3.0)
    with setScale().

    If can also be shown programatically with the show() method. In this case
    it can be dragged with the left mouse button.

    Wheel zooming with the modifier (by default Ctrl) zooms the magnifier.

    Instance attributes:

    ``showmodifier``:
        the modifier to popup (Qt.KeyboardModifier.ControlModifier)

    ``zoommodifier``:
        the modifier to wheel zoom (Qt.KeyboardModifier.ControlModifier)

    ``resizemodifier``:
        the key to press for wheel resizing (Qt.KeyboardModifier.ShiftModifier)

    ``showbutton``:
        the mouse button causing the magnifier to popup (by default
        Qt.MouseButton.LeftButton)

    ``resizebutton``:
        the extra mouse button to be pressed when resizing the
        magnifier (by default Qt.MouseButton.RightButton)

    ``MAX_EXTRA_ZOOM``:
        the maximum zoom (relative to the View's maximum zoom
        level)

    """

    # modifier for show
    showmodifier = Qt.KeyboardModifier.ControlModifier

    # modifier for wheel zoom
    zoommodifier = Qt.KeyboardModifier.ControlModifier

    # extra modifier for wheel resize
    resizemodifier = Qt.KeyboardModifier.ShiftModifier

    # button for show
    showbutton = Qt.MouseButton.LeftButton

    # extra button for resizing
    resizebutton = Qt.MouseButton.RightButton

    # Maximum extra zoom above the View.MAX_ZOOM
    MAX_EXTRA_ZOOM = 1.25

    # Minimal size
    MIN_SIZE = 50

    # Maximal size
    MAX_SIZE = 640

    def __init__(self):
        super().__init__()
        self._dragging = False
        self._resizepos = None
        self._resizewidth = 0
        self._scale = 3.0
        self.setAutoFillBackground(True)
        self.setBackgroundRole(QPalette.ColorRole.Dark)
        self.resize(350, 350)
        self.hide()

    def moveCenter(self, pos):
        """Called by the View, centers the widget on the given QPoint."""
        r = self.geometry()
        r.moveCenter(pos)
        self.setGeometry(r)

    def setScale(self, scale):
        """Sets the scale, relative to the dislayed size in the View."""
        self._scale = scale
        self.update()

    def scale(self):
        """Returns the scale, defaulting to 3.0 (=300%)."""
        return self._scale

    def startShortDrag(self, pos):
        """Start a short drag (e.g. on ctrl+click)."""
        viewport = self.parent()
        self._dragging = DRAG_SHORT
        self.moveCenter(pos)
        self.raise_()
        self.show()
        viewport.setCursor(Qt.CursorShape.BlankCursor)

    def endShortDrag(self):
        """End a short drag."""
        viewport = self.parent()
        view = viewport.parent()
        viewport.unsetCursor()
        self.hide()
        self._resizepos = None
        self._dragging = False
        view.stopScrolling() # just if needed

    def startLongDrag(self, pos):
        """Start a long drag (when we are already visible and then dragged)."""
        self._dragging = DRAG_LONG
        self._dragpos = pos
        self.setCursor(Qt.CursorShape.ClosedHandCursor)

    def endLongDrag(self):
        """End a long drag."""
        self._dragging = False
        self.unsetCursor()
        view = self.parent().parent()
        view.stopScrolling() # just if needed

    def resizeEvent(self, ev):
        """Called on resize, sets our circular mask."""
        self.setMask(QRegion(self.rect(), QRegion.RegionType.Ellipse))

    def moveEvent(self, ev):
        """Called on move, updates the contents."""
        # we also update on paint events, but they are not generated if the
        # magnifiers fully covers the viewport
        self.update()

    def eventFilter(self, viewport, ev):
        """Handle events on the viewport of the View."""
        view = viewport.parent()
        if not self.isVisible():
            if (ev.type() == QEvent.Type.MouseButtonPress and
                ev.modifiers() == self.showmodifier and
                ev.button() == self.showbutton):
                # show and drag while button pressed: DRAG_SHORT
                self.startShortDrag(ev.pos())
                return True
        elif ev.type() == QEvent.Type.Paint:
            # if the viewport is painted, also update
            self.update()
        elif self._dragging == DRAG_SHORT:
            if ev.type() == QEvent.Type.MouseButtonPress:
                if ev.button() == self.resizebutton:
                    return True
            elif ev.type() == QEvent.Type.MouseMove:
                if ev.buttons() == self.showbutton | self.resizebutton:
                    # DRAG_SHORT is busy, both buttons are pressed: resize!
                    if self._resizepos == None:
                        self._resizepos = ev.pos()
                        self._resizewidth = self.width()
                        dy = 0
                    else:
                        dy = (ev.pos() - self._resizepos).y()
                    g = self.geometry()
                    w = min(max(self.MIN_SIZE, self._resizewidth + 2 * dy), self.MAX_SIZE)
                    self.resize(w, w)
                    self.moveCenter(g.center())
                else:
                    # just drag our center
                    self.moveCenter(ev.pos())
                    view.scrollForDragging(ev.pos())
                return True
            elif ev.type() == QEvent.Type.MouseButtonRelease:
                if ev.button() == self.showbutton:
                    # left button is released, stop dragging and/or resizing, hide
                    self.endShortDrag()
                elif ev.button() == self.resizebutton:
                    # right button is released, stop resizing, warp cursor to center
                    self._resizepos = None
                    QCursor.setPos(viewport.mapToGlobal(self.geometry().center()))
                    ev.accept()
                return True
            elif ev.type() == QEvent.Type.ContextMenu:
                self.endShortDrag()
        return False

    def mousePressEvent(self, ev):
        """Start dragging the magnifier."""
        if self._dragging == DRAG_SHORT:
            ev.ignore()
        elif not self._dragging and ev.button() == Qt.MouseButton.LeftButton:
            self.startLongDrag(ev.pos())

    def mouseMoveEvent(self, ev):
        """Move the magnifier if we were dragging it."""
        ev.ignore()
        if self._dragging == DRAG_LONG:
            ev.accept()
            pos = self.mapToParent(ev.pos())
            self.move(pos - self._dragpos)
            view = self.parent().parent()
            view.scrollForDragging(pos)

    def mouseReleaseEvent(self, ev):
        """The button is released, stop moving ourselves."""
        ev.ignore()
        if self._dragging == DRAG_LONG and ev.button() == Qt.MouseButton.LeftButton:
            self.endLongDrag()

    def wheelEvent(self, ev):
        """Implement zooming the magnifying glass."""
        if ev.modifiers() & self.zoommodifier:
            ev.accept()
            if ev.modifiers() & self.resizemodifier:
                factor = 1.1 ** (ev.angleDelta().y() / 120)
                g = self.geometry()
                c = g.center()
                g.setWidth(int(min(max(g.width() * factor, self.MIN_SIZE), self.MAX_SIZE)))
                g.setHeight(int(min(max(g.height() * factor, self.MIN_SIZE), self.MAX_SIZE)))
                g.moveCenter(c)
                self.setGeometry(g)
            else:
                factor = 1.1 ** (ev.angleDelta().y() / 120)
                scale = self._scale * factor
                view = self.parent().parent()
                layout = view.pageLayout()
                scale = max(min(scale, view.MAX_ZOOM * self.MAX_EXTRA_ZOOM / layout.zoomFactor),
                            view.MIN_ZOOM / layout.zoomFactor)
                self.setScale(scale)
        else:
            super().wheelEvent(ev)

    def paintEvent(self, ev):
        """Called when paint is needed, finds out which page to magnify."""
        view = self.parent().parent()
        layout = view.pageLayout()

        scale = max(min(self._scale, view.MAX_ZOOM * self.MAX_EXTRA_ZOOM / layout.zoomFactor),
                    view.MIN_ZOOM / layout.zoomFactor)
        matrix = QTransform().scale(scale, scale)

        # the position of our center on the layout
        c = self.geometry().center() - view.layoutPosition()

        # make a region scaling back to the view scale
        rect = matrix.inverted()[0].mapRect(self.rect())
        rect.moveCenter(c)
        region = QRegion(rect, QRegion.RegionType.Ellipse) # touches the Pages we need to draw

        # our rect on the enlarged pages
        our_rect = self.rect()
        our_rect.moveCenter(matrix.map(c))

        # the virtual position of the whole scaled-up layout
        ev_rect = ev.rect().translated(our_rect.topLeft())

        # draw shadow border?
        shadow = False
        if hasattr(view, "drawDropShadow") and view.dropShadowEnabled:
            shadow = True
            shadow_width = layout.spacing * scale // 2

        painter = QPainter(self)
        for p in layout.pagesAt(region.boundingRect()):
            # get a (reused) the copy of the page
            page = p.copy(self, matrix)
            # now paint it
            rect = (page.geometry() & ev_rect).translated(-page.pos())
            painter.save()
            painter.translate(page.pos() - our_rect.topLeft())
            if shadow:
                view.drawDropShadow(page, painter, shadow_width)
            page.paint(painter, rect, self.repaintPage)
            painter.restore()

        self.drawBorder(painter)

    def drawBorder(self, painter):
        """Draw a nice looking glass border."""
        painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
        painter.setPen(QPen(QColor(192, 192, 192, 128), 6))
        painter.drawEllipse(self.rect().adjusted(2, 2, -2, -2))

    def repaintPage(self, page):
        """Called when a Page was rendered in the background."""
        ## TODO: smarter determination which part to update
        self.update()