code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def napari_write_image(path: str, data: Any, meta: dict) -> str | None: """Write image data and metadata into a path. It is the responsibility of the implementation to check any extension on ``path`` and return ``None`` if it is an unsupported extension. If ``path`` has no extension, implementations m...
Write image data and metadata into a path. It is the responsibility of the implementation to check any extension on ``path`` and return ``None`` if it is an unsupported extension. If ``path`` has no extension, implementations may append their preferred extension. Parameters ---------- pat...
napari_write_image
python
napari/napari
src/napari/plugins/hook_specifications.py
https://github.com/napari/napari/blob/master/src/napari/plugins/hook_specifications.py
BSD-3-Clause
def napari_write_labels(path: str, data: Any, meta: dict) -> str | None: """Write labels data and metadata into a path. It is the responsibility of the implementation to check any extension on ``path`` and return ``None`` if it is an unsupported extension. If ``path`` has no extension, implementations...
Write labels data and metadata into a path. It is the responsibility of the implementation to check any extension on ``path`` and return ``None`` if it is an unsupported extension. If ``path`` has no extension, implementations may append their preferred extension. Parameters ---------- pa...
napari_write_labels
python
napari/napari
src/napari/plugins/hook_specifications.py
https://github.com/napari/napari/blob/master/src/napari/plugins/hook_specifications.py
BSD-3-Clause
def napari_write_points(path: str, data: Any, meta: dict) -> str | None: """Write points data and metadata into a path. It is the responsibility of the implementation to check any extension on ``path`` and return ``None`` if it is an unsupported extension. If ``path`` has no extension, implementations...
Write points data and metadata into a path. It is the responsibility of the implementation to check any extension on ``path`` and return ``None`` if it is an unsupported extension. If ``path`` has no extension, implementations may append their preferred extension. Parameters ---------- pa...
napari_write_points
python
napari/napari
src/napari/plugins/hook_specifications.py
https://github.com/napari/napari/blob/master/src/napari/plugins/hook_specifications.py
BSD-3-Clause
def napari_write_shapes(path: str, data: Any, meta: dict) -> str | None: """Write shapes data and metadata into a path. It is the responsibility of the implementation to check any extension on ``path`` and return ``None`` if it is an unsupported extension. If ``path`` has no extension, implementations...
Write shapes data and metadata into a path. It is the responsibility of the implementation to check any extension on ``path`` and return ``None`` if it is an unsupported extension. If ``path`` has no extension, implementations may append their preferred extension. Parameters ---------- pa...
napari_write_shapes
python
napari/napari
src/napari/plugins/hook_specifications.py
https://github.com/napari/napari/blob/master/src/napari/plugins/hook_specifications.py
BSD-3-Clause
def napari_write_surface(path: str, data: Any, meta: dict) -> str | None: """Write surface data and metadata into a path. It is the responsibility of the implementation to check any extension on ``path`` and return ``None`` if it is an unsupported extension. If ``path`` has no extension, implementatio...
Write surface data and metadata into a path. It is the responsibility of the implementation to check any extension on ``path`` and return ``None`` if it is an unsupported extension. If ``path`` has no extension, implementations may append their preferred extension. Parameters ---------- p...
napari_write_surface
python
napari/napari
src/napari/plugins/hook_specifications.py
https://github.com/napari/napari/blob/master/src/napari/plugins/hook_specifications.py
BSD-3-Clause
def napari_write_vectors(path: str, data: Any, meta: dict) -> str | None: """Write vectors data and metadata into a path. It is the responsibility of the implementation to check any extension on ``path`` and return ``None`` if it is an unsupported extension. If ``path`` has no extension, implementatio...
Write vectors data and metadata into a path. It is the responsibility of the implementation to check any extension on ``path`` and return ``None`` if it is an unsupported extension. If ``path`` has no extension, implementations may append their preferred extension. Parameters ---------- p...
napari_write_vectors
python
napari/napari
src/napari/plugins/hook_specifications.py
https://github.com/napari/napari/blob/master/src/napari/plugins/hook_specifications.py
BSD-3-Clause
def napari_experimental_provide_function() -> ( FunctionType | list[FunctionType] ): """Provide function(s) that can be passed to magicgui. This hook specification is marked as experimental as the API or how the returned value is handled may change here more frequently then the rest of the codebase...
Provide function(s) that can be passed to magicgui. This hook specification is marked as experimental as the API or how the returned value is handled may change here more frequently then the rest of the codebase. Returns ------- function(s) : FunctionType or list of FunctionType Implem...
napari_experimental_provide_function
python
napari/napari
src/napari/plugins/hook_specifications.py
https://github.com/napari/napari/blob/master/src/napari/plugins/hook_specifications.py
BSD-3-Clause
def napari_experimental_provide_dock_widget() -> ( AugmentedWidget | list[AugmentedWidget] ): """Provide functions that return widgets to be docked in the viewer. This hook specification is marked as experimental as the API or how the returned value is handled may change here more frequently then the ...
Provide functions that return widgets to be docked in the viewer. This hook specification is marked as experimental as the API or how the returned value is handled may change here more frequently then the rest of the codebase. Returns ------- result : callable or tuple or list of callables or ...
napari_experimental_provide_dock_widget
python
napari/napari
src/napari/plugins/hook_specifications.py
https://github.com/napari/napari/blob/master/src/napari/plugins/hook_specifications.py
BSD-3-Clause
def napari_experimental_provide_theme() -> dict[ str, dict[str, str | tuple | list] ]: """Provide GUI with a set of colors used through napari. This hook allows you to provide additional color schemes so you can accomplish your desired styling. Themes are provided as `dict` with several required fields...
Provide GUI with a set of colors used through napari. This hook allows you to provide additional color schemes so you can accomplish your desired styling. Themes are provided as `dict` with several required fields and correctly formatted color values. Colors can be specified using color names (e.g. ``white...
napari_experimental_provide_theme
python
napari/napari
src/napari/plugins/hook_specifications.py
https://github.com/napari/napari/blob/master/src/napari/plugins/hook_specifications.py
BSD-3-Clause
def read_data_with_plugins( paths: Sequence[PathLike], plugin: str | None = None, stack: bool = False, ) -> tuple[list[LayerData] | None, HookImplementation | None]: """Iterate reader hooks and return first non-None LayerData or None. This function returns as soon as the path has been read successf...
Iterate reader hooks and return first non-None LayerData or None. This function returns as soon as the path has been read successfully, while catching any plugin exceptions, storing them for later retrieval, providing useful error messages, and re-looping until either a read operation was successful, o...
read_data_with_plugins
python
napari/napari
src/napari/plugins/io.py
https://github.com/napari/napari/blob/master/src/napari/plugins/io.py
BSD-3-Clause
def save_layers( path: str, layers: list[Layer], *, plugin: str | None = None, _writer: WriterContribution | None = None, ) -> list[str]: """Write list of layers or individual layer to a path using writer plugins. If ``plugin`` is not provided and only one layer is passed, then we direc...
Write list of layers or individual layer to a path using writer plugins. If ``plugin`` is not provided and only one layer is passed, then we directly call ``plugin_manager.hook.napari_write_<layer>()`` which will loop through implementations and stop when the first one returns a non-None result. The or...
save_layers
python
napari/napari
src/napari/plugins/io.py
https://github.com/napari/napari/blob/master/src/napari/plugins/io.py
BSD-3-Clause
def _is_null_layer_sentinel(layer_data: Any) -> bool: """Checks if the layer data returned from a reader function indicates an empty file. The sentinel value used for this is ``[(None,)]``. Parameters ---------- layer_data : LayerData The layer data returned from a reader function to check ...
Checks if the layer data returned from a reader function indicates an empty file. The sentinel value used for this is ``[(None,)]``. Parameters ---------- layer_data : LayerData The layer data returned from a reader function to check Returns ------- bool True, if the layer_...
_is_null_layer_sentinel
python
napari/napari
src/napari/plugins/io.py
https://github.com/napari/napari/blob/master/src/napari/plugins/io.py
BSD-3-Clause
def _write_multiple_layers_with_plugins( path: str, layers: list[Layer], *, plugin_name: str | None = None, _writer: WriterContribution | None = None, ) -> tuple[list[str], str]: """Write data from multiple layers data with a plugin. If a ``plugin_name`` is not provided we loop through plug...
Write data from multiple layers data with a plugin. If a ``plugin_name`` is not provided we loop through plugins to find the first one that knows how to handle the combination of layers and is able to write the file. If no plugins offer ``napari_get_writer`` for that combination of layers then the defa...
_write_multiple_layers_with_plugins
python
napari/napari
src/napari/plugins/io.py
https://github.com/napari/napari/blob/master/src/napari/plugins/io.py
BSD-3-Clause
def _write_single_layer_with_plugins( path: str, layer: Layer, *, plugin_name: str | None = None, _writer: WriterContribution | None = None, ) -> tuple[str | None, str]: """Write single layer data with a plugin. If ``plugin_name`` is not provided then we just directly call ``plugin_mana...
Write single layer data with a plugin. If ``plugin_name`` is not provided then we just directly call ``plugin_manager.hook.napari_write_<layer>()`` which will loop through implementations and stop when the first one returns a non-None result. The order in which implementations are called can be changed...
_write_single_layer_with_plugins
python
napari/napari
src/napari/plugins/io.py
https://github.com/napari/napari/blob/master/src/napari/plugins/io.py
BSD-3-Clause
def _user_agent() -> str: """Return a user agent string for use in http requests.""" import platform from napari import __version__ from napari.utils import misc if misc.running_as_constructor_app(): env = 'constructor' elif misc.in_jupyter(): env = 'jupyter' elif misc.in_i...
Return a user agent string for use in http requests.
_user_agent
python
napari/napari
src/napari/plugins/npe2api.py
https://github.com/napari/napari/blob/master/src/napari/plugins/npe2api.py
BSD-3-Clause
def plugin_summaries() -> list[SummaryDict]: """Return PackageMetadata object for all known napari plugins.""" url = 'https://npe2api.vercel.app/api/extended_summary' with urlopen(Request(url, headers={'User-Agent': _user_agent()})) as resp: return json.load(resp)
Return PackageMetadata object for all known napari plugins.
plugin_summaries
python
napari/napari
src/napari/plugins/npe2api.py
https://github.com/napari/napari/blob/master/src/napari/plugins/npe2api.py
BSD-3-Clause
def conda_map() -> dict[PyPIname, str | None]: """Return map of PyPI package name to conda_channel/package_name ().""" url = 'https://npe2api.vercel.app/api/conda' with urlopen(Request(url, headers={'User-Agent': _user_agent()})) as resp: return json.load(resp)
Return map of PyPI package name to conda_channel/package_name ().
conda_map
python
napari/napari
src/napari/plugins/npe2api.py
https://github.com/napari/napari/blob/master/src/napari/plugins/npe2api.py
BSD-3-Clause
def iter_napari_plugin_info() -> Iterator[tuple[PackageMetadata, bool, dict]]: """Iterator of tuples of ProjectInfo, Conda availability for all napari plugins.""" try: with ThreadPoolExecutor() as executor: data = executor.submit(plugin_summaries) _conda = executor.submit(conda_m...
Iterator of tuples of ProjectInfo, Conda availability for all napari plugins.
iter_napari_plugin_info
python
napari/napari
src/napari/plugins/npe2api.py
https://github.com/napari/napari/blob/master/src/napari/plugins/npe2api.py
BSD-3-Clause
def score_specificity(pattern: str) -> tuple[bool, int, list[MatchFlag]]: """Score an fnmatch pattern, with higher specificities having lower scores. Absolute paths have highest specificity, followed by paths with the most nesting, then by path segments with the least ambiguity. Parameters ---...
Score an fnmatch pattern, with higher specificities having lower scores. Absolute paths have highest specificity, followed by paths with the most nesting, then by path segments with the least ambiguity. Parameters ---------- pattern : str Pattern to score. Returns ------- ...
score_specificity
python
napari/napari
src/napari/plugins/utils.py
https://github.com/napari/napari/blob/master/src/napari/plugins/utils.py
BSD-3-Clause
def _get_preferred_readers(path: PathLike) -> list[tuple[str, str]]: """Given filepath, find matching readers from preferences. Parameters ---------- path : str Path of the file. Returns ------- filtered_preferences : List[Tuple[str, str]] Filtered patterns and their corres...
Given filepath, find matching readers from preferences. Parameters ---------- path : str Path of the file. Returns ------- filtered_preferences : List[Tuple[str, str]] Filtered patterns and their corresponding readers.
_get_preferred_readers
python
napari/napari
src/napari/plugins/utils.py
https://github.com/napari/napari/blob/master/src/napari/plugins/utils.py
BSD-3-Clause
def get_preferred_reader(path: PathLike) -> str | None: """Given filepath, find the best matching reader from the preferences. Parameters ---------- path : str Path of the file. Returns ------- reader : str or None Best matching reader, if found. """ readers = sorte...
Given filepath, find the best matching reader from the preferences. Parameters ---------- path : str Path of the file. Returns ------- reader : str or None Best matching reader, if found.
get_preferred_reader
python
napari/napari
src/napari/plugins/utils.py
https://github.com/napari/napari/blob/master/src/napari/plugins/utils.py
BSD-3-Clause
def get_potential_readers(filename: PathLike) -> dict[str, str]: """Given filename, returns all readers that may read the file. Original plugin engine readers are checked based on returning a function from `napari_get_reader`. Npe2 readers are iterated based on file extension and accepting directories....
Given filename, returns all readers that may read the file. Original plugin engine readers are checked based on returning a function from `napari_get_reader`. Npe2 readers are iterated based on file extension and accepting directories. Returns ------- Dict[str, str] dictionary of regis...
get_potential_readers
python
napari/napari
src/napari/plugins/utils.py
https://github.com/napari/napari/blob/master/src/napari/plugins/utils.py
BSD-3-Clause
def get_all_readers() -> tuple[dict[str, str], dict[str, str]]: """ Return a dict of all npe2 readers and one of all npe1 readers Can be removed once npe2 shim is activated. """ npe2_readers = _npe2.get_readers() npe1_readers = {} for spec, hook_caller in plugin_manager.hooks.items(): ...
Return a dict of all npe2 readers and one of all npe1 readers Can be removed once npe2 shim is activated.
get_all_readers
python
napari/napari
src/napari/plugins/utils.py
https://github.com/napari/napari/blob/master/src/napari/plugins/utils.py
BSD-3-Clause
def get_filename_patterns_for_reader(plugin_name: str): """Return recognized filename patterns, if any, for a given plugin. Where a plugin provides multiple readers it will return a set of all recognized filename patterns. Parameters ---------- plugin_name : str name of plugin to find ...
Return recognized filename patterns, if any, for a given plugin. Where a plugin provides multiple readers it will return a set of all recognized filename patterns. Parameters ---------- plugin_name : str name of plugin to find filename patterns for Returns ------- set ...
get_filename_patterns_for_reader
python
napari/napari
src/napari/plugins/utils.py
https://github.com/napari/napari/blob/master/src/napari/plugins/utils.py
BSD-3-Clause
def read( paths: Sequence[str], plugin: str | None = None, *, stack: bool ) -> tuple[list[LayerData], _FakeHookimpl] | None: """Try to return data for `path`, from reader plugins using a manifest.""" # do nothing if `plugin` is not an npe2 reader if plugin: # user might have passed 'plugin.read...
Try to return data for `path`, from reader plugins using a manifest.
read
python
napari/napari
src/napari/plugins/_npe2.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_npe2.py
BSD-3-Clause
def write_layers( path: str, layers: list[Layer], plugin_name: str | None = None, writer: WriterContribution | None = None, ) -> tuple[list[str], str]: """ Write layers to a file using an NPE2 plugin. Parameters ---------- path : str The path (file, directory, url) to write....
Write layers to a file using an NPE2 plugin. Parameters ---------- path : str The path (file, directory, url) to write. layers : list of Layers The layers to write. plugin_name : str, optional Name of the plugin to write data with. If None then all plugins corre...
write_layers
python
napari/napari
src/napari/plugins/_npe2.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_npe2.py
BSD-3-Clause
def populate_qmenu(menu: QMenu, menu_key: str): """Populate `menu` from a `menu_key` offering in the manifest.""" # TODO: declare somewhere what menu_keys are valid. def _wrap(cmd_): def _wrapped(*args): cmd_.exec(args=args) return _wrapped for item in pm.iter_menu(menu_ke...
Populate `menu` from a `menu_key` offering in the manifest.
populate_qmenu
python
napari/napari
src/napari/plugins/_npe2.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_npe2.py
BSD-3-Clause
def file_extensions_string_for_layers( layers: Sequence[Layer], ) -> tuple[str | None, list[WriterContribution]]: """Create extensions string using npe2. When npe2 can be imported, returns an extension string and the list of corresponding writers. Otherwise returns (None,[]). The extension string ...
Create extensions string using npe2. When npe2 can be imported, returns an extension string and the list of corresponding writers. Otherwise returns (None,[]). The extension string is a ";;" delimeted string of entries. Each entry has a brief description of the file type and a list of extensions. For ...
file_extensions_string_for_layers
python
napari/napari
src/napari/plugins/_npe2.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_npe2.py
BSD-3-Clause
def _items(): """Lookup the command name and its supported extensions.""" for writer in writers: name = pm.get_manifest(writer.command).display_name title = ( f'{name} {writer.display_name}' if writer.display_name else name ...
Lookup the command name and its supported extensions.
_items
python
napari/napari
src/napari/plugins/_npe2.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_npe2.py
BSD-3-Clause
def get_readers(path: str | None = None) -> dict[str, str]: """Get valid reader plugin_name:display_name mapping given path. Iterate through compatible readers for the given path and return dictionary of plugin_name to display_name for each reader. If path is not given, return all readers. Paramet...
Get valid reader plugin_name:display_name mapping given path. Iterate through compatible readers for the given path and return dictionary of plugin_name to display_name for each reader. If path is not given, return all readers. Parameters ---------- path : str path for which to find co...
get_readers
python
napari/napari
src/napari/plugins/_npe2.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_npe2.py
BSD-3-Clause
def get_sample_data( plugin: str, sample: str ) -> tuple[SampleDataCreator | None, list[tuple[str, str]]]: """Get sample data opener from npe2. Parameters ---------- plugin : str name of a plugin providing a sample sample : str name of the sample Returns ------- tup...
Get sample data opener from npe2. Parameters ---------- plugin : str name of a plugin providing a sample sample : str name of the sample Returns ------- tuple - first item is a data "opener": a callable that returns an iterable of layer data, or None, if n...
get_sample_data
python
napari/napari
src/napari/plugins/_npe2.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_npe2.py
BSD-3-Clause
def on_plugin_enablement_change(enabled: set[str], disabled: set[str]): """Callback when any npe2 plugins are enabled or disabled. 'Disabled' means the plugin remains installed, but it cannot be activated, and its contributions will not be indexed """ from napari.settings import get_settings p...
Callback when any npe2 plugins are enabled or disabled. 'Disabled' means the plugin remains installed, but it cannot be activated, and its contributions will not be indexed
on_plugin_enablement_change
python
napari/napari
src/napari/plugins/_npe2.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_npe2.py
BSD-3-Clause
def on_plugins_registered(manifests: set[PluginManifest]): """Callback when any npe2 plugins are registered. 'Registered' means that a manifest has been provided or discovered. """ sorted_manifests = sorted( manifests, key=lambda mf: mf.display_name if mf.display_name else mf.name, ...
Callback when any npe2 plugins are registered. 'Registered' means that a manifest has been provided or discovered.
on_plugins_registered
python
napari/napari
src/napari/plugins/_npe2.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_npe2.py
BSD-3-Clause
def _register_manifest_actions(mf: PluginManifest) -> None: """Gather and register actions from a manifest. This is called when a plugin is registered or enabled and it adds the plugin's menus and submenus to the app model registry. """ from napari._app_model import get_app_model app = get_app...
Gather and register actions from a manifest. This is called when a plugin is registered or enabled and it adds the plugin's menus and submenus to the app model registry.
_register_manifest_actions
python
napari/napari
src/napari/plugins/_npe2.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_npe2.py
BSD-3-Clause
def _safe_register_qt_actions(mf: PluginManifest) -> None: """Register samples and widget `Actions` if Qt available.""" try: from napari._qt._qplugins import _register_qt_actions except ImportError: # pragma: no cover # if no Qt bindings are installed (PyQt/PySide), then trying to import ...
Register samples and widget `Actions` if Qt available.
_safe_register_qt_actions
python
napari/napari
src/napari/plugins/_npe2.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_npe2.py
BSD-3-Clause
def _npe2_manifest_to_actions( mf: PluginManifest, ) -> tuple[list[Action], list[tuple[str, SubmenuItem]]]: """Gather actions and submenus from a npe2 manifest, export app_model types.""" from app_model.types import Action, MenuRule from napari._app_model.constants._menus import is_menu_contributable ...
Gather actions and submenus from a npe2 manifest, export app_model types.
_npe2_manifest_to_actions
python
napari/napari
src/napari/plugins/_npe2.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_npe2.py
BSD-3-Clause
def _when_group_order( menu_item: contributions.MenuItem, ) -> dict: """Extract when/group/order from an npe2 Submenu or MenuCommand.""" group, _, _order = (menu_item.group or '').partition('@') try: order: float | None = float(_order) except ValueError: order = None return {'whe...
Extract when/group/order from an npe2 Submenu or MenuCommand.
_when_group_order
python
napari/napari
src/napari/plugins/_npe2.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_npe2.py
BSD-3-Clause
def _npe2_submenu_to_app_model(subm: contributions.Submenu) -> SubmenuItem: """Convert a npe2 submenu contribution to an app_model SubmenuItem.""" contrib = pm.get_submenu(subm.submenu) return SubmenuItem( submenu=contrib.id, title=contrib.label, icon=contrib.icon, **_when_gr...
Convert a npe2 submenu contribution to an app_model SubmenuItem.
_npe2_submenu_to_app_model
python
napari/napari
src/napari/plugins/_npe2.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_npe2.py
BSD-3-Clause
def call_order(self, first_result_only=True) -> CallOrderDict: """Returns the call order from the plugin manager. Returns ------- call_order : CallOrderDict mapping of hook_specification name, to a list of dicts with keys: {'plugin', 'hook_impl', 'enabled'}. Plu...
Returns the call order from the plugin manager. Returns ------- call_order : CallOrderDict mapping of hook_specification name, to a list of dicts with keys: {'plugin', 'hook_impl', 'enabled'}. Plugins earlier in the dict are called sooner.
call_order
python
napari/napari
src/napari/plugins/_plugin_manager.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_plugin_manager.py
BSD-3-Clause
def set_call_order(self, new_order: CallOrderDict): """Sets the plugin manager call order to match settings plugin values. Note: Run this after load_settings_plugin_defaults, which sets the default values in settings. Parameters ---------- new_order : CallOrderDict ...
Sets the plugin manager call order to match settings plugin values. Note: Run this after load_settings_plugin_defaults, which sets the default values in settings. Parameters ---------- new_order : CallOrderDict mapping of hook_specification name, to a list of dicts ...
set_call_order
python
napari/napari
src/napari/plugins/_plugin_manager.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_plugin_manager.py
BSD-3-Clause
def register_sample_data( self, data: dict[str, str | Callable[..., Iterable[LayerData]]], hookimpl: HookImplementation, ): """Register sample data dict returned by `napari_provide_sample_data`. Each key in `data` is a `sample_name` (the string that will appear in the ...
Register sample data dict returned by `napari_provide_sample_data`. Each key in `data` is a `sample_name` (the string that will appear in the `Open Sample` menu), and the value is either a string, or a callable that returns an iterable of ``LayerData`` tuples, where each tuple is a 1-, 2-, ...
register_sample_data
python
napari/napari
src/napari/plugins/_plugin_manager.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_plugin_manager.py
BSD-3-Clause
def available_samples(self) -> tuple[tuple[str, str], ...]: """Return a tuple of sample data keys provided by plugins. Returns ------- sample_keys : Tuple[Tuple[str, str], ...] A sequence of 2-tuples ``(plugin_name, sample_name)`` showing available sample data pr...
Return a tuple of sample data keys provided by plugins. Returns ------- sample_keys : Tuple[Tuple[str, str], ...] A sequence of 2-tuples ``(plugin_name, sample_name)`` showing available sample data provided by plugins. To load sample data into the viewer, us...
available_samples
python
napari/napari
src/napari/plugins/_plugin_manager.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_plugin_manager.py
BSD-3-Clause
def register_theme_colors( self, data: dict[str, dict[str, str | tuple | list]], hookimpl: HookImplementation, ): """Register theme data dict returned by `napari_experimental_provide_theme`. The `theme` data should be provided as an iterable containing dictionary of ...
Register theme data dict returned by `napari_experimental_provide_theme`. The `theme` data should be provided as an iterable containing dictionary of values, where the ``folder`` value will be used as theme name.
register_theme_colors
python
napari/napari
src/napari/plugins/_plugin_manager.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_plugin_manager.py
BSD-3-Clause
def discover_themes(self) -> None: """Trigger discovery of theme plugins. As a "historic" hook, this should only need to be called once. (historic here means that even plugins that are discovered after this is called will be added.) """ if self._theme_data: r...
Trigger discovery of theme plugins. As a "historic" hook, this should only need to be called once. (historic here means that even plugins that are discovered after this is called will be added.)
discover_themes
python
napari/napari
src/napari/plugins/_plugin_manager.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_plugin_manager.py
BSD-3-Clause
def discover_widgets(self): """Trigger discovery of dock_widgets plugins. As a "historic" hook, this should only need to be called once. (historic here means that even plugins that are discovered after this is called will be added.) """ if self._dock_widgets: ...
Trigger discovery of dock_widgets plugins. As a "historic" hook, this should only need to be called once. (historic here means that even plugins that are discovered after this is called will be added.)
discover_widgets
python
napari/napari
src/napari/plugins/_plugin_manager.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_plugin_manager.py
BSD-3-Clause
def get_widget( self, plugin_name: str, widget_name: str | None = None ) -> tuple[WidgetCallable, dict[str, Any]]: """Get widget `widget_name` provided by plugin `plugin_name`. Note: it's important that :func:`discover_dock_widgets` has been called first, otherwise plugins may not b...
Get widget `widget_name` provided by plugin `plugin_name`. Note: it's important that :func:`discover_dock_widgets` has been called first, otherwise plugins may not be found yet. (Typically, that is done in qt_main_window) Parameters ---------- plugin_name : str ...
get_widget
python
napari/napari
src/napari/plugins/_plugin_manager.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_plugin_manager.py
BSD-3-Clause
def assign_reader_to_extensions( self, reader: str, extensions: str | Iterable[str] ) -> None: """Assign a specific reader plugin to `extensions`. Parameters ---------- reader : str Name of a plugin offering a reader hook. extensions : Union[str, Iterable...
Assign a specific reader plugin to `extensions`. Parameters ---------- reader : str Name of a plugin offering a reader hook. extensions : Union[str, Iterable[str]] Name(s) of extensions to always write with `reader`
assign_reader_to_extensions
python
napari/napari
src/napari/plugins/_plugin_manager.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_plugin_manager.py
BSD-3-Clause
def assign_writer_to_extensions( self, writer: str, extensions: str | Iterable[str] ) -> None: """Assign a specific writer plugin to `extensions`. Parameters ---------- writer : str Name of a plugin offering a writer hook. extensions : Union[str, Iterable...
Assign a specific writer plugin to `extensions`. Parameters ---------- writer : str Name of a plugin offering a writer hook. extensions : Union[str, Iterable[str]] Name(s) of extensions to always write with `writer`
assign_writer_to_extensions
python
napari/napari
src/napari/plugins/_plugin_manager.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_plugin_manager.py
BSD-3-Clause
def test_hook_specification_naming(name, func): """All hook specifications should begin with napari_.""" assert name.startswith('napari_'), ( f"hook specification '{name}' does not start with 'napari_'" )
All hook specifications should begin with napari_.
test_hook_specification_naming
python
napari/napari
src/napari/plugins/_tests/test_hook_specifications.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_tests/test_hook_specifications.py
BSD-3-Clause
def test_annotation_on_hook_specification(name, func): """All hook specifications should have type annotations for all parameters. (Use typing.Any to bail out). If the hook specification accepts no parameters, then it should declare a return type annotation. (until we identify a case where a hook spec...
All hook specifications should have type annotations for all parameters. (Use typing.Any to bail out). If the hook specification accepts no parameters, then it should declare a return type annotation. (until we identify a case where a hook specification needs to both take no parameters and return noth...
test_annotation_on_hook_specification
python
napari/napari
src/napari/plugins/_tests/test_hook_specifications.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_tests/test_hook_specifications.py
BSD-3-Clause
def test_plugin_discovery_is_delayed(): """Test that plugins are not getting discovered at napari import time.""" cmd = [ sys.executable, '-c', 'import sys; from napari.plugins import plugin_manager; ' 'sys.exit(len(plugin_manager.plugins) > 2)', # we have 2 'builtins' ] ...
Test that plugins are not getting discovered at napari import time.
test_plugin_discovery_is_delayed
python
napari/napari
src/napari/plugins/_tests/test_plugins_manager.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_tests/test_plugins_manager.py
BSD-3-Clause
def test_plugin_events(napari_plugin_manager): """Test event emission by plugin manager.""" tnpm: NapariPluginManager = napari_plugin_manager register_events = [] unregister_events = [] enable_events = [] disable_events = [] tnpm.events.registered.connect(lambda e: register_events.append(e...
Test event emission by plugin manager.
test_plugin_events
python
napari/napari
src/napari/plugins/_tests/test_plugins_manager.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_tests/test_plugins_manager.py
BSD-3-Clause
def test_function_widget_registration( arg, napari_plugin_manager, request, recwarn ): """Test that function widgets get validated and registerd correctly.""" class Plugin: @napari_hook_implementation def napari_experimental_provide_function(): return arg napari_plugin_mana...
Test that function widgets get validated and registerd correctly.
test_function_widget_registration
python
napari/napari
src/napari/plugins/_tests/test_plugin_widgets.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_tests/test_plugin_widgets.py
BSD-3-Clause
def test_save_layer_single_named_plugin( builtins, tmpdir, layer_data_and_types ): """Test saving a single layer with a named plugin.""" layers, _, _, filenames = layer_data_and_types for layer, fn in zip(layers, filenames, strict=False): path = os.path.join(tmpdir, fn) # Check file do...
Test saving a single layer with a named plugin.
test_save_layer_single_named_plugin
python
napari/napari
src/napari/plugins/_tests/test_save_layers.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_tests/test_save_layers.py
BSD-3-Clause
def test_save_layer_no_results(): """Test no layers is not an error, and warns on no results.""" with pytest.warns(UserWarning): result = save_layers('no_layers', []) assert result == []
Test no layers is not an error, and warns on no results.
test_save_layer_no_results
python
napari/napari
src/napari/plugins/_tests/test_save_layers.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_tests/test_save_layers.py
BSD-3-Clause
def test_save_layer_single_no_named_plugin( builtins, tmpdir, layer_data_and_types ): """Test saving a single layer without naming plugin.""" # make writer builtin plugins get called first layers, _, _, filenames = layer_data_and_types for layer, fn in zip(layers, filenames, strict=False): ...
Test saving a single layer without naming plugin.
test_save_layer_single_no_named_plugin
python
napari/napari
src/napari/plugins/_tests/test_save_layers.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_tests/test_save_layers.py
BSD-3-Clause
def test_save_layer_multiple_named_plugin( builtins: DynamicPlugin, tmpdir, layer_data_and_types ): """Test saving multiple layers with a named plugin.""" layers, _, _, filenames = layer_data_and_types path = os.path.join(tmpdir, 'layers_folder') # Check file does not exist assert not os.path....
Test saving multiple layers with a named plugin.
test_save_layer_multiple_named_plugin
python
napari/napari
src/napari/plugins/_tests/test_save_layers.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_tests/test_save_layers.py
BSD-3-Clause
def test_save_layer_multiple_no_named_plugin( builtins: DynamicPlugin, tmpdir, layer_data_and_types ): """Test saving multiple layers without naming a plugin.""" layers, _, _, filenames = layer_data_and_types path = os.path.join(tmpdir, 'layers_folder') # Check file does not exist assert not o...
Test saving multiple layers without naming a plugin.
test_save_layer_multiple_no_named_plugin
python
napari/napari
src/napari/plugins/_tests/test_save_layers.py
https://github.com/napari/napari/blob/master/src/napari/plugins/_tests/test_save_layers.py
BSD-3-Clause
def get_icon_path(name: str) -> str: """Return path to an SVG in the theme icons.""" if name not in ICONS: raise ValueError( trans._( 'unrecognized icon name: {name!r}. Known names: {icons}', deferred=True, name=name, icons=set(...
Return path to an SVG in the theme icons.
get_icon_path
python
napari/napari
src/napari/resources/_icons.py
https://github.com/napari/napari/blob/master/src/napari/resources/_icons.py
BSD-3-Clause
def get_colorized_svg( path_or_xml: str | Path, color: str | None = None, opacity=1.0 ) -> str: """Return a colorized version of the SVG XML at ``path``. Raises ------ ValueError If the path exists but does not contain valid SVG data. """ path_or_xml = str(path_or_xml) xml = pat...
Return a colorized version of the SVG XML at ``path``. Raises ------ ValueError If the path exists but does not contain valid SVG data.
get_colorized_svg
python
napari/napari
src/napari/resources/_icons.py
https://github.com/napari/napari/blob/master/src/napari/resources/_icons.py
BSD-3-Clause
def generate_colorized_svgs( svg_paths: Iterable[str | Path], colors: Iterable[str | tuple[str, str]], opacities: Iterable[float] = (1.0,), theme_override: dict[str, str] | None = None, ) -> Iterator[tuple[str, str]]: """Helper function to generate colorized SVGs. This is a generator that yield...
Helper function to generate colorized SVGs. This is a generator that yields tuples of ``(alias, icon_xml)`` for every combination (Cartesian product) of `svg_path`, `color`, and `opacity` provided. It can be used as input to :func:`_temporary_qrc_file`. Parameters ---------- svg_paths : Iterab...
generate_colorized_svgs
python
napari/napari
src/napari/resources/_icons.py
https://github.com/napari/napari/blob/master/src/napari/resources/_icons.py
BSD-3-Clause
def dict( self, *, include: AbstractSetIntStr | MappingIntStrAny = None, # type: ignore exclude: AbstractSetIntStr | MappingIntStrAny = None, # type: ignore by_alias: bool = False, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none...
Return dict representation of the model. May optionally specify which fields to include or exclude.
dict
python
napari/napari
src/napari/settings/_base.py
https://github.com/napari/napari/blob/master/src/napari/settings/_base.py
BSD-3-Clause
def _save_dict(self, **dict_kwargs: Any) -> DictStrAny: """The minimal dict representation that will be persisted to disk. By default, this will exclude settings values that match the default value, and will exclude values that were provided by environment variables. Empty dicts will a...
The minimal dict representation that will be persisted to disk. By default, this will exclude settings values that match the default value, and will exclude values that were provided by environment variables. Empty dicts will also be removed.
_save_dict
python
napari/napari
src/napari/settings/_base.py
https://github.com/napari/napari/blob/master/src/napari/settings/_base.py
BSD-3-Clause
def save(self, path: str | Path | None = None, **dict_kwargs): """Save current settings to path. By default, this will exclude settings values that match the default value, and will exclude values that were provided by environment variables. (see `_save_dict` method.) """ ...
Save current settings to path. By default, this will exclude settings values that match the default value, and will exclude values that were provided by environment variables. (see `_save_dict` method.)
save
python
napari/napari
src/napari/settings/_base.py
https://github.com/napari/napari/blob/master/src/napari/settings/_base.py
BSD-3-Clause
def _dump(self, path: str, data: Dict) -> None: """Encode and dump `data` to `path` using a path-appropriate encoder.""" if str(path).endswith(('.yaml', '.yml')): _data = self._yaml_dump(data) elif str(path).endswith('.json'): json_dumps = self.__config__.json_dumps ...
Encode and dump `data` to `path` using a path-appropriate encoder.
_dump
python
napari/napari
src/napari/settings/_base.py
https://github.com/napari/napari/blob/master/src/napari/settings/_base.py
BSD-3-Clause
def env_settings(self) -> Dict[str, Any]: """Get a dict of fields that were provided as environment vars.""" env_settings = getattr(self.__config__, '_env_settings', {}) if callable(env_settings): env_settings = env_settings(self) return env_settings
Get a dict of fields that were provided as environment vars.
env_settings
python
napari/napari
src/napari/settings/_base.py
https://github.com/napari/napari/blob/master/src/napari/settings/_base.py
BSD-3-Clause
def _remove_env_settings(self, data): """Remove key:values from `data` that match settings from env vars. This is handy when we want to persist settings to disk without including settings that were provided by environment variables (which are usually more temporary). """ ...
Remove key:values from `data` that match settings from env vars. This is handy when we want to persist settings to disk without including settings that were provided by environment variables (which are usually more temporary).
_remove_env_settings
python
napari/napari
src/napari/settings/_base.py
https://github.com/napari/napari/blob/master/src/napari/settings/_base.py
BSD-3-Clause
def customise_sources( cls, init_settings: SettingsSourceCallable, env_settings: EnvSettingsSource, file_secret_settings: SettingsSourceCallable, ) -> tuple[SettingsSourceCallable, ...]: """customise the way data is loaded. This does 2 thi...
customise the way data is loaded. This does 2 things: 1) adds the `config_file_settings_source` to the sources, which will load data from `settings._config_path` if it exists. 2) adds support for nested env_vars, such that if a model with an env_prefix ...
customise_sources
python
napari/napari
src/napari/settings/_base.py
https://github.com/napari/napari/blob/master/src/napari/settings/_base.py
BSD-3-Clause
def nested_env_settings( super_eset: EnvSettingsSource, ) -> SettingsSourceCallable: """Wraps the pydantic EnvSettingsSource to support nested env vars. currently only supports one level of nesting. Examples -------- `NAPARI_APPEARANCE_THEME=light` will parse to: {'appearance': {'theme...
Wraps the pydantic EnvSettingsSource to support nested env vars. currently only supports one level of nesting. Examples -------- `NAPARI_APPEARANCE_THEME=light` will parse to: {'appearance': {'theme': 'light'}} If a submodel has a field that explicitly declares an `env`... that will a...
nested_env_settings
python
napari/napari
src/napari/settings/_base.py
https://github.com/napari/napari/blob/master/src/napari/settings/_base.py
BSD-3-Clause
def config_file_settings_source( settings: EventedConfigFileSettings, ) -> dict[str, Any]: """Read config files during init of an EventedConfigFileSettings obj. The two important values are the `settings._config_path` attribute, which is the main config file (if present), and `settings.__config__.s...
Read config files during init of an EventedConfigFileSettings obj. The two important values are the `settings._config_path` attribute, which is the main config file (if present), and `settings.__config__.source`, which is an optional list of additional files to read. (files later in the list take prece...
config_file_settings_source
python
napari/napari
src/napari/settings/_base.py
https://github.com/napari/napari/blob/master/src/napari/settings/_base.py
BSD-3-Clause
def _remove_bad_keys(data: dict, keys: list[tuple[int | str, ...]]): """Remove list of keys (as string tuples) from dict (in place). Parameters ---------- data : dict dict to modify (will be modified inplace) keys : List[Tuple[str, ...]] list of possibly nested keys Examples ...
Remove list of keys (as string tuples) from dict (in place). Parameters ---------- data : dict dict to modify (will be modified inplace) keys : List[Tuple[str, ...]] list of possibly nested keys Examples -------- >>> data = {'a': 1, 'b' : {'c': 2, 'd': 3}, 'e': 4} >>> ...
_remove_bad_keys
python
napari/napari
src/napari/settings/_base.py
https://github.com/napari/napari/blob/master/src/napari/settings/_base.py
BSD-3-Clause
def _restore_config_data(dct: dict, delete: dict, defaults: dict) -> dict: """delete nested dict keys, restore from defaults.""" for k, v in delete.items(): # recurse if isinstance(v, dict): dflt = defaults.get(k, {}) if not isinstance(dflt, dict): dflt = ...
delete nested dict keys, restore from defaults.
_restore_config_data
python
napari/napari
src/napari/settings/_base.py
https://github.com/napari/napari/blob/master/src/napari/settings/_base.py
BSD-3-Clause
def _remove_empty_dicts(dct: dict, recurse=True) -> dict: """Remove all (nested) keys with empty dict values from `dct`""" for k, v in list(dct.items()): if isinstance(v, Mapping) and recurse: _remove_empty_dicts(dct[k]) if v == {}: del dct[k] return dct
Remove all (nested) keys with empty dict values from `dct`
_remove_empty_dicts
python
napari/napari
src/napari/settings/_base.py
https://github.com/napari/napari/blob/master/src/napari/settings/_base.py
BSD-3-Clause
def parse(cls, version: bytes | str) -> 'Version': """Convert string or bytes into Version object.""" if isinstance(version, bytes): version = version.decode('UTF-8') match = cls._SEMVER_PATTERN.match(version) if match is None: raise ValueError( tr...
Convert string or bytes into Version object.
parse
python
napari/napari
src/napari/settings/_fields.py
https://github.com/napari/napari/blob/master/src/napari/settings/_fields.py
BSD-3-Clause
def to_tuple(self) -> tuple[int, int, int, str | None, str | None]: """Return version as tuple (first three are int, last two Opt[str]).""" return ( int(self.major), int(self.minor), int(self.patch), str(self.prerelease) if self.prerelease is not None else...
Return version as tuple (first three are int, last two Opt[str]).
to_tuple
python
napari/napari
src/napari/settings/_fields.py
https://github.com/napari/napari/blob/master/src/napari/settings/_fields.py
BSD-3-Clause
def do_migrations(model: NapariSettings): """Migrate (update) a NapariSettings model in place.""" for migration in sorted(_MIGRATORS, key=lambda m: m.from_): if model.schema_version == migration.from_: with mutation_allowed(model): backup = model.dict() try: ...
Migrate (update) a NapariSettings model in place.
do_migrations
python
napari/napari
src/napari/settings/_migrations.py
https://github.com/napari/napari/blob/master/src/napari/settings/_migrations.py
BSD-3-Clause
def mutation_allowed(obj: NapariSettings): """Temporarily allow mutations on an immutable model.""" config = obj.__config__ prev, config.allow_mutation = config.allow_mutation, True try: yield finally: config.allow_mutation = prev
Temporarily allow mutations on an immutable model.
mutation_allowed
python
napari/napari
src/napari/settings/_migrations.py
https://github.com/napari/napari/blob/master/src/napari/settings/_migrations.py
BSD-3-Clause
def migrator(from_: str, to_: str) -> Callable[[MigratorF], MigratorF]: """Decorate function as migrating settings from v `from_` to v `to_`. A migrator should mutate a `NapariSettings` model from schema version `from_` to schema version `to_` (in place). Parameters ---------- from_ : str ...
Decorate function as migrating settings from v `from_` to v `to_`. A migrator should mutate a `NapariSettings` model from schema version `from_` to schema version `to_` (in place). Parameters ---------- from_ : str NapariSettings.schema_version version that this migrator expects as ...
migrator
python
napari/napari
src/napari/settings/_migrations.py
https://github.com/napari/napari/blob/master/src/napari/settings/_migrations.py
BSD-3-Clause
def v030_v040(model: NapariSettings): """Migrate from v0.3.0 to v0.4.0. Prior to v0.4.0, npe2 plugins were automatically added to disabled plugins. This migration removes any npe2 plugins discovered in the environment (at migration time) from the "disabled plugins" set. """ for dist in distribu...
Migrate from v0.3.0 to v0.4.0. Prior to v0.4.0, npe2 plugins were automatically added to disabled plugins. This migration removes any npe2 plugins discovered in the environment (at migration time) from the "disabled plugins" set.
v030_v040
python
napari/napari
src/napari/settings/_migrations.py
https://github.com/napari/napari/blob/master/src/napari/settings/_migrations.py
BSD-3-Clause
def v040_050(model: NapariSettings): """Migrate from v0.4.0 to v0.5.0 Prior to 0.5.0 existing preferences may have reader extensions preferences saved without a leading *. fnmatch would fail on these so we coerce them to include a * e.g. '.csv' becomes '*.csv' """ from napari.settings._util...
Migrate from v0.4.0 to v0.5.0 Prior to 0.5.0 existing preferences may have reader extensions preferences saved without a leading *. fnmatch would fail on these so we coerce them to include a * e.g. '.csv' becomes '*.csv'
v040_050
python
napari/napari
src/napari/settings/_migrations.py
https://github.com/napari/napari/blob/master/src/napari/settings/_migrations.py
BSD-3-Clause
def _swap_ctrl_cmd(keybinding): """Swap the Control and Command/Super/Meta modifiers in a keybinding. See `v050_060` for motivation. """ from napari.utils.key_bindings import KeyBinding kb = KeyBinding.from_str( str(keybinding) .replace('Ctrl', 'Temp') .replace('Meta', 'Ctr...
Swap the Control and Command/Super/Meta modifiers in a keybinding. See `v050_060` for motivation.
_swap_ctrl_cmd
python
napari/napari
src/napari/settings/_migrations.py
https://github.com/napari/napari/blob/master/src/napari/settings/_migrations.py
BSD-3-Clause
def v050_060(model: NapariSettings): """Migrate from v0.5.0 to v0.6.0. In #5103 we went from using our own keybinding model to using app-model's. Several consequences of this are: - Control is written out as Ctrl (and that is the only valid input) - Option is written out as Alt (and that is the onl...
Migrate from v0.5.0 to v0.6.0. In #5103 we went from using our own keybinding model to using app-model's. Several consequences of this are: - Control is written out as Ctrl (and that is the only valid input) - Option is written out as Alt (and that is the only valid input) - Super/Command/Cmd are w...
v050_060
python
napari/napari
src/napari/settings/_migrations.py
https://github.com/napari/napari/blob/master/src/napari/settings/_migrations.py
BSD-3-Clause
def v060_070(model: NapariSettings): """Migrate from v0.6.0 to v0.7.0. In #7627 we updated the default value of the npe2 shim, which bumped the minor version. However, the migration doesn't need to do anything about that. In #7747, we changed from `experimental.compiled_triangulation` (bool) to ...
Migrate from v0.6.0 to v0.7.0. In #7627 we updated the default value of the npe2 shim, which bumped the minor version. However, the migration doesn't need to do anything about that. In #7747, we changed from `experimental.compiled_triangulation` (bool) to `experimental.triangulation_backend` (enum...
v060_070
python
napari/napari
src/napari/settings/_migrations.py
https://github.com/napari/napari/blob/master/src/napari/settings/_migrations.py
BSD-3-Clause
def _coerce_extensions_to_globs(reader_settings: dict[str, T]) -> dict[str, T]: """Coerce existing reader settings for file extensions to glob patterns""" new_settings = {} for pattern, reader in reader_settings.items(): if pattern.startswith('.') and '*' not in pattern: pattern = f'*{pa...
Coerce existing reader settings for file extensions to glob patterns
_coerce_extensions_to_globs
python
napari/napari
src/napari/settings/_utils.py
https://github.com/napari/napari/blob/master/src/napari/settings/_utils.py
BSD-3-Clause
def get_settings(path=_NOT_SET) -> NapariSettings: """ Get settings for a given path. Parameters ---------- path : Path, optional The path to read/write the settings from. Returns ------- SettingsManager The settings manager. Notes ----- The path can only b...
Get settings for a given path. Parameters ---------- path : Path, optional The path to read/write the settings from. Returns ------- SettingsManager The settings manager. Notes ----- The path can only be set once per session.
get_settings
python
napari/napari
src/napari/settings/__init__.py
https://github.com/napari/napari/blob/master/src/napari/settings/__init__.py
BSD-3-Clause
def test_050_to_060_migration_mac(): """Check that Ctrl and Meta are swapped on macOS when migrating.""" settings050 = NapariSettings( schema_version='0.5.0', shortcuts={ 'shortcuts': { 'napari:focus_axes_up': ['Alt-Up'], 'napari:roll_axes': ['Control-...
Check that Ctrl and Meta are swapped on macOS when migrating.
test_050_to_060_migration_mac
python
napari/napari
src/napari/settings/_tests/test_migrations.py
https://github.com/napari/napari/blob/master/src/napari/settings/_tests/test_migrations.py
BSD-3-Clause
def test_050_to_060_migration_linux_win(): """Check that shortcuts are unchanged on non-macOS when migrating.""" shortcuts_dict = { 'napari:focus_axes_up': ['Alt-Up'], 'napari:roll_axes': ['Control-E'], 'napari:transpose_axes': ['Control-Meta-T'], 'napari:paste_shape': ['V', 'Met...
Check that shortcuts are unchanged on non-macOS when migrating.
test_050_to_060_migration_linux_win
python
napari/napari
src/napari/settings/_tests/test_migrations.py
https://github.com/napari/napari/blob/master/src/napari/settings/_tests/test_migrations.py
BSD-3-Clause
def test_settings(tmp_path): """A fixture that can be used to test and save settings""" from napari.settings import NapariSettings class TestSettings(NapariSettings): class Config: env_prefix = 'testnapari_' return TestSettings( tmp_path / 'test_settings.yml', schema_versio...
A fixture that can be used to test and save settings
test_settings
python
napari/napari
src/napari/settings/_tests/test_settings.py
https://github.com/napari/napari/blob/master/src/napari/settings/_tests/test_settings.py
BSD-3-Clause
def test_settings_to_dict_no_env(monkeypatch): """Test that exclude_env works to exclude variables coming from the env.""" s = NapariSettings(None, appearance={'theme': 'light'}) assert s.dict()['appearance']['theme'] == 'light' assert s.dict(exclude_env=True)['appearance']['theme'] == 'light' monk...
Test that exclude_env works to exclude variables coming from the env.
test_settings_to_dict_no_env
python
napari/napari
src/napari/settings/_tests/test_settings.py
https://github.com/napari/napari/blob/master/src/napari/settings/_tests/test_settings.py
BSD-3-Clause
def test_subfield_env_field(monkeypatch): """test that setting Field(env=) works for subfields""" from napari.settings._base import EventedSettings class Sub(EventedSettings): x: int = Field(1, env='varname') class T(NapariSettings): sub: Sub monkeypatch.setenv('VARNAME', '42') ...
test that setting Field(env=) works for subfields
test_subfield_env_field
python
napari/napari
src/napari/settings/_tests/test_settings.py
https://github.com/napari/napari/blob/master/src/napari/settings/_tests/test_settings.py
BSD-3-Clause
def test_no_save_path(): """trying to save without a config path is an error""" s = NapariSettings(config_path=None) assert s.config_path is None with pytest.raises(ValueError, match='No path provided'): # the original `save()` method is patched in conftest._fresh_settings # so we "unmo...
trying to save without a config path is an error
test_no_save_path
python
napari/napari
src/napari/settings/_tests/test_settings.py
https://github.com/napari/napari/blob/master/src/napari/settings/_tests/test_settings.py
BSD-3-Clause
def test_shortcut_aliases(): """Check that Command, Option, Super, Cmd are all valid modifiers.""" settings_original = NapariSettings( schema_version='0.6.0', shortcuts={ 'shortcuts': { 'napari:focus_axes_up': ['Option-Up'], 'napari:roll_axes': ['Super...
Check that Command, Option, Super, Cmd are all valid modifiers.
test_shortcut_aliases
python
napari/napari
src/napari/settings/_tests/test_settings.py
https://github.com/napari/napari/blob/master/src/napari/settings/_tests/test_settings.py
BSD-3-Clause
def register_action( self, name: str, command: Callable, description: str, keymapprovider: KeymapProvider | None, repeatable: bool = False, ): """ Register an action for future usage An action is generally a callback associated with -...
Register an action for future usage An action is generally a callback associated with - a name (unique), usually `packagename:name` - a description - A keymap provider (easier for focus and backward compatibility). - a boolean repeatability flag indicating whether i...
register_action
python
napari/napari
src/napari/utils/action_manager.py
https://github.com/napari/napari/blob/master/src/napari/utils/action_manager.py
BSD-3-Clause
def _update_shortcut_bindings(self, name: str): """ Update the key mappable for given action name to trigger the action within the given context and """ if name not in self._actions: return if name not in self._shortcuts: return action = se...
Update the key mappable for given action name to trigger the action within the given context and
_update_shortcut_bindings
python
napari/napari
src/napari/utils/action_manager.py
https://github.com/napari/napari/blob/master/src/napari/utils/action_manager.py
BSD-3-Clause
def bind_button( self, name: str, button: Button, extra_tooltip_text='' ) -> None: """ Bind `button` to trigger Action `name` on click. Parameters ---------- name : str name of the corresponding action in the form ``packagename:name`` button : But...
Bind `button` to trigger Action `name` on click. Parameters ---------- name : str name of the corresponding action in the form ``packagename:name`` button : Button A object providing Button interface (like QPushButton) that, when clicked, sho...
bind_button
python
napari/napari
src/napari/utils/action_manager.py
https://github.com/napari/napari/blob/master/src/napari/utils/action_manager.py
BSD-3-Clause
def bind_shortcut(self, name: str, shortcut: str) -> None: """ bind shortcut `shortcut` to trigger action `name` Parameters ---------- name : str name of the corresponding action in the form ``packagename:name`` shortcut : str Shortcut to assign t...
bind shortcut `shortcut` to trigger action `name` Parameters ---------- name : str name of the corresponding action in the form ``packagename:name`` shortcut : str Shortcut to assign to this action use dash as separator. See `Shortcut` for kn...
bind_shortcut
python
napari/napari
src/napari/utils/action_manager.py
https://github.com/napari/napari/blob/master/src/napari/utils/action_manager.py
BSD-3-Clause
def _get_layer_shortcuts(self, layers) -> dict: """ Get shortcuts filtered by the given layers. Parameters ---------- layers : list of layers Layers to use for shortcuts filtering. Returns ------- dict Dictionary of layers with di...
Get shortcuts filtered by the given layers. Parameters ---------- layers : list of layers Layers to use for shortcuts filtering. Returns ------- dict Dictionary of layers with dictionaries of shortcuts to descriptions. ...
_get_layer_shortcuts
python
napari/napari
src/napari/utils/action_manager.py
https://github.com/napari/napari/blob/master/src/napari/utils/action_manager.py
BSD-3-Clause
def _get_provider_actions(self, provider) -> dict: """ Get actions filtered by the given provider. Parameters ---------- provider : KeymapProvider Provider to use for actions filtering. Returns ------- provider_actions: dict Dicti...
Get actions filtered by the given provider. Parameters ---------- provider : KeymapProvider Provider to use for actions filtering. Returns ------- provider_actions: dict Dictionary of names of actions with action values for a provider. ...
_get_provider_actions
python
napari/napari
src/napari/utils/action_manager.py
https://github.com/napari/napari/blob/master/src/napari/utils/action_manager.py
BSD-3-Clause
def _get_active_shortcuts(self, active_keymap): """ Get active shortcuts for the given active keymap. Parameters ---------- active_keymap : KeymapProvider The active keymap provider. Returns ------- dict Dictionary of shortcuts to...
Get active shortcuts for the given active keymap. Parameters ---------- active_keymap : KeymapProvider The active keymap provider. Returns ------- dict Dictionary of shortcuts to descriptions.
_get_active_shortcuts
python
napari/napari
src/napari/utils/action_manager.py
https://github.com/napari/napari/blob/master/src/napari/utils/action_manager.py
BSD-3-Clause
def _get_repeatable_shortcuts(self, active_keymap) -> list: """ Get active, repeatable shortcuts for the given active keymap. Parameters ---------- active_keymap : KeymapProvider The active keymap provider. Returns ------- list Li...
Get active, repeatable shortcuts for the given active keymap. Parameters ---------- active_keymap : KeymapProvider The active keymap provider. Returns ------- list List of shortcuts that are repeatable.
_get_repeatable_shortcuts
python
napari/napari
src/napari/utils/action_manager.py
https://github.com/napari/napari/blob/master/src/napari/utils/action_manager.py
BSD-3-Clause