forked from matplotlib/napari-matplotlib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbase.py
204 lines (170 loc) · 6.54 KB
/
base.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import os
from pathlib import Path
from typing import List, Tuple
import napari
from matplotlib.backends.backend_qt5agg import (
FigureCanvas,
NavigationToolbar2QT,
)
from qtpy.QtGui import QIcon
from qtpy.QtWidgets import QVBoxLayout, QWidget
from .util import Interval
# Icons modified from
# https://github.com/matplotlib/matplotlib/tree/main/lib/matplotlib/mpl-data/images
ICON_ROOT = Path(__file__).parent / "icons"
NAPARI_WINDOW_COLOR = "#262930"
__all__ = ["NapariMPLWidget"]
class NapariMPLWidget(QWidget):
"""
Base Matplotlib canvas. Widget that can be embedded as a napari widget.
This creates a single FigureCanvas, which contains a single Figure.
This class also handles callbacks to automatically update figures when
the layer selection or z-step is changed in the napari viewer. To take
advantage of this sub-classes should implement the ``clear()`` and
``draw()`` methods.
Attributes
----------
viewer : `napari.Viewer`
Main napari viewer.
figure : `matplotlib.figure.Figure`
Matplotlib figure.
canvas : matplotlib.backends.backend_qt5agg.FigureCanvas
Matplotlib canvas.
layers : `list`
List of currently selected napari layers.
"""
def __init__(self, napari_viewer: napari.viewer.Viewer):
super().__init__()
self.viewer = napari_viewer
self.canvas = FigureCanvas()
self.canvas.figure.patch.set_facecolor(NAPARI_WINDOW_COLOR)
self.canvas.figure.set_layout_engine("constrained")
self.toolbar = NapariNavigationToolbar(self.canvas, self)
self._replace_toolbar_icons()
self.setLayout(QVBoxLayout())
self.layout().addWidget(self.toolbar)
self.layout().addWidget(self.canvas)
self.setup_callbacks()
self.layers: List[napari.layers.Layer] = []
# Accept any number of input layers by default
n_layers_input = Interval(None, None)
# Accept any type of input layer by default
input_layer_types: Tuple[napari.layers.Layer, ...] = (napari.layers.Layer,)
@property
def n_selected_layers(self) -> int:
"""
Number of currently selected layers.
"""
return len(self.layers)
@property
def current_z(self) -> int:
"""
Current z-step of the viewer.
"""
return self.viewer.dims.current_step[0]
def setup_callbacks(self) -> None:
"""
Sets up callbacks.
Sets up callbacks for:
- Layer selection changing
- z-step changing
"""
# z-step changed in viewer
self.viewer.dims.events.current_step.connect(self._draw)
# Layer selection changed in viewer
self.viewer.layers.selection.events.changed.connect(self.update_layers)
def update_layers(self, event: napari.utils.events.Event) -> None:
"""
Update the layers attribute with currently selected layers and re-draw.
"""
self.layers = list(self.viewer.layers.selection)
self._on_update_layers()
self._draw()
def _draw(self) -> None:
"""
Clear current figure, check selected layers are correct, and draw new
figure if so.
"""
self.clear()
if self.n_selected_layers in self.n_layers_input and all(
isinstance(layer, self.input_layer_types) for layer in self.layers
):
self.draw()
self.canvas.draw()
def clear(self) -> None:
"""
Clear any previously drawn figures.
This is a no-op, and is intended for derived classes to override.
"""
def draw(self) -> None:
"""
Re-draw any figures.
This is a no-op, and is intended for derived classes to override.
"""
def apply_napari_colorscheme(self):
"""
Apply napari-compatible colorscheme to the axes object.
"""
if self.axes is None:
return
# changing color of axes background to napari main window color
self.canvas.figure.patch.set_facecolor(NAPARI_WINDOW_COLOR)
# changing color of plot background to napari main window color
self.axes.set_facecolor(NAPARI_WINDOW_COLOR)
# changing colors of all axes
[
self.axes.spines[spine].set_color("white")
for spine in self.axes.spines
]
self.axes.xaxis.label.set_color("white")
self.axes.yaxis.label.set_color("white")
# changing colors of axes labels
self.axes.tick_params(axis="x", colors="white")
self.axes.tick_params(axis="y", colors="white")
def _on_update_layers(self) -> None:
"""
Function is called when self.layers is updated via
``self.update_layers()``.
This is a no-op, and is intended for derived classes to override.
"""
def _replace_toolbar_icons(self):
# Modify toolbar icons and some tooltips
for action in self.toolbar.actions():
text = action.text()
if text == "Pan":
action.setToolTip(
"Pan/Zoom: Left button pans; Right button zooms; "
"Click once to activate; Click again to deactivate"
)
if text == "Zoom":
action.setToolTip(
"Zoom to rectangle; Click once to activate; "
"Click again to deactivate"
)
if len(text) > 0: # i.e. not a separator item
icon_path = os.path.join(ICON_ROOT, text + ".png")
action.setIcon(QIcon(icon_path))
class NapariNavigationToolbar(NavigationToolbar2QT):
"""Custom Toolbar style for Napari."""
def _update_buttons_checked(self):
"""Update toggle tool icons when selected/unselected."""
super()._update_buttons_checked()
# changes pan/zoom icons depending on state (checked or not)
if "pan" in self._actions:
if self._actions["pan"].isChecked():
self._actions["pan"].setIcon(
QIcon(os.path.join(ICON_ROOT, "Pan_checked.png"))
)
else:
self._actions["pan"].setIcon(
QIcon(os.path.join(ICON_ROOT, "Pan.png"))
)
if "zoom" in self._actions:
if self._actions["zoom"].isChecked():
self._actions["zoom"].setIcon(
QIcon(os.path.join(ICON_ROOT, "Zoom_checked.png"))
)
else:
self._actions["zoom"].setIcon(
QIcon(os.path.join(ICON_ROOT, "Zoom.png"))
)