8000 Merge pull request #22180 from greglucas/macosx-savefig · matplotlib/matplotlib@dd001ed · GitHub
[go: up one dir, main page]

Skip to content

Commit dd001ed

Browse files
authored
Merge pull request #22180 from greglucas/macosx-savefig
ENH: Use rcParams savefig.directory on macosx backend
2 parents 875209e + 15afb44 commit dd001ed

File tree

3 files changed

+45
-21
lines changed

3 files changed

+45
-21
lines changed

lib/matplotlib/backends/backend_macosx.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import os
2+
13
import matplotlib as mpl
24
from matplotlib import _api, cbook
35
from matplotlib._pylab_helpers import Gcf
@@ -115,10 +117,15 @@ def remove_rubberband(self):
115117
self.canvas.remove_rubberband()
116118

117119
def save_figure(self, *args):
120+
directory = os.path.expanduser(mpl.rcParams['savefig.directory'])
118121
filename = _macosx.choose_save_file('Save the figure',
122+
directory,
119123
self.canvas.get_default_filename())
120124
if filename is None: # Cancel
121125
return
126+
# Save dir for next time, unless empty str (which means use cwd).
127+
if mpl.rcParams['savefig.directory']:
128+
mpl.rcParams['savefig.directory'] = os.path.dirname(filename)
122129
self.canvas.figure.savefig(filename)
123130

124131
def prepare_configure_subplots(self):

lib/matplotlib/tests/test_backend_macosx.py

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
1+
import os
2+
13
import pytest
24

5+
import matplotlib as mpl
36
import matplotlib.pyplot as plt
4-
5-
6-
pytest.importorskip("matplotlib.backends.backend_macosx",
7-
reason="These are mac only tests")
7+
try:
8+
from matplotlib.backends import _macosx
9+
except ImportError:
10+
pytest.skip("These are mac only tests", allow_module_level=True)
811

912

1013
@pytest.mark.backend('macosx')
@@ -18,3 +21,26 @@ def test_cached_renderer():
1821
fig = plt.figure(2)
1922
fig.draw_without_rendering()
2023
assert fig._cachedRenderer is not None
24+
25+
26+
@pytest.mark.backend('macosx')
27+
def test_savefig_rcparam(monkeypatch, tmp_path):
28+
29+
def new_choose_save_file(title, directory, filename):
30+
# Replacement function instead of opening a GUI window
31+
# Make a new directory for testing the update of the rcParams
32+
assert directory == str(tmp_path)
33+
os.makedirs(f"{directory}/test")
34+
return f"{directory}/test/{filename}"
35+
36+
monkeypatch.setattr(_macosx, "choose_save_file", new_choose_save_file)
37+
fig = plt.figure()
38+
with mpl.rc_context({"savefig.directory": tmp_path}):
39+
fig.canvas.toolbar.save_figure()
40+
# Check the saved location got created
41+
save_file = f"{tmp_path}/test/{fig.canvas.get_default_filename()}"
42+
assert os.path.exists(save_file)
43+
44+
# Check the savefig.directory rcParam got updated because
45+
# we added a subdirectory "test"
46+
assert mpl.rcParams["savefig.directory"] == f"{tmp_path}/test"

src/_macosx.m

Lines changed: 8 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1022,33 +1022,24 @@ -(void)save_figure:(id)sender { gil_call_method(toolbar, "save_figure"); }
10221022
{
10231023
int result;
10241024
const char* title;
1025+
const char* directory;
10251026
const char* default_filename;
1026-
if (!PyArg_ParseTuple(args, "ss", &title, &default_filename)) {
1027+
if (!PyArg_ParseTuple(args, "sss", &title, &directory, &default_filename)) {
10271028
return NULL;
10281029
}
10291030
NSSavePanel* panel = [NSSavePanel savePanel];
1030-
[panel setTitle: [NSString stringWithCString: title
1031-
encoding: NSASCIIStringEncoding]];
1032-
NSString* ns_default_filename =
1033-
[[NSString alloc]
1034-
initWithCString: default_filename
1035-
encoding: NSUTF8StringEncoding];
1036-
[panel setNameFieldStringValue: ns_default_filename];
1031+
[panel setTitle: [NSString stringWithUTF8String: title]];
1032+
[panel setDirectoryURL: [NSURL fileURLWithPath: [NSString stringWithUTF8String: directory]
1033+
isDirectory: YES]];
1034+
[panel setNameFieldStringValue: [NSString stringWithUTF8String: default_filename]];
10371035
result = [panel runModal];
1038-
[ns_default_filename release];
10391036
if (result == NSModalResponseOK) {
1040-
NSURL* url = [panel URL];
1041-
NSString* filename = [url path];
1037+
NSString *filename = [[panel URL] path];
10421038
if (!filename) {
10431039
PyErr_SetString(PyExc_RuntimeError, "Failed to obtain filename");
10441040
return 0;
10451041
}
1046-
unsigned int n = [filename length];
1047-
unichar* buffer = malloc(n*sizeof(unichar));
1048-
[filename getCharacters: buffer];
1049-
PyObject* string = PyUnicode_FromKindAndData(PyUnicode_2BYTE_KIND, buffer, n);
1050-
free(buffer);
1051-
return string;
1042+
return PyUnicode_FromString([filename UTF8String]);
10521043
}
10531044
Py_RETURN_NONE;
10541045
}

0 commit comments

Comments
 (0)
0