Skip to content

Commit

Permalink
compatibility for napari 0.4.15-19
Browse files Browse the repository at this point in the history
  • Loading branch information
bauerdavid committed Feb 2, 2024
1 parent 60e1515 commit aff6643
Show file tree
Hide file tree
Showing 11 changed files with 250 additions and 170 deletions.
2 changes: 2 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,5 @@ testing =

[options.package_data]
* = *.yaml
*.svg
*.qss
49 changes: 41 additions & 8 deletions src/napari_bbox/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
__version__ = "0.0.3"

__version__ = "0.0.6"
from packaging import version
from napari import layers
layers.NAMES.add("bounding_boxes")

Expand All @@ -10,17 +10,50 @@
from .boundingbox import BoundingBoxLayer
from ._reader import napari_get_reader
from ._writer import write_single_bbox

from ._utils import NAPARI_VERSION
from ._widget import BoundingBoxCreator

from napari import Viewer
def add_bounding_boxes(self, *args, **kwargs):
layer = BoundingBoxLayer(*args, **kwargs)
self.layers.append(layer)
return layer

if NAPARI_VERSION >= version.parse("0.4.18"):

def revert_last_dim_point_cb(viewer):
def revert_last_dim_point(e):
viewer.dims.set_point(range(len(e.source._last_dim_point)), e.source._last_dim_point)
viewer.events.layers_change()
return revert_last_dim_point

def store_last_dim_point_cb(layer):
def store_last_dim_point(e):
p = tuple(round(c) for c in e.source.point)
layer._store_last_dim_point(p)
return store_last_dim_point

def add_bounding_boxes(self, *args, **kwargs):
layer = BoundingBoxLayer(*args, **kwargs)
layer._store_last_dim_point(self.dims.point)
store_cb = store_last_dim_point_cb(layer)
layer.events.data.connect(revert_last_dim_point_cb(self))
self.dims.events.current_step.connect(store_cb)

def disconnect_all(e):
if e.value is not layer:
return
self.dims.events.range.disconnect(store_cb)
self.dims.events.current_step.disconnect(store_cb)
self.layers.events.removed.disconnect(disconnect_all)
self.layers.events.removed.connect(disconnect_all)
self.layers.append(layer)
return layer
else:
def add_bounding_boxes(self, *args, **kwargs):
layer = BoundingBoxLayer(*args, **kwargs)
self.layers.append(layer)
return layer


Viewer.add_bounding_boxes = add_bounding_boxes

import npe2.manifest.contributions._writers
from enum import Enum


Expand Down
26 changes: 26 additions & 0 deletions src/napari_bbox/_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import os
from packaging import version
import napari
NAPARI_VERSION = version.parse(napari.__version__)


def parse_package_by_napari_version(file_path, package, _globals):
__location__ = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(file_path)))
packages = os.listdir(__location__)
napari_versions = [version.parse(package.replace("napari_", "").replace("_", ".")) for package in packages if
package.startswith("napari_")]
for napari_version in reversed(sorted(napari_versions)):
subpackage = "napari_%s" % str(napari_version).replace(".", "_")
if not os.path.exists(os.path.join(__location__, subpackage)):
continue
version_str = subpackage.replace("napari_", "")
cur_version = version.parse(version_str.replace("_", "."))
if NAPARI_VERSION < cur_version:
continue
module = __import__("", fromlist=[f"{subpackage}"], level=1, globals={"__package__": package})
for attr in getattr(getattr(module, f"{subpackage}"), "__all__"):
_globals[attr] = getattr(getattr(module, f"{subpackage}"), attr)
break

__all__ = ["parse_package_by_napari_version", "NAPARI_VERSION"]
2 changes: 1 addition & 1 deletion src/napari_bbox/_widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def __init__(self, viewer: Viewer):
layout.addLayout(ndims_layout)

create_button = QPushButton("Create")
create_button.clicked.connect(lambda: viewer.add_layer(BoundingBoxLayer(ndim=ndims_spinbox.value())))
create_button.clicked.connect(lambda: viewer.add_bounding_boxes(ndim=ndims_spinbox.value()))
layout.addWidget(create_button)
separator = QFrame()
separator.setFrameShape(QFrame.HLine)
Expand Down
21 changes: 2 additions & 19 deletions src/napari_bbox/boundingbox/__init__.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,4 @@
import os
import napari
from packaging import version
__location__ = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(__file__)))
from .._utils import parse_package_by_napari_version
parse_package_by_napari_version(__file__, __package__, globals())

packages = os.listdir(__location__)
napari_versions = [version.parse(package.replace("napari_", "").replace("_", ".")) for package in packages if package.startswith("napari_")]
for napari_version in reversed(sorted(napari_versions)):
package = "napari_%s" % str(napari_version).replace(".", "_")
if not os.path.exists(os.path.join(__location__, package)):
continue
version_str = package.replace("napari_", "")
cur_version = version.parse(version_str.replace("_", "."))
if version.parse(napari.__version__) < cur_version:
continue
module = __import__("", fromlist=[f"{package}"], level=1, globals={"__package__": __package__})
for attr in getattr(getattr(module, f"{package}"), "__all__"):
globals()[attr] = getattr(getattr(module, f"{package}"), attr)
break
__all__ = ["BoundingBoxLayer", "register_layer_control", "register_layer_visual"]
12 changes: 11 additions & 1 deletion src/napari_bbox/boundingbox/napari_0_4_15/bounding_boxes.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from contextlib import contextmanager
from copy import deepcopy, copy
from itertools import cycle
from typing import Dict, Optional, Union, Tuple
from typing import Dict, Any, Optional, Union, Tuple
from packaging import version
import napari.layers
import pandas as pd
Expand Down Expand Up @@ -105,6 +105,8 @@ def __init__(self,
edge_color=Event,
face_color=Event,
properties=Event,
features=Event,
feature_defaults=Event,
current_edge_color=Event,
current_face_color=Event,
current_properties=Event,
Expand Down Expand Up @@ -403,6 +405,14 @@ def feature_defaults(self):
"""
return self._feature_table.defaults

@feature_defaults.setter
def feature_defaults(
self, defaults: Union[Dict[str, Any], pd.DataFrame]
) -> None:
self._feature_table.set_defaults(defaults)
self.events.current_properties()
self.events.feature_defaults()

@property
def properties(self) -> Dict[str, np.ndarray]:
"""dict {str: np.ndarray (N,)}, DataFrame: Annotations for each shape"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ def __init__(self, layer):
self.layer.events.face_color.connect(self._on_data_change)
self.layer.text.events.connect(self._on_text_change)
self.layer.events.highlight.connect(self._on_highlight_change)

self.node._subvisuals[3].symbol = 'square'
self.node._subvisuals[3].scaling = False
self.reset()
self._on_data_change()
self._on_highlight_change()
Expand Down
Loading

0 comments on commit aff6643

Please sign in to comment.