Skip to content

Commit dfc9872

Browse files
committed
Move pixel ratio handling into FigureCanvasBase.
This is already implemented in two backends (Qt5 and nbAgg), and I plan to implement it in TkAgg, so it's better to remove the repetition.
1 parent d45dcef commit dfc9872

File tree

7 files changed

+104
-74
lines changed

7 files changed

+104
-74
lines changed

lib/matplotlib/backend_bases.py

Lines changed: 68 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1723,6 +1723,10 @@ def __init__(self, figure):
17231723
self.toolbar = None # NavigationToolbar2 will set me
17241724
self._is_idle_drawing = False
17251725

1726+
# We don't want to scale up the figure DPI more than once.
1727+
figure._original_dpi = figure.dpi
1728+
self._device_pixel_ratio = 1
1729+
17261730
@property
17271731
def callbacks(self):
17281732
return self.figure._canvas_callbacks
@@ -2040,12 +2044,73 @@ def draw_idle(self, *args, **kwargs):
20402044
with self._idle_draw_cntx():
20412045
self.draw(*args, **kwargs)
20422046

2047+
@property
2048+
def device_pixel_ratio(self):
2049+
"""
2050+
The ratio of physical to logical pixels used for the canvas on screen.
2051+
2052+
By default, this is 1, meaning physical and logical pixels are the same
2053+
size. Subclasses that support High DPI screens may set this property to
2054+
indicate that said ratio is different. All Matplotlib interaction,
2055+
unless working directly with the canvas, remains in logical pixels.
2056+
2057+
"""
2058+
return self._device_pixel_ratio
2059+
2060+
def _set_device_pixel_ratio(self, ratio):
2061+
"""
2062+
Set the ratio of physical to logical pixels used for the canvas.
2063+
2064+
Subclasses that support High DPI screens can set this property to
2065+
indicate that said ratio is different. The canvas itself will be
2066+
created at the physical size, while the client side will use the
2067+
logical size. Thus the DPI of the Figure will change to be scaled by
2068+
this ratio. Implementations that support High DPI screens should use
2069+
physical pixels for events so that transforms back to Axes space are
2070+
correct.
2071+
2072+
By default, this is 1, meaning physical and logical pixels are the same
2073+
size.
2074+
2075+
Parameters
2076+
----------
2077+
ratio : float
2078+
The ratio of logical to physical pixels used for the canvas.
2079+
2080+
Returns
2081+
-------
2082+
bool
2083+
Whether the ratio has changed. Backends may interpret this as a
2084+
signal to resize the window, repaint the canvas, or change any
2085+
other relevant properties.
2086+
"""
2087+
if self._device_pixel_ratio == ratio:
2088+
return False
2089+
# In cases with mixed resolution displays, we need to be careful if the
2090+
# device pixel ratio changes - in this case we need to resize the
2091+
# canvas accordingly. Some backends provide events that indicate a
2092+
# change in DPI, but those that don't will update this before drawing.
2093+
dpi = ratio * self.figure._original_dpi
2094+
self.figure._set_dpi(dpi, forward=False)
2095+
self._device_pixel_ratio = ratio
2096+
return True
2097+
20432098
def get_width_height(self):
20442099
"""
2045-
Return the figure width and height in points or pixels
2046-
(depending on the backend), truncated to integers.
2100+
Return the figure width and height in integral points or pixels.
2101+
2102+
When the figure is used on High DPI screens (and the backend supports
2103+
it), the truncation to integers occurs after scaling by the device
2104+
pixel ratio.
2105+
2106+
Returns
2107+
-------
2108+
width, height : int
2109+
The size of the figure, in points or pixels, depending on the
2110+
backend.
20472111
"""
2048-
return int(self.figure.bbox.width), int(self.figure.bbox.height)
2112+
return tuple(int(size / self.device_pixel_ratio)
2113+
for size in self.figure.bbox.max)
20492114

20502115
@classmethod
20512116
def get_supported_filetypes(cls):

lib/matplotlib/backends/backend_qt5.py

Lines changed: 8 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -220,15 +220,6 @@ def __init__(self, figure):
220220
_create_qApp()
221221
super().__init__(figure=figure)
222222

223-
# We don't want to scale up the figure DPI more than once.
224-
# Note, we don't handle a signal for changing DPI yet.
225-
figure._original_dpi = figure.dpi
226-
self._update_figure_dpi()
227-
# In cases with mixed resolution displays, we need to be careful if the
228-
# dpi_ratio changes - in this case we need to resize the canvas
229-
# accordingly.
230-
self._dpi_ratio_prev = self._dpi_ratio
231-
232223
self._draw_pending = False
233224
self._is_drawing = False
234225
self._draw_rect_callback = lambda painter: None
@@ -240,28 +231,13 @@ def __init__(self, figure):
240231
palette = QtGui.QPalette(QtCore.Qt.white)
241232
self.setPalette(palette)
242233

243-
def _update_figure_dpi(self):
244-
dpi = self._dpi_ratio * self.figure._original_dpi
245-
self.figure._set_dpi(dpi, forward=False)
246-
247-
@property
248-
def _dpi_ratio(self):
249-
return _devicePixelRatioF(self)
250-
251234
def _update_pixel_ratio(self):
252-
# We need to be careful in cases with mixed resolution displays if
253-
# dpi_ratio changes.
254-
if self._dpi_ratio != self._dpi_ratio_prev:
255-
# We need to update the figure DPI.
256-
self._update_figure_dpi()
257-
self._dpi_ratio_prev = self._dpi_ratio
235+
if self._set_device_pixel_ratio(_devicePixelRatioF(self)):
258236
# The easiest way to resize the canvas is to emit a resizeEvent
259237
# since we implement all the logic for resizing the canvas for
260238
# that event.
261239
event = QtGui.QResizeEvent(self.size(), self.size())
262240
self.resizeEvent(event)
263-
# resizeEvent triggers a paintEvent itself, so we exit this one
264-
# (after making sure that the event is immediately handled).
265241

266242
def _update_screen(self, screen):
267243
# Handler for changes to a window's attached screen.
@@ -277,10 +253,6 @@ def showEvent(self, event):
277253
window.screenChanged.connect(self._update_screen)
278254
self._update_screen(window.screen())
279255

280-
def get_width_height(self):
281-
w, h = FigureCanvasBase.get_width_height(self)
282-
return int(w / self._dpi_ratio), int(h / self._dpi_ratio)
283-
284256
def enterEvent(self, event):
285257
try:
286258
x, y = self.mouseEventCoords(event.pos())
@@ -303,11 +275,10 @@ def mouseEventCoords(self, pos):
303275
304276
Also, the origin is different and needs to be corrected.
305277
"""
306-
dpi_ratio = self._dpi_ratio
307278
x = pos.x()
308279
# flip y so y=0 is bottom of canvas
309-
y = self.figure.bbox.height / dpi_ratio - pos.y()
310-
return x * dpi_ratio, y * dpi_ratio
280+
y = self.figure.bbox.height / self.device_pixel_ratio - pos.y()
281+
return x * self.device_pixel_ratio, y * self.device_pixel_ratio
311282

312283
def mousePressEvent(self, event):
313284
x, y = self.mouseEventCoords(event.pos())
@@ -368,8 +339,8 @@ def keyReleaseEvent(self, event):
368339
FigureCanvasBase.key_release_event(self, key, guiEvent=event)
369340

370341
def resizeEvent(self, event):
371-
w = event.size().width() * self._dpi_ratio
372-
h = event.size().height() * self._dpi_ratio
342+
w = event.size().width() * self.device_pixel_ratio
343+
h = event.size().height() * self.device_pixel_ratio
373344
dpival = self.figure.dpi
374345
winch = w / dpival
375346
hinch = h / dpival
@@ -467,7 +438,7 @@ def blit(self, bbox=None):
467438
if bbox is None and self.figure:
468439
bbox = self.figure.bbox # Blit the entire canvas if bbox is None.
469440
# repaint uses logical pixels, not physical pixels like the renderer.
470-
l, b, w, h = [int(pt / self._dpi_ratio) for pt in bbox.bounds]
441+
l, b, w, h = [int(pt / self.device_pixel_ratio) for pt in bbox.bounds]
471442
t = b + h
472443
self.repaint(l, self.rect().height() - t, w, h)
473444

@@ -488,11 +459,11 @@ def drawRectangle(self, rect):
488459
# Draw the zoom rectangle to the QPainter. _draw_rect_callback needs
489460
# to be called at the end of paintEvent.
490461
if rect is not None:
491-
x0, y0, w, h = [int(pt / self._dpi_ratio) for pt in rect]
462+
x0, y0, w, h = [int(pt / self.device_pixel_ratio) for pt in rect]
492463
x1 = x0 + w
493464
y1 = y0 + h
494465
def _draw_rect_callback(painter):
495-
pen = QtGui.QPen(QtCore.Qt.black, 1 / self._dpi_ratio)
466+
pen = QtGui.QPen(QtCore.Qt.black, 1 / self.device_pixel_ratio)
496467
pen.setDashPattern([3, 3])
497468
for color, offset in [
498469
(QtCore.Qt.black, 0), (QtCore.Qt.white, 3)]:

lib/matplotlib/backends/backend_qt5agg.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,8 @@ def paintEvent(self, event):
4242
# scale rect dimensions using the screen dpi ratio to get
4343
# correct values for the Figure coordinates (rather than
4444
# QT5's coords)
45-
width = rect.width() * self._dpi_ratio
46-
height = rect.height() * self._dpi_ratio
45+
width = rect.width() * self.device_pixel_ratio
46+
height = rect.height() * self.device_pixel_ratio
4747
left, top = self.mouseEventCoords(rect.topLeft())
4848
# shift the "top" by the height of the image to get the
4949
# correct corner for our coordinate system
@@ -61,7 +61,7 @@ def paintEvent(self, event):
6161

6262
qimage = QtGui.QImage(buf, buf.shape[1], buf.shape[0],
6363
QtGui.QImage.Format_ARGB32_Premultiplied)
64-
_setDevicePixelRatio(qimage, self._dpi_ratio)
64+
_setDevicePixelRatio(qimage, self.device_pixel_ratio)
6565
# set origin using original QT coordinates
6666
origin = QtCore.QPoint(rect.left(), rect.top())
6767
painter.drawImage(origin, qimage)

lib/matplotlib/backends/backend_qt5cairo.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,8 @@ def draw(self):
1717
super().draw()
1818

1919
def paintEvent(self, event):
20-
dpi_ratio = self._dpi_ratio
21-
width = int(dpi_ratio * self.width())
22-
height = int(dpi_ratio * self.height())
20+
width = int(self.device_pixel_ratio * self.width())
21+
height = int(self.device_pixel_ratio * self.height())
2322
if (width, height) != self._renderer.get_canvas_width_height():
2423
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
2524
self._renderer.set_ctx_from_surface(surface)
@@ -32,7 +31,7 @@ def paintEvent(self, event):
3231
# QImage under PySide on Python 3.
3332
if QT_API == 'PySide':
3433
ctypes.c_long.from_address(id(buf)).value = 1
35-
_setDevicePixelRatio(qimage, dpi_ratio)
34+
_setDevicePixelRatio(qimage, self.device_pixel_ratio)
3635
painter = QtGui.QPainter(self)
3736
painter.eraseRect(event.rect())
3837
painter.drawImage(0, 0, qimage)

lib/matplotlib/backends/backend_webagg_core.py

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -172,10 +172,6 @@ def __init__(self, *args, **kwargs):
172172
# to the connected clients.
173173
self._current_image_mode = 'full'
174174

175-
# Store the DPI ratio of the browser. This is the scaling that
176-
# occurs automatically for all images on a HiDPI display.
177-
self._dpi_ratio = 1
178-
179175
def show(self):
180176
# show the figure window
181177
from matplotlib.pyplot import show
@@ -345,8 +341,8 @@ def handle_refresh(self, event):
345341
self.draw_idle()
346342

347343
def handle_resize(self, event):
348-
x, y = event.get('width', 800), event.get('height', 800)
349-
x, y = int(x) * self._dpi_ratio, int(y) * self._dpi_ratio
344+
x = int(event.get('width', 800)) * self.device_pixel_ratio
345+
y = int(event.get('height', 800)) * self.device_pixel_ratio
350346
fig = self.figure
351347
# An attempt at approximating the figure size in pixels.
352348
fig.set_size_inches(x / fig.dpi, y / fig.dpi, forward=False)
@@ -361,14 +357,9 @@ def handle_send_image_mode(self, event):
361357
# The client requests notification of what the current image mode is.
362358
self.send_event('image_mode', mode=self._current_image_mode)
363359

364-
def handle_set_dpi_ratio(self, event):
365-
dpi_ratio = event.get('dpi_ratio', 1)
366-
if dpi_ratio != self._dpi_ratio:
367-
# We don't want to scale up the figure dpi more than once.
368-
if not hasattr(self.figure, '_original_dpi'):
369-
self.figure._original_dpi = self.figure.dpi
370-
self.figure.dpi = dpi_ratio * self.figure._original_dpi
371-
self._dpi_ratio = dpi_ratio
360+
def handle_set_device_pixel_ratio(self, event):
361+
device_pixel_ratio = event.get('device_pixel_ratio', 1)
362+
if self._set_device_pixel_ratio(device_pixel_ratio):
372363
self._force_full = True
373364
self.draw_idle()
374365

@@ -460,7 +451,8 @@ def _get_toolbar(self, canvas):
460451
def resize(self, w, h, forward=True):
461452
self._send_event(
462453
'resize',
463-
size=(w / self.canvas._dpi_ratio, h / self.canvas._dpi_ratio),
454+
size=(w / self.canvas.device_pixel_ratio,
455+
h / self.canvas.device_pixel_ratio),
464456
forward=forward)
465457

466458
def set_window_title(self, title):

lib/matplotlib/backends/web_backend/js/mpl.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,9 @@ mpl.figure = function (figure_id, websocket, ondownload, parent_element) {
6363
fig.send_message('supports_binary', { value: fig.supports_binary });
6464
fig.send_message('send_image_mode', {});
6565
if (fig.ratio !== 1) {
66-
fig.send_message('set_dpi_ratio', { dpi_ratio: fig.ratio });
66+
fig.send_message('set_device_pixel_ratio', {
67+
device_pixel_ratio: fig.ratio,
68+
});
6769
}
6870
fig.send_message('refresh', {});
6971
};

lib/matplotlib/tests/test_backend_qt.py

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -166,10 +166,10 @@ def on_key_press(event):
166166

167167

168168
@pytest.mark.backend('Qt5Agg', skip_on_importerror=True)
169-
def test_pixel_ratio_change():
169+
def test_device_pixel_ratio_change():
170170
"""
171171
Make sure that if the pixel ratio changes, the figure dpi changes but the
172-
widget remains the same physical size.
172+
widget remains the same logical size.
173173
"""
174174

175175
prop = 'matplotlib.backends.backend_qt5.FigureCanvasQT.devicePixelRatioF'
@@ -180,10 +180,8 @@ def test_pixel_ratio_change():
180180
qt_canvas = fig.canvas
181181
qt_canvas.show()
182182

183-
def set_pixel_ratio(ratio):
183+
def set_device_pixel_ratio(ratio):
184184
p.return_value = ratio
185-
# Make sure the mocking worked
186-
assert qt_canvas._dpi_ratio == ratio
187185

188186
# The value here doesn't matter, as we can't mock the C++ QScreen
189187
# object, but can override the functional wrapper around it.
@@ -194,43 +192,46 @@ def set_pixel_ratio(ratio):
194192
qt_canvas.draw()
195193
qt_canvas.flush_events()
196194

195+
# Make sure the mocking worked
196+
assert qt_canvas.device_pixel_ratio == ratio
197+
197198
qt_canvas.manager.show()
198199
size = qt_canvas.size()
199200
screen = qt_canvas.window().windowHandle().screen()
200-
set_pixel_ratio(3)
201+
set_device_pixel_ratio(3)
201202

202203
# The DPI and the renderer width/height change
203204
assert fig.dpi == 360
204205
assert qt_canvas.renderer.width == 1800
205206
assert qt_canvas.renderer.height == 720
206207

207-
# The actual widget size and figure physical size don't change
208+
# The actual widget size and figure logical size don't change.
208209
assert size.width() == 600
209210
assert size.height() == 240
210211
assert qt_canvas.get_width_height() == (600, 240)
211212
assert (fig.get_size_inches() == (5, 2)).all()
212213

213-
set_pixel_ratio(2)
214+
set_device_pixel_ratio(2)
214215

215216
# The DPI and the renderer width/height change
216217
assert fig.dpi == 240
217218
assert qt_canvas.renderer.width == 1200
218219
assert qt_canvas.renderer.height == 480
219220

220-
# The actual widget size and figure physical size don't change
221+
# The actual widget size and figure logical size don't change.
221222
assert size.width() == 600
222223
assert size.height() == 240
223224
assert qt_canvas.get_width_height() == (600, 240)
224225
assert (fig.get_size_inches() == (5, 2)).all()
225226

226-
set_pixel_ratio(1.5)
227+
set_device_pixel_ratio(1.5)
227228

228229
# The DPI and the renderer width/height change
229230
assert fig.dpi == 180
230231
assert qt_canvas.renderer.width == 900
231232
assert qt_canvas.renderer.height == 360
232233

233-
# The actual widget size and figure physical size don't change
234+
# The actual widget size and figure logical size don't change.
234235
assert size.width() == 600
235236
assert size.height() == 240
236237
assert qt_canvas.get_width_height() == (600, 240)

0 commit comments

Comments
 (0)