Merge branch 'devel' into dev/click
Conflicts: setup.py src/octoprint/__init__.py src/octoprint/plugin/core.py src/octoprint/server/__init__.py
This commit is contained in:
commit
b326efbc3c
197 files changed
+28216
-4328
No files matched your search
@@ -106,7 +106,9 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
|
||||
EventHandlerPlugin,
|
||||
SlicerPlugin,
|
||||
AppPlugin,
|
||||
ProgressPlugin]
|
||||
ProgressPlugin,
|
||||
WizardPlugin,
|
||||
UiPlugin]
|
||||
if plugin_entry_points is None:
|
||||
plugin_entry_points = "octoprint.plugin"
|
||||
if plugin_disabled_list is None:
|
||||
@@ -159,7 +161,7 @@ def plugin_settings(plugin_key, defaults=None, get_preprocessors=None, set_prepr
|
||||
set_preprocessors=set_preprocessors)
|
||||
|
||||
|
||||
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None):
|
||||
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None):
|
||||
"""
|
||||
Helper method to invoke the indicated ``method`` on all registered plugin implementations implementing the
|
||||
indicated ``types``. Allows providing method arguments and registering callbacks to call in case of success
|
||||
@@ -205,7 +207,7 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
|
||||
if kwargs is None:
|
||||
kwargs = dict()
|
||||
|
||||
plugins = plugin_manager().get_implementations(*types)
|
||||
plugins = plugin_manager().get_implementations(*types, sorting_context=sorting_context)
|
||||
for plugin in plugins:
|
||||
if hasattr(plugin, method):
|
||||
try:
|
||||
@@ -301,19 +303,16 @@ class PluginSettings(object):
|
||||
self.set_preprocessors = dict(plugins=dict())
|
||||
self.set_preprocessors["plugins"][plugin_key] = set_preprocessors
|
||||
|
||||
def prefix_path(path):
|
||||
return ['plugins', self.plugin_key] + path
|
||||
|
||||
def prefix_path_in_args(args, index=0):
|
||||
result = []
|
||||
if index == 0:
|
||||
result.append(prefix_path(args[0]))
|
||||
result.append(self._prefix_path(args[0]))
|
||||
result.extend(args[1:])
|
||||
else:
|
||||
args_before = args[:index - 1]
|
||||
args_after = args[index + 1:]
|
||||
result.extend(args_before)
|
||||
result.append(prefix_path(args[index]))
|
||||
result.append(self._prefix_path(args[index]))
|
||||
result.extend(args_after)
|
||||
return result
|
||||
|
||||
@@ -332,6 +331,7 @@ class PluginSettings(object):
|
||||
return kwargs
|
||||
|
||||
self.access_methods = dict(
|
||||
has =("has", prefix_path_in_args, add_getter_kwargs),
|
||||
get =("get", prefix_path_in_args, add_getter_kwargs),
|
||||
get_int =("getInt", prefix_path_in_args, add_getter_kwargs),
|
||||
get_float =("getFloat", prefix_path_in_args, add_getter_kwargs),
|
||||
@@ -339,7 +339,8 @@ class PluginSettings(object):
|
||||
set =("set", prefix_path_in_args, add_setter_kwargs),
|
||||
set_int =("setInt", prefix_path_in_args, add_setter_kwargs),
|
||||
set_float =("setFloat", prefix_path_in_args, add_setter_kwargs),
|
||||
set_boolean=("setBoolean", prefix_path_in_args, add_setter_kwargs)
|
||||
set_boolean=("setBoolean", prefix_path_in_args, add_setter_kwargs),
|
||||
remove =("remove", prefix_path_in_args)
|
||||
)
|
||||
self.deprecated_access_methods = dict(
|
||||
getInt ="get_int",
|
||||
@@ -350,6 +351,17 @@ class PluginSettings(object):
|
||||
setBoolean="set_boolean"
|
||||
)
|
||||
|
||||
def _prefix_path(self, path=None):
|
||||
if path is None:
|
||||
path = list()
|
||||
return ['plugins', self.plugin_key] + path
|
||||
|
||||
def global_has(self, path, **kwargs):
|
||||
return self.settings.has(path, **kwargs)
|
||||
|
||||
def global_remove(self, path, **kwargs):
|
||||
return self.settings.remove(path, **kwargs)
|
||||
|
||||
def global_get(self, path, **kwargs):
|
||||
"""
|
||||
Getter for retrieving settings not managed by the plugin itself from the core settings structure. Use this
|
||||
@@ -443,6 +455,24 @@ class PluginSettings(object):
|
||||
os.makedirs(path)
|
||||
return path
|
||||
|
||||
def get_all_data(self, **kwargs):
|
||||
merged = kwargs.get("merged", True)
|
||||
asdict = kwargs.get("asdict", True)
|
||||
defaults = kwargs.get("defaults", self.defaults)
|
||||
preprocessors = kwargs.get("preprocessors", self.get_preprocessors)
|
||||
|
||||
kwargs.update(dict(
|
||||
merged=merged,
|
||||
asdict=asdict,
|
||||
defaults=defaults,
|
||||
preprocessors=preprocessors
|
||||
))
|
||||
|
||||
return self.settings.get(self._prefix_path(), **kwargs)
|
||||
|
||||
def clean_all_data(self):
|
||||
self.settings.remove(self._prefix_path())
|
||||
|
||||
def __getattr__(self, item):
|
||||
all_access_methods = self.access_methods.keys() + self.deprecated_access_methods.keys()
|
||||
if item in all_access_methods:
|
||||
|
||||
+180
-28
@@ -12,6 +12,12 @@ way and could be extracted into a separate Python module in the future.
|
||||
.. autoclass:: Plugin
|
||||
:members:
|
||||
|
||||
.. autoclass:: RestartNeedingPlugin
|
||||
:members:
|
||||
|
||||
.. autoclass:: SortablePlugin
|
||||
:members:
|
||||
|
||||
"""
|
||||
|
||||
from __future__ import absolute_import
|
||||
@@ -23,7 +29,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import os
|
||||
import imp
|
||||
from collections import defaultdict, namedtuple
|
||||
from collections import defaultdict, namedtuple, OrderedDict
|
||||
import logging
|
||||
|
||||
import pkg_resources
|
||||
@@ -127,6 +133,7 @@ class PluginInfo(object):
|
||||
self.enabled = True
|
||||
self.bundled = False
|
||||
self.loaded = False
|
||||
self.managable = True
|
||||
|
||||
self._name = name
|
||||
self._version = version
|
||||
@@ -449,10 +456,11 @@ class PluginManager(object):
|
||||
|
||||
self.enabled_plugins = dict()
|
||||
self.disabled_plugins = dict()
|
||||
self.plugin_hooks = defaultdict(list)
|
||||
self.plugin_implementations = dict()
|
||||
self.plugin_implementations_by_type = defaultdict(list)
|
||||
|
||||
self._plugin_hooks = defaultdict(list)
|
||||
|
||||
self.implementation_injects = dict()
|
||||
self.implementation_inject_factories = []
|
||||
self.implementation_pre_inits = []
|
||||
@@ -468,12 +476,35 @@ class PluginManager(object):
|
||||
|
||||
self.marked_plugins = defaultdict(list)
|
||||
|
||||
self._python_install_dir = None
|
||||
self._python_virtual_env = False
|
||||
self._detect_python_environment()
|
||||
|
||||
self.reload_plugins(startup=True, initialize_implementations=False)
|
||||
|
||||
def _detect_python_environment(self):
|
||||
from distutils.command.install import install as cmd_install
|
||||
from distutils.dist import Distribution
|
||||
import sys
|
||||
|
||||
cmd = cmd_install(Distribution())
|
||||
cmd.finalize_options()
|
||||
|
||||
self._python_install_dir = cmd.install_lib
|
||||
self._python_prefix = sys.prefix
|
||||
self._python_virtual_env = hasattr(sys, "real_prefix") \
|
||||
or (hasattr(sys, "base_prefix") and sys.prefix != sys.base_prefix)
|
||||
|
||||
@property
|
||||
def plugins(self):
|
||||
plugins = dict(self.enabled_plugins)
|
||||
plugins.update(self.disabled_plugins)
|
||||
return plugins
|
||||
|
||||
@property
|
||||
def plugin_hooks(self):
|
||||
return {key: map(lambda v: (v[1], v[2]), value) for key, value in self._plugin_hooks.items()}
|
||||
|
||||
def find_plugins(self, existing=None, ignore_uninstalled=True):
|
||||
if existing is None:
|
||||
existing = dict(self.plugins)
|
||||
@@ -490,12 +521,13 @@ class PluginManager(object):
|
||||
result = dict()
|
||||
|
||||
for folder in folders:
|
||||
readonly = False
|
||||
flagged_readonly = False
|
||||
if isinstance(folder, (list, tuple)):
|
||||
if len(folder) == 2:
|
||||
folder, readonly = folder
|
||||
folder, flagged_readonly = folder
|
||||
else:
|
||||
continue
|
||||
actual_readonly = not os.access(folder, os.W_OK)
|
||||
|
||||
if not os.path.exists(folder):
|
||||
self.logger.warn("Plugin folder {folder} could not be found, skipping it".format(folder=folder))
|
||||
@@ -518,8 +550,8 @@ class PluginManager(object):
|
||||
plugin = self._import_plugin_from_module(key, folder=folder)
|
||||
if plugin:
|
||||
plugin.origin = FolderOrigin("folder", folder)
|
||||
if readonly:
|
||||
plugin.bundled = True
|
||||
plugin.managable = not flagged_readonly and not actual_readonly
|
||||
plugin.bundled = flagged_readonly
|
||||
|
||||
plugin.enabled = False
|
||||
|
||||
@@ -530,9 +562,18 @@ class PluginManager(object):
|
||||
def _find_plugins_from_entry_points(self, groups, existing, ignore_uninstalled=True):
|
||||
result = dict()
|
||||
|
||||
# let's make sure we have a current working set
|
||||
# let's make sure we have a current working set ...
|
||||
working_set = pkg_resources.WorkingSet()
|
||||
|
||||
# ... including the user's site packages
|
||||
import site
|
||||
import sys
|
||||
if site.ENABLE_USER_SITE:
|
||||
if not site.USER_SITE in working_set.entries:
|
||||
working_set.add_entry(site.USER_SITE)
|
||||
if not site.USER_SITE in sys.path:
|
||||
site.addsitedir(site.USER_SITE)
|
||||
|
||||
if not isinstance(groups, (list, tuple)):
|
||||
groups = [groups]
|
||||
|
||||
@@ -565,6 +606,16 @@ class PluginManager(object):
|
||||
plugin = self._import_plugin_from_module(key, **kwargs)
|
||||
if plugin:
|
||||
plugin.origin = EntryPointOrigin("entry_point", group, module_name, package_name, version)
|
||||
|
||||
# plugin is manageable if its location is writable and OctoPrint
|
||||
# is either not running from a virtual env or the plugin is
|
||||
# installed in that virtual env - the virtual env's pip will not
|
||||
# allow us to uninstall stuff that is installed outside
|
||||
# of the virtual env, so this check is necessary
|
||||
plugin.managable = os.access(plugin.location, os.W_OK) \
|
||||
and (not self._python_virtual_env
|
||||
or plugin.location.startswith(self._python_prefix))
|
||||
|
||||
plugin.enabled = False
|
||||
result[key] = plugin
|
||||
|
||||
@@ -635,15 +686,24 @@ class PluginManager(object):
|
||||
hooks=sum(map(lambda x: len(x), self.plugin_hooks.values()))
|
||||
))
|
||||
|
||||
def mark_plugin(self, name, uninstalled=None):
|
||||
def mark_plugin(self, name, **kwargs):
|
||||
if not name in self.plugins:
|
||||
self.logger.warn("Trying to mark an unknown plugin {name}".format(**locals()))
|
||||
self.logger.debug("Trying to mark an unknown plugin {name}".format(**locals()))
|
||||
|
||||
if uninstalled is not None:
|
||||
if uninstalled and not name in self.marked_plugins["uninstalled"]:
|
||||
self.marked_plugins["uninstalled"].append(name)
|
||||
elif not uninstalled and name in self.marked_plugins["uninstalled"]:
|
||||
self.marked_plugins["uninstalled"].remove(name)
|
||||
for key, value in kwargs.items():
|
||||
if value is None:
|
||||
continue
|
||||
|
||||
if value and not name in self.marked_plugins[key]:
|
||||
self.marked_plugins[key].append(name)
|
||||
elif not value and name in self.marked_plugins[key]:
|
||||
self.marked_plugins[key].remove(name)
|
||||
|
||||
def is_plugin_marked(self, name, key):
|
||||
if not name in self.plugins:
|
||||
return False
|
||||
|
||||
return name in self.marked_plugins[key]
|
||||
|
||||
def load_plugin(self, name, plugin=None, startup=False, initialize_implementation=True):
|
||||
if not name in self.plugins:
|
||||
@@ -777,8 +837,15 @@ class PluginManager(object):
|
||||
plugin.hotchangeable = self.is_restart_needing_plugin(plugin)
|
||||
|
||||
# evaluate registered hooks
|
||||
for hook, callback in plugin.hooks.items():
|
||||
self.plugin_hooks[hook].append((name, callback))
|
||||
for hook, definition in plugin.hooks.items():
|
||||
try:
|
||||
callback, order = self._get_callback_and_order(definition)
|
||||
except ValueError as e:
|
||||
self.logger.warn("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e)))
|
||||
continue
|
||||
|
||||
self._plugin_hooks[hook].append((order, name, callback))
|
||||
self._sort_hooks(hook)
|
||||
|
||||
# evaluate registered implementation
|
||||
if plugin.implementation:
|
||||
@@ -789,9 +856,16 @@ class PluginManager(object):
|
||||
self.plugin_implementations[name] = plugin.implementation
|
||||
|
||||
def _deactivate_plugin(self, name, plugin):
|
||||
for hook, callback in plugin.hooks.items():
|
||||
for hook, definition in plugin.hooks.items():
|
||||
try:
|
||||
self.plugin_hooks[hook].remove((name, callback))
|
||||
callback, order = self._get_callback_and_order(definition)
|
||||
except ValueError as e:
|
||||
self.logger.warn("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e)))
|
||||
continue
|
||||
|
||||
try:
|
||||
self._plugin_hooks[hook].remove((order, name, callback))
|
||||
self._sort_hooks(hook)
|
||||
except ValueError:
|
||||
# that's ok, the plugin was just not registered for the hook
|
||||
pass
|
||||
@@ -859,7 +933,7 @@ class PluginManager(object):
|
||||
additional_pre_inits=additional_pre_inits,
|
||||
additional_post_inits=additional_post_inits)
|
||||
|
||||
self.logger.info("Initialized {count} plugin(s)".format(count=len(self.plugin_implementations)))
|
||||
self.logger.info("Initialized {count} plugin implementation(s)".format(count=len(self.plugin_implementations)))
|
||||
|
||||
def initialize_implementation_of_plugin(self, name, plugin, additional_injects=None, additional_inject_factories=None, additional_pre_inits=None, additional_post_inits=None):
|
||||
if plugin.implementation is None:
|
||||
@@ -959,8 +1033,8 @@ class PluginManager(object):
|
||||
location_str=location_str,
|
||||
show_enabled=show_enabled,
|
||||
enabled_strs=enabled_str),
|
||||
sorted(self.enabled_plugins.values(), key=lambda x: x.name.lower()),
|
||||
))))
|
||||
sorted(self.plugins.values(), key=lambda x: str(x).lower()))
|
||||
)))
|
||||
|
||||
def get_plugin(self, identifier, require_enabled=True):
|
||||
"""
|
||||
@@ -1015,9 +1089,13 @@ class PluginManager(object):
|
||||
|
||||
if not hook in self.plugin_hooks:
|
||||
return dict()
|
||||
return {hook[0]: hook[1] for hook in self.plugin_hooks[hook]}
|
||||
|
||||
def get_implementations(self, *types):
|
||||
result = OrderedDict()
|
||||
for h in self.plugin_hooks[hook]:
|
||||
result[h[0]] = h[1]
|
||||
return result
|
||||
|
||||
def get_implementations(self, *types, **kwargs):
|
||||
"""
|
||||
Get all mixin implementations that implement *all* of the provided ``types``.
|
||||
|
||||
@@ -1028,6 +1106,8 @@ class PluginManager(object):
|
||||
list: A list of all found implementations
|
||||
"""
|
||||
|
||||
sorting_context = kwargs.get("sorting_context", None)
|
||||
|
||||
result = None
|
||||
|
||||
for t in types:
|
||||
@@ -1038,10 +1118,28 @@ class PluginManager(object):
|
||||
result = result.intersection(implementations)
|
||||
|
||||
if result is None:
|
||||
return dict()
|
||||
return [impl[1] for impl in result]
|
||||
return []
|
||||
|
||||
def get_filtered_implementations(self, f, *types):
|
||||
def sort_func(impl):
|
||||
sorting_value = None
|
||||
if sorting_context is not None and isinstance(impl[1], SortablePlugin):
|
||||
try:
|
||||
sorting_value = impl[1].get_sorting_key(sorting_context)
|
||||
except:
|
||||
self.logger.exception("Error while trying to retrieve sorting order for plugin {}".format(impl[0]))
|
||||
|
||||
if sorting_value is not None:
|
||||
try:
|
||||
int(sorting_value)
|
||||
except ValueError:
|
||||
self.logger.warn("The order value returned by {} for sorting context {} is not a valid integer, ignoring it".format(impl[0], sorting_context))
|
||||
sorting_value = None
|
||||
|
||||
return sorting_value is None, sorting_value, impl[0]
|
||||
|
||||
return [impl[1] for impl in sorted(result, key=sort_func)]
|
||||
|
||||
def get_filtered_implementations(self, f, *types, **kwargs):
|
||||
"""
|
||||
Get all mixin implementation that implementat *all* of the provided ``types`` and match the provided filter `f`.
|
||||
|
||||
@@ -1054,7 +1152,7 @@ class PluginManager(object):
|
||||
"""
|
||||
|
||||
assert callable(f)
|
||||
implementations = self.get_implementations(*types)
|
||||
implementations = self.get_implementations(*types, sorting_context=kwargs.get("sorting_context", None))
|
||||
return filter(f, implementations)
|
||||
|
||||
def get_helpers(self, name, *helpers):
|
||||
@@ -1114,6 +1212,32 @@ class PluginManager(object):
|
||||
try: client(plugin, data)
|
||||
except: self.logger.exception("Exception while sending plugin data to client")
|
||||
|
||||
def _sort_hooks(self, hook):
|
||||
self._plugin_hooks[hook] = sorted(self._plugin_hooks[hook],
|
||||
key=lambda x: (x[0] is None, x[0], x[1], x[2]))
|
||||
|
||||
def _get_callback_and_order(self, hook):
|
||||
if callable(hook):
|
||||
return hook, None
|
||||
|
||||
elif isinstance(hook, tuple) and len(hook) == 2:
|
||||
callback, order = hook
|
||||
|
||||
# test that callback is a callable
|
||||
if not callable(callback):
|
||||
raise ValueError("Hook callback is not a callable")
|
||||
|
||||
# test that number is an int
|
||||
try:
|
||||
int(order)
|
||||
except ValueError:
|
||||
raise ValueError("Hook order is not a number")
|
||||
|
||||
return callback, order
|
||||
|
||||
else:
|
||||
raise ValueError("Invalid hook definition, neither a callable nor a 2-tuple (callback, order): {!r}".format(hook))
|
||||
|
||||
|
||||
class InstalledEntryPoint(pkginfo.Installed):
|
||||
|
||||
@@ -1207,7 +1331,35 @@ class Plugin(object):
|
||||
pass
|
||||
|
||||
class RestartNeedingPlugin(Plugin):
|
||||
pass
|
||||
"""
|
||||
Mixin for plugin types that need a restart in order to be enabled.
|
||||
"""
|
||||
|
||||
class SortablePlugin(Plugin):
|
||||
"""
|
||||
Mixin for plugin types that are sortable.
|
||||
"""
|
||||
|
||||
def get_sorting_key(self, context=None):
|
||||
"""
|
||||
Returns the sorting key to use for the implementation in the specified ``context``.
|
||||
|
||||
May return ``None`` if order is irrelevant.
|
||||
|
||||
Implementations returning None will be ordered by plugin identifier
|
||||
after all implementations which did return a sorting key value that was
|
||||
not None sorted by that.
|
||||
|
||||
Arguments:
|
||||
context (str): The sorting context for which to provide the
|
||||
sorting key value.
|
||||
|
||||
Returns:
|
||||
int or None: An integer signifying the sorting key value of the plugin
|
||||
(sorting will be done ascending), or None if the implementation
|
||||
doesn't care about calling order.
|
||||
"""
|
||||
return None
|
||||
|
||||
class PluginNeedsRestart(Exception):
|
||||
def __init__(self, name):
|
||||
|
||||
+525
-14
@@ -9,6 +9,9 @@ Please note that the plugin implementation types are documented in the section
|
||||
.. autoclass:: OctoPrintPlugin
|
||||
:show-inheritance:
|
||||
|
||||
.. autoclass:: ReloadNeedingPlugin
|
||||
:show-inheritance:
|
||||
|
||||
"""
|
||||
|
||||
from __future__ import absolute_import
|
||||
@@ -18,7 +21,7 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
from .core import (Plugin, RestartNeedingPlugin)
|
||||
from .core import (Plugin, RestartNeedingPlugin, SortablePlugin)
|
||||
|
||||
|
||||
class OctoPrintPlugin(Plugin):
|
||||
@@ -77,7 +80,7 @@ class OctoPrintPlugin(Plugin):
|
||||
and if not creating it before returning it. Injected by the plugin core system upon initialization of the
|
||||
implementation.
|
||||
|
||||
.. automethod:: get_plugin_data_folder
|
||||
.. automethod:: get_plugin_data_folder
|
||||
"""
|
||||
|
||||
def get_plugin_data_folder(self):
|
||||
@@ -97,12 +100,18 @@ class OctoPrintPlugin(Plugin):
|
||||
|
||||
|
||||
class ReloadNeedingPlugin(Plugin):
|
||||
pass
|
||||
"""
|
||||
Mixin for plugin types that need a reload of the UI in order to become usable.
|
||||
"""
|
||||
|
||||
class StartupPlugin(OctoPrintPlugin):
|
||||
class StartupPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
"""
|
||||
The ``StartupPlugin`` allows hooking into the startup of OctoPrint. It can be used to start up additional services
|
||||
on or just after the startup of the server.
|
||||
|
||||
``StartupPlugin`` is a :class:`~octoprint.plugin.core.SortablePlugin`. The
|
||||
relevant sorting context for :meth:`on_startup` is ``StartupPlugin.on_startup``,
|
||||
the one for :meth:`on_after_startup` will be ``StartupPlugin.on_after_startup``.
|
||||
"""
|
||||
|
||||
def on_startup(self, host, port):
|
||||
@@ -127,11 +136,14 @@ class StartupPlugin(OctoPrintPlugin):
|
||||
pass
|
||||
|
||||
|
||||
class ShutdownPlugin(OctoPrintPlugin):
|
||||
class ShutdownPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
"""
|
||||
The ``ShutdownPlugin`` allows hooking into the shutdown of OctoPrint. It's usually used in conjunction with the
|
||||
:class:`StartupPlugin` mixin, to cleanly shut down additional services again that where started by the :class:`StartupPlugin`
|
||||
part of the plugin.
|
||||
|
||||
``ShutdownPlugin`` is a :class:`~octoprint.plugin.core.SortablePlugin`.
|
||||
The relevant sorting context will be ``ShutdownPlugin.on_shutdown``.
|
||||
"""
|
||||
|
||||
def on_shutdown(self):
|
||||
@@ -149,6 +161,8 @@ class AssetPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
|
||||
A typical usage of the ``AssetPlugin`` functionality is to embed a custom view model to be used by templates injected
|
||||
through a :class:`TemplatePlugin`.
|
||||
|
||||
``AssetPlugin`` is a :class:`~octoprint.plugins.core.RestartNeedingPlugin`.
|
||||
"""
|
||||
|
||||
def get_asset_folder(self):
|
||||
@@ -249,6 +263,30 @@ class TemplatePlugin(OctoPrintPlugin, ReloadNeedingPlugin):
|
||||
wrapper div and the link in the navigation will have the additional classes and styles applied as defined via the
|
||||
supplied configuration supplied through :func:`get_template_configs`.
|
||||
|
||||
Wizards
|
||||
Plugins may define wizard dialogs to display to the user if necessary (e.g. in case of missing information that
|
||||
needs to be queried from the user to make the plugin work). Note that with the current implementations, all
|
||||
wizard dialogs will be will always be sorted by their ``mandatory`` attribute (which defaults to ``False``) and then
|
||||
alphabetically by their ``name``. Hence, mandatory wizard steps will come first, sorted alphabetically, then the
|
||||
optional steps will follow, also alphabetically. A wizard dialog provided through a plugin will only be displayed
|
||||
if the plugin reports the wizard as being required through :meth:`~octoprint.plugin.WizardPlugin.is_wizard_required`.
|
||||
Please also refer to the :class:`~octoprint.plugin.WizardPlugin` mixin for further details on this.
|
||||
|
||||
The included template must be called ``<plugin identifier>_wizard.jinja2`` (e.g. ``myplugin_wizard.jinja2``) unless
|
||||
overridden by the configuration supplied through :func:`get_template_configs`.
|
||||
|
||||
The template will be already wrapped into the necessary structure, plugins just need to supply the pure content.
|
||||
The wrapper div and the link in the wizard navigation will have the additional classes and styles applied as defined
|
||||
via the supplied configuration supplied through :func:`get_template_configs`.
|
||||
|
||||
.. note::
|
||||
|
||||
A note about ``mandatory`` wizard steps: In the current implementation, marking a wizard step as
|
||||
mandatory will *only* make it styled accordingly. It is the task of the :ref:`view model <sec-plugins-viewmodels>`
|
||||
to actually prevent the user from skipping the dialog by implementing the ``onWizardTabChange``
|
||||
callback and returning ``false`` there if it is detected that the user hasn't yet filled in the
|
||||
wizard step.
|
||||
|
||||
Generic
|
||||
Plugins may also inject arbitrary templates into the page of the web interface itself, e.g. in order to
|
||||
add overlays or dialogs to be called from within the plugin's javascript code.
|
||||
@@ -273,6 +311,8 @@ class TemplatePlugin(OctoPrintPlugin, ReloadNeedingPlugin):
|
||||
responsibility to ensure that all core functionality is still maintained.
|
||||
|
||||
Plugins can also add additional template types by implementing the :ref:`octoprint.ui.web.templatetypes <sec-plugins-hook-ui-web-templatetypes>` hook.
|
||||
|
||||
``TemplatePlugin`` is a :class:`~octoprint.plugin.core.ReloadNeedingPlugin`.
|
||||
"""
|
||||
|
||||
def get_template_configs(self):
|
||||
@@ -396,6 +436,17 @@ class TemplatePlugin(OctoPrintPlugin, ReloadNeedingPlugin):
|
||||
* - styles_content
|
||||
- Like ``styles`` but only applied to the content pane itself.
|
||||
|
||||
``wizard`` type
|
||||
|
||||
.. list-table::
|
||||
:widths: 5 95
|
||||
|
||||
* - mandatory
|
||||
- Whether the wizard step is mandatory (True) or not (False). Optional,
|
||||
defaults to False. If set to True, OctoPrint will sort visually mark
|
||||
the step as mandatory in the UI (bold in the navigation and a little
|
||||
alert) and also sort it into the first half.
|
||||
|
||||
.. note::
|
||||
|
||||
As already outlined above, each template type has a default template name (i.e. the default navbar template
|
||||
@@ -450,6 +501,357 @@ class TemplatePlugin(OctoPrintPlugin, ReloadNeedingPlugin):
|
||||
return os.path.join(self._basefolder, "templates")
|
||||
|
||||
|
||||
class UiPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
"""
|
||||
The ``UiPlugin`` mixin allows plugins to completely replace the UI served
|
||||
by OctoPrint when requesting the main page hosted at `/`.
|
||||
|
||||
OctoPrint will query whether your mixin implementation will handle a
|
||||
provided request by calling :meth:`~octoprint.plugin.UiPlugin.will_handle_ui` with the Flask
|
||||
`Request <http://flask.pocoo.org/docs/0.10/api/#flask.Request>`_ object as
|
||||
parameter. If you plugin returns `True` here, OctoPrint will next call
|
||||
:meth:`~octoprint.plugin.UiPlugin.on_ui_render` with a couple of parameters like
|
||||
- again - the Flask Request object and the render keyword arguments as
|
||||
used by the default OctoPrint web interface. For more information see below.
|
||||
|
||||
There are two methods used in order to allow for caching of the actual
|
||||
response sent to the client. Whatever a plugin implementation returns
|
||||
from the call to its :meth:`~octoprint.plugin.UiPlugin.on_ui_render` method
|
||||
will be cached server side. The cache will be emptied in case of explicit
|
||||
no-cache headers sent by the client, or if the ``_refresh`` query parameter
|
||||
on the request exists and is set to ``true``. To prevent caching of the
|
||||
response altogether, a plugin may set no-cache headers on the returned
|
||||
response as well.
|
||||
|
||||
``UiPlugin`` is a :class:`~octoprint.plugin.core.SortablePlugin`. The
|
||||
relevant sorting context when acting as a UiPlugin is ``UiPlugin.will_handle_ui``.
|
||||
The first plugin to return ``True`` will be the one whose ui will be used,
|
||||
no further calls to :meth:`~octoprint.plugin.UiPlugin.on_ui_render` will be performed.
|
||||
|
||||
If implementations want to serve custom templates in the :meth:`~octoprint.plugin.UiPlugin.on_ui_render`
|
||||
method it is recommended to also implement the :class:`~octoprint.plugin.TemplatePlugin`
|
||||
mixin.
|
||||
|
||||
**Example**
|
||||
|
||||
What follows is a very simple example that renders a different (non functional and
|
||||
only exemplary) UI if the requesting client has a UserAgent string hinting
|
||||
at it being a mobile device:
|
||||
|
||||
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/dummy_mobile_ui/__init__.py
|
||||
:linenos:
|
||||
:tab-width: 4
|
||||
:caption: `dummy_mobile_ui/__init__.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/dummy_mobile_ui/__init__.py>`_
|
||||
|
||||
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/dummy_mobile_ui/templates/dummy_mobile_ui_index.jinja2
|
||||
:linenos:
|
||||
:tab-width: 4
|
||||
:caption: `dummy_mobile_ui/templates/dummy_mobile_ui_index.jinja2 <https://github.com/OctoPrint/Plugin-Examples/blob/master/dummy_mobile_ui/templates/dummy_mobile_ui_index.jinja2>`_
|
||||
|
||||
Try installing the above plugin ``dummy_mobile_ui`` (also available in the
|
||||
`plugin examples repository <https://github.com/OctoPrint/Plugin-Examples/blob/master/dummy_mobile_ui>`_)
|
||||
into your OctoPrint instance. If you access it from a regular desktop browser,
|
||||
you should still see the default UI. However if you access it from a mobile
|
||||
device (make sure to not have that request the desktop version of pages!)
|
||||
you should see the very simple dummy page defined above.
|
||||
"""
|
||||
|
||||
def will_handle_ui(self, request):
|
||||
"""
|
||||
Called by OctoPrint to determine if the mixin implementation will be
|
||||
able to handle the ``request`` provided as a parameter.
|
||||
|
||||
Return ``True`` here to signal that your implementation will handle
|
||||
the request and that the result of its :meth:`~octoprint.plugin.UiPlugin.on_ui_render` method
|
||||
is what should be served to the user.
|
||||
|
||||
Arguments:
|
||||
request (flask.Request): A Flask `Request <http://flask.pocoo.org/docs/0.10/api/#flask.Request>`_
|
||||
object.
|
||||
|
||||
Returns:
|
||||
bool: ``True`` if the the implementation will serve the request,
|
||||
``False`` otherwise.
|
||||
"""
|
||||
return False
|
||||
|
||||
def on_ui_render(self, now, request, render_kwargs):
|
||||
"""
|
||||
Called by OctoPrint to retrieve the response to send to the client
|
||||
for the ``request`` to ``/``. Only called if :meth:`~octoprint.plugin.UiPlugin.will_handle_ui`
|
||||
returned ``True``.
|
||||
|
||||
``render_kwargs`` will be a dictionary (whose contents are cached) which
|
||||
will contain the following key and value pairs (note that not all
|
||||
key value pairs contained in the dictionary are listed here, only
|
||||
those you should depend on as a plugin developer at the current time):
|
||||
|
||||
.. list-table::
|
||||
:widths: 5 95
|
||||
|
||||
* - debug
|
||||
- ``True`` if debug mode is enabled, ``False`` otherwise.
|
||||
* - firstRun
|
||||
- ``True`` if the server is being run for the first time (not
|
||||
configured yet), ``False`` otherwise.
|
||||
* - version
|
||||
- OctoPrint's version information. This is a ``dict`` with the
|
||||
following keys:
|
||||
|
||||
.. list-table::
|
||||
:widths: 5 95
|
||||
|
||||
* - number
|
||||
- The version number (e.g. ``x.y.z``)
|
||||
* - branch
|
||||
- The GIT branch from which the OctoPrint instance was built
|
||||
(e.g. ``master``)
|
||||
* - display
|
||||
- The full human readable version string, including the
|
||||
branch information (e.g. ``x.y.z (master branch)``
|
||||
|
||||
* - uiApiKey
|
||||
- The UI API key to use for unauthorized API requests. This is
|
||||
freshly generated on every server restart.
|
||||
* - templates
|
||||
- Template data to render in the UI. Will be a ``dict`` containing entries
|
||||
for all known template types.
|
||||
|
||||
The sub structure for each key will be as follows:
|
||||
|
||||
.. list-table::
|
||||
:widths: 5 95
|
||||
|
||||
* - order
|
||||
- A list of template names in the order they should appear
|
||||
in the final rendered page
|
||||
* - entries
|
||||
- The template entry definitions to render. Depending on the
|
||||
template type those are either 2-tuples of a name and a ``dict``
|
||||
or directly ``dicts`` with information regarding the
|
||||
template to render.
|
||||
|
||||
For the possible contents of the data ``dicts`` see the
|
||||
:class:`~octoprint.plugin.TemplatePlugin` mixin.
|
||||
|
||||
* - pluginNames
|
||||
- A list of names of :class:`~octoprint.plugin.TemplatePlugin`
|
||||
implementation that were enabled when creating the ``templates``
|
||||
value.
|
||||
* - locales
|
||||
- The locales for which there are translations available.
|
||||
|
||||
On top of that all additional template variables as provided by :meth:`~octoprint.plugin.TemplatePlugin.get_template_vars`
|
||||
will be contained in the dictionary as well.
|
||||
|
||||
Arguments:
|
||||
now (datetime.datetime): The datetime instance representing "now"
|
||||
for this request, in case your plugin implementation needs this
|
||||
information.
|
||||
request (flask.Request): A Flask `Request <http://flask.pocoo.org/docs/0.10/api/#flask.Request>`_ object.
|
||||
render_kwargs (dict): The (cached) render keyword arguments that
|
||||
would usually be provided to the core UI render function.
|
||||
|
||||
Returns:
|
||||
flask.Response: Should return a Flask `Response <http://flask.pocoo.org/docs/0.10/api/#flask.Response>`_
|
||||
object that can be served to the requesting client directly. May be
|
||||
created with ``flask.make_response`` combined with something like
|
||||
``flask.render_template``.
|
||||
"""
|
||||
|
||||
return None
|
||||
|
||||
|
||||
class WizardPlugin(OctoPrintPlugin, ReloadNeedingPlugin):
|
||||
"""
|
||||
The ``WizardPlugin`` mixin allows plugins to report to OctoPrint whether
|
||||
the ``wizard`` templates they define via the :class:`~octoprint.plugin.TemplatePlugin`
|
||||
should be displayed to the user, what details to provide to their respective
|
||||
wizard frontend components and what to do when the wizard is finished
|
||||
by the user.
|
||||
|
||||
OctoPrint will only display such wizard dialogs to the user which belong
|
||||
to plugins that
|
||||
|
||||
* report ``True`` in their :func:`is_wizard_required` method and
|
||||
* have not yet been shown to the user in the version currently being reported
|
||||
by the :meth:`~octoprint.plugin.WizardPlugin.get_wizard_version` method
|
||||
|
||||
Example: If a plugin with the identifier ``myplugin`` has a specific
|
||||
setting ``some_key`` it needs to have filled by the user in order to be
|
||||
able to work at all, it would probably test for that setting's value in
|
||||
the :meth:`~octoprint.plugin.WizardPlugin.is_wizard_required` method and
|
||||
return ``True`` if the value is unset:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
class MyPlugin(octoprint.plugin.SettingsPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.WizardPlugin):
|
||||
|
||||
def get_default_settings(self):
|
||||
return dict(some_key=None)
|
||||
|
||||
def is_wizard_required(self):
|
||||
return self._settings.get(["some_key"]) is None
|
||||
|
||||
OctoPrint will then display the wizard dialog provided by the plugin through
|
||||
the :class:`TemplatePlugin` mixin. Once the user finishes the wizard on the
|
||||
frontend, OctoPrint will store that it already showed the wizard of ``myplugin``
|
||||
in the version reported by :meth:`~octoprint.plugin.WizardPlugin.get_wizard_version`
|
||||
- here ``None`` since that is the default value returned by that function
|
||||
and the plugin did not override it.
|
||||
|
||||
If the plugin in a later version needs another setting from the user in order
|
||||
to function, it will also need to change the reported version in order to
|
||||
have OctoPrint reshow the dialog. E.g.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
class MyPlugin(octoprint.plugin.SettingsPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.WizardPlugin):
|
||||
|
||||
def get_default_settings(self):
|
||||
return dict(some_key=None, some_other_key=None)
|
||||
|
||||
def is_wizard_required(self):
|
||||
some_key_unset = self._settings.get(["some_key"]) is None
|
||||
some_other_key_unset = self._settings.get(["some_other_key"]) is None
|
||||
|
||||
return some_key_unset or some_other_key_unset
|
||||
|
||||
def get_wizard_version(self):
|
||||
return 1
|
||||
|
||||
``WizardPlugin`` is a :class:`~octoprint.plugin.core.ReloadNeedingPlugin`.
|
||||
"""
|
||||
|
||||
def is_wizard_required(self):
|
||||
"""
|
||||
Allows the plugin to report whether it needs to display a wizard to the
|
||||
user or not.
|
||||
|
||||
Defaults to ``False``.
|
||||
|
||||
OctoPrint will only include those wizards from plugins which are reporting
|
||||
their wizards as being required through this method returning ``True``.
|
||||
Still, if OctoPrint already displayed that wizard in the same version
|
||||
to the user once it won't be displayed again regardless whether this
|
||||
method returns ``True`` or not.
|
||||
"""
|
||||
return False
|
||||
|
||||
def get_wizard_version(self):
|
||||
"""
|
||||
The version of this plugin's wizard. OctoPrint will only display a wizard
|
||||
of the same plugin and wizard version once to the user. After they
|
||||
finish the wizard, OctoPrint will remember that it already showed this
|
||||
wizard in this particular version and not reshow it.
|
||||
|
||||
If a plugin needs to show its wizard to the user again (e.g. because
|
||||
of changes in the required settings), increasing this value is the
|
||||
way to notify OctoPrint of these changes.
|
||||
|
||||
Returns:
|
||||
int or None: an int signifying the current wizard version, should be incremented by plugins whenever there
|
||||
are changes to the plugin that might necessitate reshowing the wizard if it is required. ``None``
|
||||
will also be accepted and lead to the wizard always be ignored unless it has never been finished
|
||||
so far
|
||||
"""
|
||||
return None
|
||||
|
||||
def get_wizard_details(self):
|
||||
"""
|
||||
Called by OctoPrint when the wizard wrapper dialog is shown. Allows the plugin to return data
|
||||
that will then be made available to the view models via the view model callback ``onWizardDetails``.
|
||||
|
||||
Use this if your plugin's view model that handles your wizard dialog needs additional
|
||||
data to perform its task.
|
||||
|
||||
Returns:
|
||||
dict: a dictionary containig additional data to provide to the frontend. Whatever the plugin
|
||||
returns here will be made available on the wizard API under the plugin's identifier
|
||||
"""
|
||||
return dict()
|
||||
|
||||
def on_wizard_finish(self, handled):
|
||||
"""
|
||||
Called by OctoPrint whenever the user finishes a wizard session is finished.
|
||||
|
||||
The ``handled`` parameter will indicate whether that plugin's wizard was
|
||||
included in the wizard dialog presented to the user (so the plugin providing
|
||||
it was reporting that the wizard was required and the wizard plus version was not
|
||||
ignored/had already been seen).
|
||||
|
||||
Use this to do any clean up tasks necessary after wizard completion.
|
||||
|
||||
Arguments:
|
||||
handled (bool): True if the plugin's wizard was previously reported as
|
||||
required, not ignored and thus presented to the user,
|
||||
False otherwise
|
||||
"""
|
||||
pass
|
||||
|
||||
@classmethod
|
||||
def is_wizard_ignored(cls, seen_wizards, implementation):
|
||||
"""
|
||||
Determines whether the provided implementation is ignored based on the
|
||||
provided information about already seen wizards and their versions or not.
|
||||
|
||||
A wizard is ignored if
|
||||
|
||||
* the current and seen versions are identical
|
||||
* the current version is None and the seen version is not
|
||||
* the current version is less or equal than the seen one
|
||||
|
||||
.. code-block:: none
|
||||
|
||||
| current |
|
||||
| N | 1 | 2 | N = None
|
||||
----+---+---+---+ X = ignored
|
||||
s N | X | | |
|
||||
e --+---+---+---+
|
||||
e 1 | X | X | |
|
||||
n --+---+---+---+
|
||||
2 | X | X | X |
|
||||
----+---+---+---+
|
||||
|
||||
Arguments:
|
||||
seen_wizards (dict): A dictionary with information about already seen
|
||||
wizards and their versions. Mappings from the identifiers of
|
||||
the plugin providing the wizard to the reported wizard
|
||||
version (int or None) that was already seen by the user.
|
||||
implementation (object): The plugin implementation to check.
|
||||
|
||||
Returns:
|
||||
bool: False if the provided ``implementation`` is either not a :class:`WizardPlugin`
|
||||
or has not yet been seen (in this version), True otherwise
|
||||
"""
|
||||
|
||||
if not isinstance(implementation, cls):
|
||||
return False
|
||||
|
||||
name = implementation._identifier
|
||||
if not name in seen_wizards:
|
||||
return False
|
||||
|
||||
seen = seen_wizards[name]
|
||||
wizard_version = implementation.get_wizard_version()
|
||||
|
||||
current = None
|
||||
if wizard_version is not None:
|
||||
try:
|
||||
current = int(wizard_version)
|
||||
except ValueError as e:
|
||||
import logging
|
||||
logging.getLogger(__name__).log("WizardPlugin {} returned invalid value {} for wizard version: {}".format(name, wizard_version, str(e)))
|
||||
|
||||
return (current == seen) \
|
||||
or (current is None and seen is not None) \
|
||||
or (current <= seen)
|
||||
|
||||
|
||||
class SimpleApiPlugin(OctoPrintPlugin):
|
||||
"""
|
||||
Utilizing the ``SimpleApiPlugin`` mixin plugins may implement a simple API based around one GET resource and one
|
||||
@@ -627,6 +1029,8 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
|
||||
flask.url_for("plugin.myblueprintplugin.myEcho") # will return "/plugin/myblueprintplugin/echo"
|
||||
|
||||
|
||||
``BlueprintPlugin`` implements :class:`~octoprint.plugins.core.RestartNeedingPlugin`.
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
@@ -651,6 +1055,24 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
return f
|
||||
return decorator
|
||||
|
||||
@staticmethod
|
||||
def errorhandler(code_or_exception):
|
||||
"""
|
||||
A decorator to mark errorhandlings methods in your BlueprintPlugin subclass. Works just the same as Flask's
|
||||
own ``errorhandler`` decorator available on blueprints.
|
||||
|
||||
See `the documentation for flask.Blueprint.errorhandler <http://flask.pocoo.org/docs/0.10/api/#flask.Blueprint.errorhandler>`_
|
||||
and `the documentation for flask.Flask.errorhandler <http://flask.pocoo.org/docs/0.10/api/#flask.Flask.errorhandler>`_ for more
|
||||
information.
|
||||
"""
|
||||
from collections import defaultdict
|
||||
def decorator(f):
|
||||
if not hasattr(f, "_blueprint_error_handler") or f._blueprint_error_handler is None:
|
||||
f._blueprint_error_handler = defaultdict(list)
|
||||
f._blueprint_error_handler[f.__name__].append(code_or_exception)
|
||||
return f
|
||||
return decorator
|
||||
|
||||
def get_blueprint(self):
|
||||
"""
|
||||
Creates and returns the blueprint for your plugin. Override this if you want to define and handle your blueprint yourself.
|
||||
@@ -660,15 +1082,34 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
:return: the blueprint ready to be registered with Flask
|
||||
"""
|
||||
|
||||
if hasattr(self, "_blueprint"):
|
||||
# if we already constructed the blueprint and hence have it cached,
|
||||
# return that instance - we don't want to instance it multiple times
|
||||
return self._blueprint
|
||||
|
||||
import flask
|
||||
kwargs = self.get_blueprint_kwargs()
|
||||
blueprint = flask.Blueprint("plugin." + self._identifier, self._identifier, **kwargs)
|
||||
|
||||
# we now iterate over all members of ourselves and look if we find an attribute
|
||||
# that has data originating from one of our decorators - we ignore anything
|
||||
# starting with a _ to only handle public stuff
|
||||
for member in [member for member in dir(self) if not member.startswith("_")]:
|
||||
f = getattr(self, member)
|
||||
|
||||
if hasattr(f, "_blueprint_rules") and member in f._blueprint_rules:
|
||||
# this attribute was annotated with our @route decorator
|
||||
for blueprint_rule in f._blueprint_rules[member]:
|
||||
rule, options = blueprint_rule
|
||||
blueprint.add_url_rule(rule, options.pop("endpoint", f.__name__), view_func=f, **options)
|
||||
|
||||
if hasattr(f, "_blueprint_error_handler") and member in f._blueprint_error_handler:
|
||||
# this attribute was annotated with our @error_handler decorator
|
||||
for code_or_exception in f._blueprint_error_handler[member]:
|
||||
blueprint.errorhandler(code_or_exception)(f)
|
||||
|
||||
# cache and return the blueprint object
|
||||
self._blueprint = blueprint
|
||||
return blueprint
|
||||
|
||||
def get_blueprint_kwargs(self):
|
||||
@@ -764,6 +1205,9 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
the plugin core system upon initialization of the implementation.
|
||||
"""
|
||||
|
||||
config_version_key = "_config_version"
|
||||
"""Key of the field in the settings that holds the configuration format version."""
|
||||
|
||||
def on_settings_load(self):
|
||||
"""
|
||||
Loads the settings for the plugin, called by the Settings API view in order to retrieve all settings from
|
||||
@@ -781,9 +1225,9 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
|
||||
:return: the current settings of the plugin, as a dictionary
|
||||
"""
|
||||
data = self._settings.get([], asdict=True, merged=True)
|
||||
if "_config_version" in data:
|
||||
del data["_config_version"]
|
||||
data = self._settings.get_all_data()
|
||||
if self.config_version_key in data:
|
||||
del data[self.config_version_key]
|
||||
return data
|
||||
|
||||
def on_settings_save(self, data):
|
||||
@@ -795,7 +1239,8 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
.. note::
|
||||
|
||||
The default implementation will persist your plugin's settings as is, so just in the structure and in the
|
||||
types that were received by the Settings API view.
|
||||
types that were received by the Settings API view. Values identical to the default settings values
|
||||
will *not* be persisted.
|
||||
|
||||
If you need more granular control here, e.g. over the used data types, you'll need to override this method
|
||||
and iterate yourself over all your settings, retrieving them (if set) from the supplied received ``data``
|
||||
@@ -803,15 +1248,38 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
|
||||
Arguments:
|
||||
data (dict): The settings dictionary to be saved for the plugin
|
||||
|
||||
Returns:
|
||||
dict: The settings that differed from the defaults and were actually saved.
|
||||
"""
|
||||
import octoprint.util
|
||||
|
||||
if "_config_version" in data:
|
||||
del data["_config_version"]
|
||||
# get the current data
|
||||
current = self._settings.get_all_data()
|
||||
if current is None:
|
||||
current = dict()
|
||||
|
||||
current = self._settings.get([], asdict=True, merged=True)
|
||||
merged = octoprint.util.dict_merge(current, data)
|
||||
self._settings.set([], merged)
|
||||
# merge our new data on top of it
|
||||
new_current = octoprint.util.dict_merge(current, data)
|
||||
if self.config_version_key in new_current:
|
||||
del new_current[self.config_version_key]
|
||||
|
||||
# determine diff dict that contains minimal set of changes against the
|
||||
# default settings - we only want to persist that, not everything
|
||||
diff = octoprint.util.dict_minimal_mergediff(self.get_settings_defaults(), new_current)
|
||||
|
||||
version = self.get_settings_version()
|
||||
|
||||
to_persist = dict(diff)
|
||||
if version:
|
||||
to_persist[self.config_version_key] = version
|
||||
|
||||
if to_persist:
|
||||
self._settings.set([], to_persist)
|
||||
else:
|
||||
self._settings.clean_all_data()
|
||||
|
||||
return diff
|
||||
|
||||
def get_settings_defaults(self):
|
||||
"""
|
||||
@@ -894,6 +1362,49 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
"""
|
||||
pass
|
||||
|
||||
def on_settings_cleanup(self):
|
||||
"""
|
||||
Called after migration and initialization but before call to :func:`on_settings_initialized`.
|
||||
|
||||
Plugins may overwrite this method to perform additional clean up tasks.
|
||||
|
||||
The default implementation just minimizes the data persisted on disk to only contain
|
||||
the differences to the defaults (in case the current data was persisted with an older
|
||||
version of OctoPrint that still duplicated default data).
|
||||
"""
|
||||
import octoprint.util
|
||||
from octoprint.settings import NoSuchSettingsPath
|
||||
|
||||
try:
|
||||
# let's fetch the current persisted config (so only the data on disk,
|
||||
# without the defaults)
|
||||
config = self._settings.get_all_data(merged=False, incl_defaults=False, error_on_path=True)
|
||||
except NoSuchSettingsPath:
|
||||
# no config persisted, nothing to do => get out of here
|
||||
return
|
||||
|
||||
if config is None:
|
||||
# config is set to None, that doesn't make sense, kill it and leave
|
||||
self._settings.clean_all_data()
|
||||
return
|
||||
|
||||
if self.config_version_key in config and config[self.config_version_key] is None:
|
||||
# delete None entries for config version - it's the default, no need
|
||||
del config[self.config_version_key]
|
||||
|
||||
# calculate a minimal diff between the settings and the current config -
|
||||
# anything already in the settings will be removed from the persisted
|
||||
# config, no need to duplicate it
|
||||
defaults = self.get_settings_defaults()
|
||||
diff = octoprint.util.dict_minimal_mergediff(defaults, config)
|
||||
|
||||
if not diff:
|
||||
# no diff to defaults, no need to have anything persisted
|
||||
self._settings.clean_all_data()
|
||||
else:
|
||||
# diff => persist only that
|
||||
self._settings.set([], diff)
|
||||
|
||||
def on_settings_initialized(self):
|
||||
"""
|
||||
Called after the settings have been initialized and - if necessary - also been migrated through a call to
|
||||
|
||||
Reference in new issue
Block a user