From 2ddb364a015d66a3f3c39fd42cb5f3083409f18d Mon Sep 17 00:00:00 2001 From: Tim Hoffmann <2836374+timhoffm@users.noreply.github.com> Date: Thu, 20 Mar 2025 19:00:17 +0100 Subject: [PATCH] Backport PR #29781: Fix escaping of nulls and "0" in default filenames. --- lib/matplotlib/backend_bases.py | 17 +++++++++-------- lib/matplotlib/tests/test_backend_bases.py | 5 ++++- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/lib/matplotlib/backend_bases.py b/lib/matplotlib/backend_bases.py index 0843796bad5a..a889a6b26e8e 100644 --- a/lib/matplotlib/backend_bases.py +++ b/lib/matplotlib/backend_bases.py @@ -2218,7 +2218,7 @@ def get_default_filename(self): # Characters to be avoided in a NT path: # https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#naming_conventions # plus ' ' - removed_chars = r'<>:"/\|?*\0 ' + removed_chars = '<>:"/\\|?*\0 ' default_basename = default_basename.translate( {ord(c): "_" for c in removed_chars}) default_filetype = self.get_default_filetype() @@ -2728,23 +2728,24 @@ def resize(self, w, h): """For GUI backends, resize the window (in physical pixels).""" def get_window_title(self): - """ - Return the title text of the window containing the figure, or None - if there is no window (e.g., a PS backend). - """ - return 'image' + """Return the title text of the window containing the figure.""" + return self._window_title def set_window_title(self, title): """ Set the title text of the window containing the figure. - This has no effect for non-GUI (e.g., PS) backends. - Examples -------- >>> fig = plt.figure() >>> fig.canvas.manager.set_window_title('My figure') """ + # This attribute is not defined in __init__ (but __init__ calls this + # setter), as derived classes (real GUI managers) will store this + # information directly on the widget; only the base (non-GUI) manager + # class needs a specific attribute for it (so that filename escaping + # can be checked in the test suite). + self._window_title = title cursors = tools.cursors diff --git a/lib/matplotlib/tests/test_backend_bases.py b/lib/matplotlib/tests/test_backend_bases.py index 3e1f524ed1c9..10108d11bd0a 100644 --- a/lib/matplotlib/tests/test_backend_bases.py +++ b/lib/matplotlib/tests/test_backend_bases.py @@ -64,7 +64,10 @@ def test_canvas_ctor(): def test_get_default_filename(): - assert plt.figure().canvas.get_default_filename() == 'image.png' + fig = plt.figure() + assert fig.canvas.get_default_filename() == "Figure_1.png" + fig.canvas.manager.set_window_title("0:1/2<3") + assert fig.canvas.get_default_filename() == "0_1_2_3.png" def test_canvas_change():