synapse_net.tools.base_widget

  1import os
  2import sys
  3from contextlib import contextmanager
  4from pathlib import Path
  5
  6import napari
  7import numpy as np
  8import qtpy.QtWidgets as QtWidgets
  9
 10from napari.utils.notifications import show_info
 11from qtpy.QtCore import Qt
 12from qtpy.QtWidgets import (
 13    QApplication, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QSpinBox, QComboBox, QCheckBox
 14)
 15from superqt import QCollapsible
 16
 17try:
 18    from napari_skimage_regionprops import add_table
 19except ImportError:
 20    add_table = None
 21
 22
 23class _SilencePrint:
 24    def __enter__(self):
 25        self._original_stdout = sys.stdout
 26        sys.stdout = open(os.devnull, "w")
 27
 28    def __exit__(self, exc_type, exc_val, exc_tb):
 29        sys.stdout.close()
 30        sys.stdout = self._original_stdout
 31
 32
 33class BaseWidget(QWidget):
 34    def __init__(self):
 35        super().__init__()
 36        self.viewer = napari.current_viewer()
 37        self.attribute_dict = {}
 38
 39    def _create_layer_selector(self, selector_name, layer_type="Image", prefer_substring=None):
 40        """Create a layer selector for an image or labels and store it in a dictionary.
 41
 42        Args:
 43            selector_name (str): The name of the selector, used as a key in the dictionary.
 44            layer_type (str): The type of layer to filter for ("Image" or "Labels").
 45            prefer_substring (str, optional): If given, the selector auto-defaults to the first
 46                layer whose name contains this substring (case-insensitive); falls back to the first
 47                layer otherwise. Applied only when there is no valid current selection (initial
 48                population or the selected layer was removed); a user's manual choice is preserved.
 49        """
 50        if not hasattr(self, "layer_selectors"):
 51            self.layer_selectors = {}
 52
 53        # Determine the annotation type for the widget
 54        if layer_type == "Image":
 55            layer_filter = napari.layers.Image
 56        elif layer_type == "Labels":
 57            layer_filter = napari.layers.Labels
 58        elif layer_type == "Shapes":
 59            layer_filter = napari.layers.Shapes
 60        else:
 61            raise ValueError("layer_type must be either 'Image' or 'Labels'.")
 62
 63        selector_widget = QtWidgets.QWidget()
 64        image_selector = QtWidgets.QComboBox()
 65        layer_label = QtWidgets.QLabel(f"{selector_name}:")
 66
 67        # Populate initial options
 68        self._update_selector(selector=image_selector, layer_filter=layer_filter, prefer_substring=prefer_substring)
 69
 70        # Update selector on layer events
 71        self.viewer.layers.events.inserted.connect(
 72            lambda event: self._update_selector(image_selector, layer_filter, prefer_substring)
 73        )
 74        self.viewer.layers.events.removed.connect(
 75            lambda event: self._update_selector(image_selector, layer_filter, prefer_substring)
 76        )
 77
 78        # Store the selector in the dictionary
 79        self.layer_selectors[selector_name] = selector_widget
 80
 81        # Set up layout
 82        layout = QVBoxLayout()
 83        layout.addWidget(layer_label)
 84        layout.addWidget(image_selector)
 85        selector_widget.setLayout(layout)
 86        return selector_widget
 87
 88    def _update_selector(self, selector, layer_filter, prefer_substring=None):
 89        """Update a single selector with the current image layers in the viewer.
 90
 91        The user's current selection is preserved if that layer still exists. Only when there is
 92        no valid current selection (initial population, or the selected layer was removed) does the
 93        default apply: the first layer whose name contains ``prefer_substring`` (case-insensitive)
 94        if given, otherwise the first layer (QComboBox default).
 95        """
 96        previous = selector.currentText()
 97        selector.clear()
 98        image_layers = [layer.name for layer in self.viewer.layers if isinstance(layer, layer_filter)]
 99        selector.addItems(image_layers)
100        if previous in image_layers:
101            selector.setCurrentText(previous)
102        elif prefer_substring:
103            needle = prefer_substring.lower()
104            match = next((name for name in image_layers if needle in name.lower()), None)
105            if match is not None:
106                selector.setCurrentText(match)
107
108    @contextmanager
109    def _computing(self, button, busy_text, idle_text, message):
110        """Show a busy state around a synchronous, GUI-thread-blocking action, then restore it.
111
112        Disables and relabels ``button``, sets a wait cursor, shows ``message`` and forces one repaint
113        so the busy state is painted *before* the blocking call — otherwise none of it would render
114        until the call returned and the button would just look stuck. The cursor, button label and
115        enabled state are restored on exit (also on error). Disabling the button also blocks a
116        re-entrant second click while the action is in flight. All Qt calls are guarded so they no-op
117        without a running QApplication.
118        """
119        app = QApplication.instance()
120        button.setEnabled(False)
121        button.setText(busy_text)
122        if app is not None:
123            QApplication.setOverrideCursor(Qt.WaitCursor)
124        show_info(message)
125        if app is not None:
126            app.processEvents()
127        try:
128            yield
129        finally:
130            if app is not None:
131                QApplication.restoreOverrideCursor()
132            button.setEnabled(True)
133            button.setText(idle_text)
134
135    def _get_layer_selector_layer(self, selector_name):
136        """Return the layer currently selected in a given selector."""
137        if selector_name in self.layer_selectors:
138            selector_widget = self.layer_selectors[selector_name]
139
140            # Retrieve the QComboBox from the QWidget's layout
141            image_selector = selector_widget.layout().itemAt(1).widget()
142
143            if isinstance(image_selector, QComboBox):
144                selected_layer_name = image_selector.currentText()
145                if selected_layer_name in self.viewer.layers:
146                    return self.viewer.layers[selected_layer_name]
147        return None  # Return None if layer not found
148
149    def _get_layer_selector_data(self, selector_name, return_metadata=False):
150        """Return the data for the layer currently selected in a given selector."""
151        if selector_name in self.layer_selectors:
152            selector_widget = self.layer_selectors[selector_name]
153
154            # Retrieve the QComboBox from the QWidget's layout
155            image_selector = selector_widget.layout().itemAt(1).widget()
156
157            if isinstance(image_selector, QComboBox):
158                selected_layer_name = image_selector.currentText()
159                if selected_layer_name in self.viewer.layers:
160                    layer = self.viewer.layers[selected_layer_name]
161                    if return_metadata:
162                        return layer.metadata
163                    # Lazy (dask / zarr) data is loaded into memory; multiscale data uses the full resolution.
164                    if isinstance(layer, (napari.layers.Image, napari.layers.Labels)):
165                        return np.asarray(layer.data[0] if layer.multiscale else layer.data)
166                    return layer.data
167        return None  # Return None if layer not found
168
169    def _add_string_param(self, name, value, title=None, placeholder=None, layout=None, tooltip=None):
170        if layout is None:
171            layout = QtWidgets.QHBoxLayout()
172        label = QtWidgets.QLabel(title or name)
173        if tooltip:
174            label.setToolTip(tooltip)
175        layout.addWidget(label)
176        param = QtWidgets.QLineEdit()
177        param.setText(value)
178        if placeholder is not None:
179            param.setPlaceholderText(placeholder)
180        param.textChanged.connect(lambda val: setattr(self, name, val))
181        if tooltip:
182            param.setToolTip(tooltip)
183        layout.addWidget(param)
184        return param, layout
185
186    def _add_float_param(self, name, value, title=None, min_val=0.0, max_val=1.0, decimals=2,
187                         step=0.01, layout=None, tooltip=None):
188        if layout is None:
189            layout = QtWidgets.QHBoxLayout()
190        label = QtWidgets.QLabel(title or name)
191        if tooltip:
192            label.setToolTip(tooltip)
193        layout.addWidget(label)
194        param = QtWidgets.QDoubleSpinBox()
195        param.setRange(min_val, max_val)
196        param.setDecimals(decimals)
197        param.setValue(value)
198        param.setSingleStep(step)
199        param.valueChanged.connect(lambda val: setattr(self, name, val))
200        if tooltip:
201            param.setToolTip(tooltip)
202        layout.addWidget(param)
203        return param, layout
204
205    def _add_int_param(self, name, value, min_val, max_val, title=None, step=1, layout=None, tooltip=None):
206        if layout is None:
207            layout = QHBoxLayout()
208        label = QLabel(title or name)
209        if tooltip:
210            label.setToolTip(tooltip)
211        layout.addWidget(label)
212        param = QSpinBox()
213        param.setRange(min_val, max_val)
214        param.setValue(value)
215        param.setSingleStep(step)
216        param.valueChanged.connect(lambda val: setattr(self, name, val))
217        if tooltip:
218            param.setToolTip(tooltip)
219        layout.addWidget(param)
220        return param, layout
221
222    def _add_choice_param(self, name, value, options, title=None, layout=None, update=None, tooltip=None):
223        if layout is None:
224            layout = QHBoxLayout()
225        label = QLabel(title or name)
226        if tooltip:
227            label.setToolTip(tooltip)
228        layout.addWidget(label)
229
230        # Create the dropdown menu via QComboBox, set the available values.
231        dropdown = QComboBox()
232        dropdown.addItems(options)
233        if update is None:
234            dropdown.currentIndexChanged.connect(lambda index: setattr(self, name, options[index]))
235        else:
236            dropdown.currentIndexChanged.connect(update)
237
238        # Set the correct value for the value.
239        dropdown.setCurrentIndex(dropdown.findText(value))
240
241        if tooltip:
242            dropdown.setToolTip(tooltip)
243
244        layout.addWidget(dropdown)
245        return dropdown, layout
246
247    def _add_shape_param(self, names, values, min_val, max_val, step=1, title=None, tooltip=None):
248        layout = QHBoxLayout()
249
250        x_layout = QVBoxLayout()
251        x_param, _ = self._add_int_param(
252            names[0], values[0], min_val=min_val, max_val=max_val, layout=x_layout, step=step,
253            title=title[0] if title is not None else title, tooltip=tooltip
254        )
255        layout.addLayout(x_layout)
256
257        y_layout = QVBoxLayout()
258        y_param, _ = self._add_int_param(
259            names[1], values[1], min_val=min_val, max_val=max_val, layout=y_layout, step=step,
260            title=title[1] if title is not None else title, tooltip=tooltip
261        )
262        layout.addLayout(y_layout)
263
264        if len(names) == 3:
265            z_layout = QVBoxLayout()
266            z_param, _ = self._add_int_param(
267                names[2], values[2], min_val=min_val, max_val=max_val, layout=z_layout, step=step,
268                title=title[2] if title is not None else title, tooltip=tooltip
269            )
270            layout.addLayout(z_layout)
271            return x_param, y_param, z_param, layout
272
273        return x_param, y_param, layout
274
275    def _make_collapsible(self, widget, title):
276        parent_widget = QWidget()
277        parent_widget.setLayout(QVBoxLayout())
278        collapsible = QCollapsible(title, parent_widget)
279        collapsible.addWidget(widget)
280        parent_widget.layout().addWidget(collapsible)
281        return parent_widget
282
283    def _add_boolean_param(self, name, value, title=None, tooltip=None):
284        checkbox = QCheckBox(name if title is None else title)
285        checkbox.setChecked(value)
286        checkbox.stateChanged.connect(lambda val: setattr(self, name, val))
287        if tooltip:
288            checkbox.setToolTip(tooltip)
289        return checkbox
290
291    def _add_path_param(self, name, value, select_type, title=None, placeholder=None, tooltip=None):
292        assert select_type in ("directory", "file", "both")
293
294        layout = QtWidgets.QHBoxLayout()
295        label = QtWidgets.QLabel(title or name)
296        if tooltip:
297            label.setToolTip(tooltip)
298        layout.addWidget(label)
299
300        path_textbox = QtWidgets.QLineEdit()
301        path_textbox.setText(str(value))
302        if placeholder is not None:
303            path_textbox.setPlaceholderText(placeholder)
304        path_textbox.textChanged.connect(lambda val: setattr(self, name, val))
305        if tooltip:
306            path_textbox.setToolTip(tooltip)
307
308        layout.addWidget(path_textbox)
309
310        def add_path_button(select_type, tooltip=None):
311            # Adjust button text.
312            button_text = f"Select {select_type.capitalize()}"
313            path_button = QtWidgets.QPushButton(button_text)
314
315            # Call appropriate function based on select_type.
316            path_button.clicked.connect(lambda: getattr(self, f"_get_{select_type}_path")(name, path_textbox))
317            if tooltip:
318                path_button.setToolTip(tooltip)
319            layout.addWidget(path_button)
320
321        if select_type == "both":
322            add_path_button("file")
323            add_path_button("directory")
324
325        else:
326            add_path_button(select_type)
327
328        return path_textbox, layout
329
330    def _get_directory_path(self, name, textbox, tooltip=None):
331        directory = QtWidgets.QFileDialog.getExistingDirectory(
332            self, "Select Directory", "", QtWidgets.QFileDialog.ShowDirsOnly
333        )
334        if tooltip:
335            directory.setToolTip(tooltip)
336        if directory and Path(directory).is_dir():
337            textbox.setText(str(directory))
338        else:
339            # Handle the case where the selected path is not a directory
340            print("Invalid directory selected. Please try again.")
341
342    def _get_file_path(self, name, textbox, tooltip=None):
343        file_path, _ = QtWidgets.QFileDialog.getOpenFileName(
344            self, "Select File", "", "All Files (*)"
345        )
346        if tooltip:
347            file_path.setToolTip(tooltip)
348        if file_path and Path(file_path).is_file():
349            textbox.setText(str(file_path))
350        else:
351            # Handle the case where the selected path is not a file
352            print("Invalid file selected. Please try again.")
353
354    def _handle_resolution(self, metadata, voxel_size_param, ndim, return_as_list=True):
355        # Get the resolution / voxel size from the layer metadata if available.
356        resolution = metadata.get("voxel_size", None)
357
358        # If user input was given then override resolution from metadata.
359        axes = "zyx" if ndim == 3 else "yx"
360        if voxel_size_param.value() != 0.0:  # Changed from default.
361            resolution = {ax: voxel_size_param.value() for ax in axes}
362
363        if resolution is not None and return_as_list:
364            resolution = [resolution[ax] for ax in axes]
365            assert len(resolution) == ndim
366
367        return resolution
368
369    def _save_table(self, save_path, data):
370        ext = os.path.splitext(save_path)[1]
371        if ext == "":  # No file extension given, By default we save to CSV.
372            file_path = f"{save_path}.csv"
373            data.to_csv(file_path, index=False)
374        elif ext == ".csv":  # Extension was specified as csv
375            file_path = save_path
376            data.to_csv(file_path, index=False)
377        elif ext == ".xlsx":  # We also support excel.
378            file_path = save_path
379            data.to_excel(file_path, index=False)
380        else:
381            raise ValueError(f"Invalid extension for table: {ext}. We support .csv or .xlsx.")
382        return file_path
383
384    def _add_properties_and_table(self, layer, table_data, save_path=""):
385        layer.properties = table_data
386
387        if add_table is not None:
388            with _SilencePrint():
389                add_table(layer, self.viewer)
390
391        # Save table to file if save path is provided.
392        if save_path != "":
393            file_path = self._save_table(save_path, table_data)
394            show_info(f"INFO: Added table and saved file to {file_path}.")
395
396    def _add_or_update_layer(self, add_fn, name, data, scale, translate, layer_kwargs):
397        """Add a layer via ``add_fn`` (e.g. ``self.viewer.add_labels``), or refresh it in place if a
398        layer with this name already exists.
399
400        On refresh the ``scale``/``translate`` are reapplied (when provided) because a persisted layer
401        keeps its original transform, which may be stale if the source layer / voxel size changed
402        between runs; any ``layer_kwargs`` (e.g. ``opacity``, ``blending``, ``colormap``) are reapplied
403        too. On first add these go through the layer constructor. Returns the (new or existing) layer.
404
405        A layer of a *different* type carrying this name is replaced rather than refreshed: assigning
406        e.g. an (n, 2, ndim) vectors array to a Points layer left over from an earlier run would raise
407        deep inside napari.
408        """
409        if name in self.viewer.layers:
410            expected = f"add_{type(self.viewer.layers[name]).__name__.lower()}"
411            if getattr(add_fn, "__name__", expected) != expected:
412                del self.viewer.layers[name]
413        if name in self.viewer.layers:
414            layer = self.viewer.layers[name]
415            layer.data = data
416            if scale is not None:
417                layer.scale = scale
418            if translate is not None:
419                layer.translate = translate
420            for key, value in layer_kwargs.items():
421                setattr(layer, key, value)
422        else:
423            ctor_kwargs = dict(layer_kwargs)
424            if scale is not None:
425                ctor_kwargs["scale"] = scale
426            if translate is not None:
427                ctor_kwargs["translate"] = translate
428            layer = add_fn(data, name=name, **ctor_kwargs)
429        return layer
430
431    def add_or_update_labels(self, name, data, *, scale=None, translate=None, **layer_kwargs):
432        """Add a Labels layer, or refresh it in place if one with this name already exists.
433
434        See :meth:`_add_or_update_layer` for the refresh/transform semantics. Extra keyword arguments
435        (``opacity``, ``blending``, ``colormap``, …) are forwarded to the layer. Returns the layer.
436        """
437        return self._add_or_update_layer(
438            self.viewer.add_labels, name, data, scale, translate, layer_kwargs
439        )
440
441    def add_or_update_surface(self, name, vertices, faces, *, scale=None, translate=None,
442                              values=None, **layer_kwargs):
443        """Add a Surface layer, or refresh it in place if one with this name already exists.
444
445        Surface layers colour by per-vertex ``values``; a constant array (the default) gives a
446        flat-coloured surface. See :meth:`_add_or_update_layer` for the refresh/transform semantics.
447        Returns the layer.
448        """
449        if values is None:
450            values = np.ones(len(vertices), dtype="float32")
451        return self._add_or_update_layer(
452            self.viewer.add_surface, name, (vertices, faces, values), scale, translate, layer_kwargs
453        )
454
455    def add_or_update_points(self, name, points, *, scale=None, translate=None, **layer_kwargs):
456        """Add a Points layer, or refresh it in place if one with this name already exists.
457
458        ``points`` is an (n, ndim) array in the same coordinate frame as the other layers — i.e. voxel
459        indices, with the physical placement left to ``scale``/``translate``. See
460        :meth:`_add_or_update_layer` for the refresh/transform semantics. Returns the layer.
461
462        For line-like data such as a skeleton, use :meth:`add_or_update_vectors` rather than Shapes: a
463        Shapes layer needs ``shape_type``, which is a constructor-only argument and so cannot be
464        reapplied on the refresh path, and thousands of individual line shapes render slowly.
465        """
466        return self._add_or_update_layer(
467            self.viewer.add_points, name, points, scale, translate, layer_kwargs
468        )
469
470    def add_or_update_vectors(self, name, vectors, *, scale=None, translate=None, **layer_kwargs):
471        """Add a Vectors layer, or refresh it in place if one with this name already exists.
472
473        ``vectors`` is an (n, 2, ndim) array of ``[start, direction]`` pairs, in the same coordinate
474        frame as the other layers — i.e. voxel indices, with the physical placement left to
475        ``scale``/``translate``. This is the layer to use for the edges of a graph such as a skeleton:
476        one instanced segment per edge, no constructor-only ``shape_type`` to reapply, and it stays
477        responsive at edge counts where a Shapes layer does not. See :meth:`_add_or_update_layer` for
478        the refresh/transform semantics. Returns the layer.
479        """
480        return self._add_or_update_layer(
481            self.viewer.add_vectors, name, vectors, scale, translate, layer_kwargs
482        )
class BaseWidget(PyQt5.QtWidgets.QWidget):
 34class BaseWidget(QWidget):
 35    def __init__(self):
 36        super().__init__()
 37        self.viewer = napari.current_viewer()
 38        self.attribute_dict = {}
 39
 40    def _create_layer_selector(self, selector_name, layer_type="Image", prefer_substring=None):
 41        """Create a layer selector for an image or labels and store it in a dictionary.
 42
 43        Args:
 44            selector_name (str): The name of the selector, used as a key in the dictionary.
 45            layer_type (str): The type of layer to filter for ("Image" or "Labels").
 46            prefer_substring (str, optional): If given, the selector auto-defaults to the first
 47                layer whose name contains this substring (case-insensitive); falls back to the first
 48                layer otherwise. Applied only when there is no valid current selection (initial
 49                population or the selected layer was removed); a user's manual choice is preserved.
 50        """
 51        if not hasattr(self, "layer_selectors"):
 52            self.layer_selectors = {}
 53
 54        # Determine the annotation type for the widget
 55        if layer_type == "Image":
 56            layer_filter = napari.layers.Image
 57        elif layer_type == "Labels":
 58            layer_filter = napari.layers.Labels
 59        elif layer_type == "Shapes":
 60            layer_filter = napari.layers.Shapes
 61        else:
 62            raise ValueError("layer_type must be either 'Image' or 'Labels'.")
 63
 64        selector_widget = QtWidgets.QWidget()
 65        image_selector = QtWidgets.QComboBox()
 66        layer_label = QtWidgets.QLabel(f"{selector_name}:")
 67
 68        # Populate initial options
 69        self._update_selector(selector=image_selector, layer_filter=layer_filter, prefer_substring=prefer_substring)
 70
 71        # Update selector on layer events
 72        self.viewer.layers.events.inserted.connect(
 73            lambda event: self._update_selector(image_selector, layer_filter, prefer_substring)
 74        )
 75        self.viewer.layers.events.removed.connect(
 76            lambda event: self._update_selector(image_selector, layer_filter, prefer_substring)
 77        )
 78
 79        # Store the selector in the dictionary
 80        self.layer_selectors[selector_name] = selector_widget
 81
 82        # Set up layout
 83        layout = QVBoxLayout()
 84        layout.addWidget(layer_label)
 85        layout.addWidget(image_selector)
 86        selector_widget.setLayout(layout)
 87        return selector_widget
 88
 89    def _update_selector(self, selector, layer_filter, prefer_substring=None):
 90        """Update a single selector with the current image layers in the viewer.
 91
 92        The user's current selection is preserved if that layer still exists. Only when there is
 93        no valid current selection (initial population, or the selected layer was removed) does the
 94        default apply: the first layer whose name contains ``prefer_substring`` (case-insensitive)
 95        if given, otherwise the first layer (QComboBox default).
 96        """
 97        previous = selector.currentText()
 98        selector.clear()
 99        image_layers = [layer.name for layer in self.viewer.layers if isinstance(layer, layer_filter)]
100        selector.addItems(image_layers)
101        if previous in image_layers:
102            selector.setCurrentText(previous)
103        elif prefer_substring:
104            needle = prefer_substring.lower()
105            match = next((name for name in image_layers if needle in name.lower()), None)
106            if match is not None:
107                selector.setCurrentText(match)
108
109    @contextmanager
110    def _computing(self, button, busy_text, idle_text, message):
111        """Show a busy state around a synchronous, GUI-thread-blocking action, then restore it.
112
113        Disables and relabels ``button``, sets a wait cursor, shows ``message`` and forces one repaint
114        so the busy state is painted *before* the blocking call — otherwise none of it would render
115        until the call returned and the button would just look stuck. The cursor, button label and
116        enabled state are restored on exit (also on error). Disabling the button also blocks a
117        re-entrant second click while the action is in flight. All Qt calls are guarded so they no-op
118        without a running QApplication.
119        """
120        app = QApplication.instance()
121        button.setEnabled(False)
122        button.setText(busy_text)
123        if app is not None:
124            QApplication.setOverrideCursor(Qt.WaitCursor)
125        show_info(message)
126        if app is not None:
127            app.processEvents()
128        try:
129            yield
130        finally:
131            if app is not None:
132                QApplication.restoreOverrideCursor()
133            button.setEnabled(True)
134            button.setText(idle_text)
135
136    def _get_layer_selector_layer(self, selector_name):
137        """Return the layer currently selected in a given selector."""
138        if selector_name in self.layer_selectors:
139            selector_widget = self.layer_selectors[selector_name]
140
141            # Retrieve the QComboBox from the QWidget's layout
142            image_selector = selector_widget.layout().itemAt(1).widget()
143
144            if isinstance(image_selector, QComboBox):
145                selected_layer_name = image_selector.currentText()
146                if selected_layer_name in self.viewer.layers:
147                    return self.viewer.layers[selected_layer_name]
148        return None  # Return None if layer not found
149
150    def _get_layer_selector_data(self, selector_name, return_metadata=False):
151        """Return the data for the layer currently selected in a given selector."""
152        if selector_name in self.layer_selectors:
153            selector_widget = self.layer_selectors[selector_name]
154
155            # Retrieve the QComboBox from the QWidget's layout
156            image_selector = selector_widget.layout().itemAt(1).widget()
157
158            if isinstance(image_selector, QComboBox):
159                selected_layer_name = image_selector.currentText()
160                if selected_layer_name in self.viewer.layers:
161                    layer = self.viewer.layers[selected_layer_name]
162                    if return_metadata:
163                        return layer.metadata
164                    # Lazy (dask / zarr) data is loaded into memory; multiscale data uses the full resolution.
165                    if isinstance(layer, (napari.layers.Image, napari.layers.Labels)):
166                        return np.asarray(layer.data[0] if layer.multiscale else layer.data)
167                    return layer.data
168        return None  # Return None if layer not found
169
170    def _add_string_param(self, name, value, title=None, placeholder=None, layout=None, tooltip=None):
171        if layout is None:
172            layout = QtWidgets.QHBoxLayout()
173        label = QtWidgets.QLabel(title or name)
174        if tooltip:
175            label.setToolTip(tooltip)
176        layout.addWidget(label)
177        param = QtWidgets.QLineEdit()
178        param.setText(value)
179        if placeholder is not None:
180            param.setPlaceholderText(placeholder)
181        param.textChanged.connect(lambda val: setattr(self, name, val))
182        if tooltip:
183            param.setToolTip(tooltip)
184        layout.addWidget(param)
185        return param, layout
186
187    def _add_float_param(self, name, value, title=None, min_val=0.0, max_val=1.0, decimals=2,
188                         step=0.01, layout=None, tooltip=None):
189        if layout is None:
190            layout = QtWidgets.QHBoxLayout()
191        label = QtWidgets.QLabel(title or name)
192        if tooltip:
193            label.setToolTip(tooltip)
194        layout.addWidget(label)
195        param = QtWidgets.QDoubleSpinBox()
196        param.setRange(min_val, max_val)
197        param.setDecimals(decimals)
198        param.setValue(value)
199        param.setSingleStep(step)
200        param.valueChanged.connect(lambda val: setattr(self, name, val))
201        if tooltip:
202            param.setToolTip(tooltip)
203        layout.addWidget(param)
204        return param, layout
205
206    def _add_int_param(self, name, value, min_val, max_val, title=None, step=1, layout=None, tooltip=None):
207        if layout is None:
208            layout = QHBoxLayout()
209        label = QLabel(title or name)
210        if tooltip:
211            label.setToolTip(tooltip)
212        layout.addWidget(label)
213        param = QSpinBox()
214        param.setRange(min_val, max_val)
215        param.setValue(value)
216        param.setSingleStep(step)
217        param.valueChanged.connect(lambda val: setattr(self, name, val))
218        if tooltip:
219            param.setToolTip(tooltip)
220        layout.addWidget(param)
221        return param, layout
222
223    def _add_choice_param(self, name, value, options, title=None, layout=None, update=None, tooltip=None):
224        if layout is None:
225            layout = QHBoxLayout()
226        label = QLabel(title or name)
227        if tooltip:
228            label.setToolTip(tooltip)
229        layout.addWidget(label)
230
231        # Create the dropdown menu via QComboBox, set the available values.
232        dropdown = QComboBox()
233        dropdown.addItems(options)
234        if update is None:
235            dropdown.currentIndexChanged.connect(lambda index: setattr(self, name, options[index]))
236        else:
237            dropdown.currentIndexChanged.connect(update)
238
239        # Set the correct value for the value.
240        dropdown.setCurrentIndex(dropdown.findText(value))
241
242        if tooltip:
243            dropdown.setToolTip(tooltip)
244
245        layout.addWidget(dropdown)
246        return dropdown, layout
247
248    def _add_shape_param(self, names, values, min_val, max_val, step=1, title=None, tooltip=None):
249        layout = QHBoxLayout()
250
251        x_layout = QVBoxLayout()
252        x_param, _ = self._add_int_param(
253            names[0], values[0], min_val=min_val, max_val=max_val, layout=x_layout, step=step,
254            title=title[0] if title is not None else title, tooltip=tooltip
255        )
256        layout.addLayout(x_layout)
257
258        y_layout = QVBoxLayout()
259        y_param, _ = self._add_int_param(
260            names[1], values[1], min_val=min_val, max_val=max_val, layout=y_layout, step=step,
261            title=title[1] if title is not None else title, tooltip=tooltip
262        )
263        layout.addLayout(y_layout)
264
265        if len(names) == 3:
266            z_layout = QVBoxLayout()
267            z_param, _ = self._add_int_param(
268                names[2], values[2], min_val=min_val, max_val=max_val, layout=z_layout, step=step,
269                title=title[2] if title is not None else title, tooltip=tooltip
270            )
271            layout.addLayout(z_layout)
272            return x_param, y_param, z_param, layout
273
274        return x_param, y_param, layout
275
276    def _make_collapsible(self, widget, title):
277        parent_widget = QWidget()
278        parent_widget.setLayout(QVBoxLayout())
279        collapsible = QCollapsible(title, parent_widget)
280        collapsible.addWidget(widget)
281        parent_widget.layout().addWidget(collapsible)
282        return parent_widget
283
284    def _add_boolean_param(self, name, value, title=None, tooltip=None):
285        checkbox = QCheckBox(name if title is None else title)
286        checkbox.setChecked(value)
287        checkbox.stateChanged.connect(lambda val: setattr(self, name, val))
288        if tooltip:
289            checkbox.setToolTip(tooltip)
290        return checkbox
291
292    def _add_path_param(self, name, value, select_type, title=None, placeholder=None, tooltip=None):
293        assert select_type in ("directory", "file", "both")
294
295        layout = QtWidgets.QHBoxLayout()
296        label = QtWidgets.QLabel(title or name)
297        if tooltip:
298            label.setToolTip(tooltip)
299        layout.addWidget(label)
300
301        path_textbox = QtWidgets.QLineEdit()
302        path_textbox.setText(str(value))
303        if placeholder is not None:
304            path_textbox.setPlaceholderText(placeholder)
305        path_textbox.textChanged.connect(lambda val: setattr(self, name, val))
306        if tooltip:
307            path_textbox.setToolTip(tooltip)
308
309        layout.addWidget(path_textbox)
310
311        def add_path_button(select_type, tooltip=None):
312            # Adjust button text.
313            button_text = f"Select {select_type.capitalize()}"
314            path_button = QtWidgets.QPushButton(button_text)
315
316            # Call appropriate function based on select_type.
317            path_button.clicked.connect(lambda: getattr(self, f"_get_{select_type}_path")(name, path_textbox))
318            if tooltip:
319                path_button.setToolTip(tooltip)
320            layout.addWidget(path_button)
321
322        if select_type == "both":
323            add_path_button("file")
324            add_path_button("directory")
325
326        else:
327            add_path_button(select_type)
328
329        return path_textbox, layout
330
331    def _get_directory_path(self, name, textbox, tooltip=None):
332        directory = QtWidgets.QFileDialog.getExistingDirectory(
333            self, "Select Directory", "", QtWidgets.QFileDialog.ShowDirsOnly
334        )
335        if tooltip:
336            directory.setToolTip(tooltip)
337        if directory and Path(directory).is_dir():
338            textbox.setText(str(directory))
339        else:
340            # Handle the case where the selected path is not a directory
341            print("Invalid directory selected. Please try again.")
342
343    def _get_file_path(self, name, textbox, tooltip=None):
344        file_path, _ = QtWidgets.QFileDialog.getOpenFileName(
345            self, "Select File", "", "All Files (*)"
346        )
347        if tooltip:
348            file_path.setToolTip(tooltip)
349        if file_path and Path(file_path).is_file():
350            textbox.setText(str(file_path))
351        else:
352            # Handle the case where the selected path is not a file
353            print("Invalid file selected. Please try again.")
354
355    def _handle_resolution(self, metadata, voxel_size_param, ndim, return_as_list=True):
356        # Get the resolution / voxel size from the layer metadata if available.
357        resolution = metadata.get("voxel_size", None)
358
359        # If user input was given then override resolution from metadata.
360        axes = "zyx" if ndim == 3 else "yx"
361        if voxel_size_param.value() != 0.0:  # Changed from default.
362            resolution = {ax: voxel_size_param.value() for ax in axes}
363
364        if resolution is not None and return_as_list:
365            resolution = [resolution[ax] for ax in axes]
366            assert len(resolution) == ndim
367
368        return resolution
369
370    def _save_table(self, save_path, data):
371        ext = os.path.splitext(save_path)[1]
372        if ext == "":  # No file extension given, By default we save to CSV.
373            file_path = f"{save_path}.csv"
374            data.to_csv(file_path, index=False)
375        elif ext == ".csv":  # Extension was specified as csv
376            file_path = save_path
377            data.to_csv(file_path, index=False)
378        elif ext == ".xlsx":  # We also support excel.
379            file_path = save_path
380            data.to_excel(file_path, index=False)
381        else:
382            raise ValueError(f"Invalid extension for table: {ext}. We support .csv or .xlsx.")
383        return file_path
384
385    def _add_properties_and_table(self, layer, table_data, save_path=""):
386        layer.properties = table_data
387
388        if add_table is not None:
389            with _SilencePrint():
390                add_table(layer, self.viewer)
391
392        # Save table to file if save path is provided.
393        if save_path != "":
394            file_path = self._save_table(save_path, table_data)
395            show_info(f"INFO: Added table and saved file to {file_path}.")
396
397    def _add_or_update_layer(self, add_fn, name, data, scale, translate, layer_kwargs):
398        """Add a layer via ``add_fn`` (e.g. ``self.viewer.add_labels``), or refresh it in place if a
399        layer with this name already exists.
400
401        On refresh the ``scale``/``translate`` are reapplied (when provided) because a persisted layer
402        keeps its original transform, which may be stale if the source layer / voxel size changed
403        between runs; any ``layer_kwargs`` (e.g. ``opacity``, ``blending``, ``colormap``) are reapplied
404        too. On first add these go through the layer constructor. Returns the (new or existing) layer.
405
406        A layer of a *different* type carrying this name is replaced rather than refreshed: assigning
407        e.g. an (n, 2, ndim) vectors array to a Points layer left over from an earlier run would raise
408        deep inside napari.
409        """
410        if name in self.viewer.layers:
411            expected = f"add_{type(self.viewer.layers[name]).__name__.lower()}"
412            if getattr(add_fn, "__name__", expected) != expected:
413                del self.viewer.layers[name]
414        if name in self.viewer.layers:
415            layer = self.viewer.layers[name]
416            layer.data = data
417            if scale is not None:
418                layer.scale = scale
419            if translate is not None:
420                layer.translate = translate
421            for key, value in layer_kwargs.items():
422                setattr(layer, key, value)
423        else:
424            ctor_kwargs = dict(layer_kwargs)
425            if scale is not None:
426                ctor_kwargs["scale"] = scale
427            if translate is not None:
428                ctor_kwargs["translate"] = translate
429            layer = add_fn(data, name=name, **ctor_kwargs)
430        return layer
431
432    def add_or_update_labels(self, name, data, *, scale=None, translate=None, **layer_kwargs):
433        """Add a Labels layer, or refresh it in place if one with this name already exists.
434
435        See :meth:`_add_or_update_layer` for the refresh/transform semantics. Extra keyword arguments
436        (``opacity``, ``blending``, ``colormap``, …) are forwarded to the layer. Returns the layer.
437        """
438        return self._add_or_update_layer(
439            self.viewer.add_labels, name, data, scale, translate, layer_kwargs
440        )
441
442    def add_or_update_surface(self, name, vertices, faces, *, scale=None, translate=None,
443                              values=None, **layer_kwargs):
444        """Add a Surface layer, or refresh it in place if one with this name already exists.
445
446        Surface layers colour by per-vertex ``values``; a constant array (the default) gives a
447        flat-coloured surface. See :meth:`_add_or_update_layer` for the refresh/transform semantics.
448        Returns the layer.
449        """
450        if values is None:
451            values = np.ones(len(vertices), dtype="float32")
452        return self._add_or_update_layer(
453            self.viewer.add_surface, name, (vertices, faces, values), scale, translate, layer_kwargs
454        )
455
456    def add_or_update_points(self, name, points, *, scale=None, translate=None, **layer_kwargs):
457        """Add a Points layer, or refresh it in place if one with this name already exists.
458
459        ``points`` is an (n, ndim) array in the same coordinate frame as the other layers — i.e. voxel
460        indices, with the physical placement left to ``scale``/``translate``. See
461        :meth:`_add_or_update_layer` for the refresh/transform semantics. Returns the layer.
462
463        For line-like data such as a skeleton, use :meth:`add_or_update_vectors` rather than Shapes: a
464        Shapes layer needs ``shape_type``, which is a constructor-only argument and so cannot be
465        reapplied on the refresh path, and thousands of individual line shapes render slowly.
466        """
467        return self._add_or_update_layer(
468            self.viewer.add_points, name, points, scale, translate, layer_kwargs
469        )
470
471    def add_or_update_vectors(self, name, vectors, *, scale=None, translate=None, **layer_kwargs):
472        """Add a Vectors layer, or refresh it in place if one with this name already exists.
473
474        ``vectors`` is an (n, 2, ndim) array of ``[start, direction]`` pairs, in the same coordinate
475        frame as the other layers — i.e. voxel indices, with the physical placement left to
476        ``scale``/``translate``. This is the layer to use for the edges of a graph such as a skeleton:
477        one instanced segment per edge, no constructor-only ``shape_type`` to reapply, and it stays
478        responsive at edge counts where a Shapes layer does not. See :meth:`_add_or_update_layer` for
479        the refresh/transform semantics. Returns the layer.
480        """
481        return self._add_or_update_layer(
482            self.viewer.add_vectors, name, vectors, scale, translate, layer_kwargs
483        )

QWidget(parent: Optional[QWidget] = None, flags: Union[Qt.WindowFlags, Qt.WindowType] = Qt.WindowFlags())

viewer
attribute_dict
def add_or_update_labels(self, name, data, *, scale=None, translate=None, **layer_kwargs):
432    def add_or_update_labels(self, name, data, *, scale=None, translate=None, **layer_kwargs):
433        """Add a Labels layer, or refresh it in place if one with this name already exists.
434
435        See :meth:`_add_or_update_layer` for the refresh/transform semantics. Extra keyword arguments
436        (``opacity``, ``blending``, ``colormap``, …) are forwarded to the layer. Returns the layer.
437        """
438        return self._add_or_update_layer(
439            self.viewer.add_labels, name, data, scale, translate, layer_kwargs
440        )

Add a Labels layer, or refresh it in place if one with this name already exists.

See _add_or_update_layer() for the refresh/transform semantics. Extra keyword arguments (opacity, blending, colormap, …) are forwarded to the layer. Returns the layer.

def add_or_update_surface( self, name, vertices, faces, *, scale=None, translate=None, values=None, **layer_kwargs):
442    def add_or_update_surface(self, name, vertices, faces, *, scale=None, translate=None,
443                              values=None, **layer_kwargs):
444        """Add a Surface layer, or refresh it in place if one with this name already exists.
445
446        Surface layers colour by per-vertex ``values``; a constant array (the default) gives a
447        flat-coloured surface. See :meth:`_add_or_update_layer` for the refresh/transform semantics.
448        Returns the layer.
449        """
450        if values is None:
451            values = np.ones(len(vertices), dtype="float32")
452        return self._add_or_update_layer(
453            self.viewer.add_surface, name, (vertices, faces, values), scale, translate, layer_kwargs
454        )

Add a Surface layer, or refresh it in place if one with this name already exists.

Surface layers colour by per-vertex values; a constant array (the default) gives a flat-coloured surface. See _add_or_update_layer() for the refresh/transform semantics. Returns the layer.

def add_or_update_points(self, name, points, *, scale=None, translate=None, **layer_kwargs):
456    def add_or_update_points(self, name, points, *, scale=None, translate=None, **layer_kwargs):
457        """Add a Points layer, or refresh it in place if one with this name already exists.
458
459        ``points`` is an (n, ndim) array in the same coordinate frame as the other layers — i.e. voxel
460        indices, with the physical placement left to ``scale``/``translate``. See
461        :meth:`_add_or_update_layer` for the refresh/transform semantics. Returns the layer.
462
463        For line-like data such as a skeleton, use :meth:`add_or_update_vectors` rather than Shapes: a
464        Shapes layer needs ``shape_type``, which is a constructor-only argument and so cannot be
465        reapplied on the refresh path, and thousands of individual line shapes render slowly.
466        """
467        return self._add_or_update_layer(
468            self.viewer.add_points, name, points, scale, translate, layer_kwargs
469        )

Add a Points layer, or refresh it in place if one with this name already exists.

points is an (n, ndim) array in the same coordinate frame as the other layers — i.e. voxel indices, with the physical placement left to scale/translate. See _add_or_update_layer() for the refresh/transform semantics. Returns the layer.

For line-like data such as a skeleton, use add_or_update_vectors() rather than Shapes: a Shapes layer needs shape_type, which is a constructor-only argument and so cannot be reapplied on the refresh path, and thousands of individual line shapes render slowly.

def add_or_update_vectors(self, name, vectors, *, scale=None, translate=None, **layer_kwargs):
471    def add_or_update_vectors(self, name, vectors, *, scale=None, translate=None, **layer_kwargs):
472        """Add a Vectors layer, or refresh it in place if one with this name already exists.
473
474        ``vectors`` is an (n, 2, ndim) array of ``[start, direction]`` pairs, in the same coordinate
475        frame as the other layers — i.e. voxel indices, with the physical placement left to
476        ``scale``/``translate``. This is the layer to use for the edges of a graph such as a skeleton:
477        one instanced segment per edge, no constructor-only ``shape_type`` to reapply, and it stays
478        responsive at edge counts where a Shapes layer does not. See :meth:`_add_or_update_layer` for
479        the refresh/transform semantics. Returns the layer.
480        """
481        return self._add_or_update_layer(
482            self.viewer.add_vectors, name, vectors, scale, translate, layer_kwargs
483        )

Add a Vectors layer, or refresh it in place if one with this name already exists.

vectors is an (n, 2, ndim) array of [start, direction] pairs, in the same coordinate frame as the other layers — i.e. voxel indices, with the physical placement left to scale/translate. This is the layer to use for the edges of a graph such as a skeleton: one instanced segment per edge, no constructor-only shape_type to reapply, and it stays responsive at edge counts where a Shapes layer does not. See _add_or_update_layer() for the refresh/transform semantics. Returns the layer.