-
-
Notifications
You must be signed in to change notification settings - Fork 8.3k
Add support for High DPI displays to wxAgg backend #26710
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -14,9 +14,6 @@ | |
| import sys | ||
| import weakref | ||
|
|
||
| import numpy as np | ||
| import PIL.Image | ||
|
|
||
| import matplotlib as mpl | ||
| from matplotlib.backend_bases import ( | ||
| _Backend, FigureCanvasBase, FigureManagerBase, | ||
|
|
@@ -30,6 +27,7 @@ | |
| from matplotlib.transforms import Affine2D | ||
|
|
||
| import wx | ||
| import wx.svg | ||
|
|
||
| _log = logging.getLogger(__name__) | ||
|
|
||
|
|
@@ -45,6 +43,10 @@ def _create_wxapp(): | |
| wxapp = wx.App(False) | ||
| wxapp.SetExitOnFrameDelete(True) | ||
| cbook._setup_new_guiapp() | ||
| if wx.Platform == '__WXMSW__': | ||
| # Set per-process DPI awareness. See https://docs.microsoft.com/en-us/windows/win32/api/shellscalingapi/ne-shellscalingapi-process_dpi_awareness | ||
| import ctypes | ||
| ctypes.windll.shcore.SetProcessDpiAwareness(2) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This should use the wrapper from
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @QuLogic Thank you for catching that. Fixed. |
||
| return wxapp | ||
|
|
||
|
|
||
|
|
@@ -471,12 +473,12 @@ def __init__(self, parent, id, figure=None): | |
| """ | ||
|
|
||
| FigureCanvasBase.__init__(self, figure) | ||
| w, h = map(math.ceil, self.figure.bbox.size) | ||
| size = wx.Size(*map(math.ceil, self.figure.bbox.size)) | ||
| if wx.Platform != '__WXMSW__': | ||
| size = parent.FromDIP(size) | ||
| # Set preferred window size hint - helps the sizer, if one is connected | ||
| wx.Panel.__init__(self, parent, id, size=wx.Size(w, h)) | ||
| # Create the drawing bitmap | ||
| self.bitmap = wx.Bitmap(w, h) | ||
| _log.debug("%s - __init__() - bitmap w:%d h:%d", type(self), w, h) | ||
| wx.Panel.__init__(self, parent, id, size=size) | ||
| self.bitmap = None | ||
| self._isDrawn = False | ||
| self._rubberband_rect = None | ||
| self._rubberband_pen_black = wx.Pen('BLACK', 1, wx.PENSTYLE_SHORT_DASH) | ||
|
|
@@ -512,6 +514,12 @@ def __init__(self, parent, id, figure=None): | |
| self.SetBackgroundStyle(wx.BG_STYLE_PAINT) # Reduce flicker. | ||
| self.SetBackgroundColour(wx.WHITE) | ||
|
|
||
| if wx.Platform == '__WXMAC__': | ||
| # Initial scaling. Other platforms handle this automatically | ||
| dpiScale = self.GetDPIScaleFactor() | ||
| self.SetInitialSize(self.GetSize()*(1/dpiScale)) | ||
| self._set_device_pixel_ratio(dpiScale) | ||
|
|
||
| def Copy_to_Clipboard(self, event=None): | ||
| """Copy bitmap of canvas to system clipboard.""" | ||
| bmp_obj = wx.BitmapDataObject() | ||
|
|
@@ -524,6 +532,12 @@ def Copy_to_Clipboard(self, event=None): | |
| wx.TheClipboard.Flush() | ||
| wx.TheClipboard.Close() | ||
|
|
||
| def _update_device_pixel_ratio(self, *args, **kwargs): | ||
| # We need to be careful in cases with mixed resolution displays if | ||
| # device_pixel_ratio changes. | ||
| if self._set_device_pixel_ratio(self.GetDPIScaleFactor()): | ||
| self.draw() | ||
|
|
||
| def draw_idle(self): | ||
| # docstring inherited | ||
| _log.debug("%s - draw_idle()", type(self)) | ||
|
|
@@ -631,7 +645,7 @@ def _on_size(self, event): | |
| In this application we attempt to resize to fit the window, so it | ||
| is better to take the performance hit and redraw the whole window. | ||
| """ | ||
|
|
||
| self._update_device_pixel_ratio() | ||
| _log.debug("%s - _on_size()", type(self)) | ||
| sz = self.GetParent().GetSizer() | ||
| if sz: | ||
|
|
@@ -655,9 +669,10 @@ def _on_size(self, event): | |
| return # Empty figure | ||
|
|
||
| # Create a new, correctly sized bitmap | ||
| self.bitmap = wx.Bitmap(self._width, self._height) | ||
|
|
||
| dpival = self.figure.dpi | ||
| if not wx.Platform == '__WXMSW__': | ||
| scale = self.GetDPIScaleFactor() | ||
| dpival /= scale | ||
| winch = self._width / dpival | ||
| hinch = self._height / dpival | ||
| self.figure.set_size_inches(winch, hinch, forward=False) | ||
|
|
@@ -712,7 +727,11 @@ def _mpl_coords(self, pos=None): | |
| else: | ||
| x, y = pos.X, pos.Y | ||
| # flip y so y=0 is bottom of canvas | ||
| return x, self.figure.bbox.height - y | ||
| if not wx.Platform == '__WXMSW__': | ||
| scale = self.GetDPIScaleFactor() | ||
| return x*scale, self.figure.bbox.height - y*scale | ||
| else: | ||
| return x, self.figure.bbox.height - y | ||
|
|
||
| def _on_key_down(self, event): | ||
| """Capture key press.""" | ||
|
|
@@ -898,8 +917,8 @@ def __init__(self, num, fig, *, canvas_class): | |
| # On Windows, canvas sizing must occur after toolbar addition; | ||
| # otherwise the toolbar further resizes the canvas. | ||
| w, h = map(math.ceil, fig.bbox.size) | ||
| self.canvas.SetInitialSize(wx.Size(w, h)) | ||
| self.canvas.SetMinSize((2, 2)) | ||
| self.canvas.SetInitialSize(self.FromDIP(wx.Size(w, h))) | ||
| self.canvas.SetMinSize(self.FromDIP(wx.Size(2, 2))) | ||
| self.canvas.SetFocus() | ||
|
|
||
| self.Fit() | ||
|
|
@@ -1017,9 +1036,9 @@ def _set_frame_icon(frame): | |
| class NavigationToolbar2Wx(NavigationToolbar2, wx.ToolBar): | ||
| def __init__(self, canvas, coordinates=True, *, style=wx.TB_BOTTOM): | ||
| wx.ToolBar.__init__(self, canvas.GetParent(), -1, style=style) | ||
| if wx.Platform == '__WXMAC__': | ||
| self.SetToolBitmapSize(self.GetToolBitmapSize()*self.GetDPIScaleFactor()) | ||
|
|
||
| if 'wxMac' in wx.PlatformInfo: | ||
| self.SetToolBitmapSize((24, 24)) | ||
| self.wx_ids = {} | ||
| for text, tooltip_text, image_file, callback in self.toolitems: | ||
| if text is None: | ||
|
|
@@ -1028,7 +1047,7 @@ def __init__(self, canvas, coordinates=True, *, style=wx.TB_BOTTOM): | |
| self.wx_ids[text] = ( | ||
| self.AddTool( | ||
| -1, | ||
| bitmap=self._icon(f"{image_file}.png"), | ||
| bitmap=self._icon(f"{image_file}.svg"), | ||
| bmpDisabled=wx.NullBitmap, | ||
| label=text, shortHelp=tooltip_text, | ||
| kind=(wx.ITEM_CHECK if text in ["Pan", "Zoom"] | ||
|
|
@@ -1054,9 +1073,7 @@ def _icon(name): | |
| *name*, including the extension and relative to Matplotlib's "images" | ||
| data directory. | ||
| """ | ||
| pilimg = PIL.Image.open(cbook._get_data_path("images", name)) | ||
| # ensure RGBA as wx BitMap expects RGBA format | ||
| image = np.array(pilimg.convert("RGBA")) | ||
| svg = cbook._get_data_path("images", name).read_bytes() | ||
| try: | ||
| dark = wx.SystemSettings.GetAppearance().IsDark() | ||
| except AttributeError: # wxpython < 4.1 | ||
|
|
@@ -1068,11 +1085,9 @@ def _icon(name): | |
| fg_lum = (.299 * fg.red + .587 * fg.green + .114 * fg.blue) / 255 | ||
| dark = fg_lum - bg_lum > .2 | ||
| if dark: | ||
| fg = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT) | ||
| black_mask = (image[..., :3] == 0).all(axis=-1) | ||
| image[black_mask, :3] = (fg.Red(), fg.Green(), fg.Blue()) | ||
| return wx.Bitmap.FromBufferRGBA( | ||
| image.shape[1], image.shape[0], image.tobytes()) | ||
| svg = svg.replace(b'fill:black;', b'fill:white;') | ||
| toolbarIconSize = wx.ArtProvider().GetDIPSizeHint(wx.ART_TOOLBAR) | ||
| return wx.BitmapBundle.FromSVG(svg, toolbarIconSize) | ||
|
|
||
| def _update_buttons_checked(self): | ||
| if "Pan" in self.wx_ids: | ||
|
|
@@ -1123,7 +1138,9 @@ def save_figure(self, *args): | |
|
|
||
| def draw_rubberband(self, event, x0, y0, x1, y1): | ||
| height = self.canvas.figure.bbox.height | ||
| self.canvas._rubberband_rect = (x0, height - y0, x1, height - y1) | ||
| sf = 1 if wx.Platform == '__WXMSW__' else self.GetDPIScaleFactor() | ||
| self.canvas._rubberband_rect = (x0/sf, (height - y0)/sf, | ||
| x1/sf, (height - y1)/sf) | ||
| self.canvas.Refresh() | ||
|
|
||
| def remove_rubberband(self): | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
flake8 will be happy if the long URL is on a line by itself:
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thank you. Good to know. I ended up removing the link because using the internal function that you suggest in your next comment makes it unnecessary.