Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions lib/matplotlib/tests/test_backend_macosx.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import os
import threading
from pathlib import Path

import pytest
Expand Down Expand Up @@ -84,3 +85,25 @@ def _test_save_figure_return():
def test_save_figure_return():
subprocess_run_helper(_test_save_figure_return, timeout=_test_timeout,
extra_env={"MPLBACKEND": "macosx"})


def _test_create_figure_on_worker_thread_fails():
def create_figure():
warn_msg = "Matplotlib GUI outside of the main thread will likely fail."
err_msg = "Cannot create a GUI FigureManager outside the main thread"
with pytest.warns(UserWarning, match=warn_msg):
with pytest.raises(RuntimeError, match=err_msg):
plt.gcf()

worker = threading.Thread(target=create_figure)
worker.start()
worker.join()


@pytest.mark.backend('macosx', skip_on_importerror=True)
def test_create_figure_on_worker_thread_fails():
subprocess_run_helper(
_test_create_figure_on_worker_thread_fails,
timeout=_test_timeout,
extra_env={"MPLBACKEND": "macosx"}
)
10 changes: 10 additions & 0 deletions src/_macosx.m
Original file line number Diff line number Diff line change
Expand Up @@ -582,6 +582,16 @@ bool mpl_check_modifier(bool present, PyObject* list, char const* name)
static PyObject*
FigureManager_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
if (![NSThread isMainThread]) {
PyErr_SetString(
PyExc_RuntimeError,
"Cannot create a GUI FigureManager outside the main thread "
"using the MacOS backend. Use a non-interactive "
"backend like 'agg' to make plots on worker threads."
);
return NULL;
}

lazy_init();
Window* window = [Window alloc];
if (!window) { return NULL; }
Expand Down