Merge branch 'devel' into dev/jsclientdocs

This commit is contained in:
Gina Häußge committed 2016-06-28 18:28:55 +02:00
commit cd71efdc71
38 files changed
+1623 -415

No files matched your search

+4 -4
View File
@@ -16,11 +16,11 @@ rc
HEAD
\(detached.*
# maintenance is currently the branch for preparation of maintenance release 1.2.13
# maintenance is currently the branch for preparation of maintenance release 1.2.14
# so are any fix/... and improve/... branches
maintenance 1.2.13 685ce16c85eea9c4f11586ea99c9a84aca382bd4 pep440-dev
fix/.* 1.2.13 685ce16c85eea9c4f11586ea99c9a84aca382bd4 pep440-dev
improve/.* 1.2.13 685ce16c85eea9c4f11586ea99c9a84aca382bd4 pep440-dev
maintenance 1.2.14 cb2e0d449f607bbc89c7ad13c983a0cf11bbfdee pep440-dev
fix/.* 1.2.14 cb2e0d449f607bbc89c7ad13c983a0cf11bbfdee pep440-dev
improve/.* 1.2.14 cb2e0d449f607bbc89c7ad13c983a0cf11bbfdee pep440-dev
# every other branch is a development branch and thus gets resolved to 1.3.0-dev for now
.* 1.3.0 198d3450d94be1a2 pep440-dev
+1
View File
@@ -68,6 +68,7 @@ date of first contribution):
* [Philipp Baum](https://github.com/philphilphil)
* [Kyle Evans](https://github.com/kevans91)
* [Javier Martínez Arrieta](https://github.com/Javierma)
* ["MirceaDan"](https://github.com/ByReaL)
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
[Daid Braam](https://github.com/daid). Parts of its communication layer and
+12
View File
@@ -74,6 +74,18 @@
* [#1047](https://github.com/foosel/OctoPrint/issues/1047) - Fixed 90 degree
webcam rotation for iOS Safari.
## 1.2.13 (2016-06-16)
### Bug Fixes
* [#1373](https://github.com/foosel/OctoPrint/issues/1373): Don't parse `B:` as bed temperature when it shows up as part of a position report from `M114`.
* [#1374](https://github.com/foosel/OctoPrint/issues/1374): Don't try to perform a passive login when the components we'd need to inform about a change in login state aren't yet available. Solves a bug that lead - among other things - to the Plugin Manager and the Software Update Plugin not showing anything but misleading errors until the user logged out and back in.
* Fixed the temperature graph staying uninitialized until a connection to a printer was established.
* Fixed an error causing issues during frontend startup if the browser doesn't support tracking browser visibility.
* Fixed an error causing issues during frontend startup if the browser doesn't support the capabilities needed for the GCODE viewer.
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.12...1.2.13))
## 1.2.12 (2016-06-09)
### Improvements
+5 -4
View File
@@ -216,10 +216,6 @@ Progress information
File related
============
.. todo::
Update to reflect enhanced data now available.
.. _sec-api-datamodel-files-file:
File information
@@ -242,6 +238,11 @@ File information
- String
- Type of file. ``model`` or ``machinecode``. Or ``folder`` if it's a folder, in which case the ``children``
node will be populated
* - ``typePath``
- 1
- list
- Path to type of file in extension tree. E.g. ``["model", "stl"]`` for ``.stl`` files, or ``["machinecode", "gcode"]``
for ``.gcode`` files. ``["folder"]`` for folders.
Additional properties depend on ``type``. For a ``type`` value of ``folder``, see "Folders". For any other value
see "Files".
+8
View File
@@ -352,7 +352,9 @@ SlicingStarted
Payload:
* ``stl``: the STL's filename
* ``stl_location``: the STL's location
* ``gcode``: the sliced GCODE's filename
* ``gcode_location``: the sliced GCODE's location
* ``progressAvailable``: true if progress information via the ``slicingProgress`` push update will be available, false if not
SlicingDone
@@ -361,7 +363,9 @@ SlicingDone
Payload:
* ``stl``: the STL's filename
* ``stl_location``: the STL's location
* ``gcode``: the sliced GCODE's filename
* ``gcode_location``: the sliced GCODE's location
* ``time``: the time needed for slicing, in seconds (float)
SlicingCancelled
@@ -371,7 +375,9 @@ SlicingCancelled
Payload:
* ``stl``: the STL's filename
* ``stl_location``: the STL's location
* ``gcode``: the sliced GCODE's filename
* ``gcode_location``: the sliced GCODE's location
SlicingFailed
The slicing of a file has failed.
@@ -379,7 +385,9 @@ SlicingFailed
Payload:
* ``stl``: the STL's filename
* ``stl_location``: the STL's location
* ``gcode``: the sliced GCODE's filename
* ``gcode_location``: the sliced GCODE's location
* ``reason``: the reason for the slicing having failed
SlicingProfileAdded
+32
View File
@@ -676,6 +676,38 @@ octoprint.filemanager.preprocessor
:return: The `file_object` as passed in or None, or a replaced version to use instead for further processing.
:rtype: AbstractFileWrapper or None
.. _sec-plugins-hook-printer-factory:
octoprint.printer.factory
~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: hook(components, *args, **kwargs)
Return a :class:`~octoprint.printer.PrinterInstance` instance to use as global printer object. This will
be called only once during initial server startup.
The provided ``components`` is a dictionary containing the already initialized system components:
* ``plugin_manager``: The :class:`~octoprint.plugin.core.PluginManager`
* ``printer_profile_manager``: The :class:`~octoprint.printer.profile.PrinterProfileManager`
* ``event_bus``: The :class:`~octoprint.events.EventManager`
* ``analysis_queue``: The :class:`~octoprint.filemanager.analysis.AnalysisQueue`
* ``slicing_manager``: The :class:`~octoprint.slicing.SlicingManager`
* ``file_manager``: The :class:`~octoprint.filemanager.FileManager`
* ``app_session_manager``: The :class:`~octoprint.server.util.flask.AppSessionManager`
* ``plugin_lifecycle_manager``: The :class:`~octoprint.server.LifecycleManager`
* ``user_manager``: The :class:`~octoprint.users.UserManager`
* ``preemptive_cache``: The :class:`~octoprint.server.util.flask.PreemptiveCache`
If the factory returns anything but ``None``, it will be assigned to the global ``printer`` instance.
If no of the registered factories return a printer instance, the default :class:`~octoprint.printer.standard.Printer`
class will be instantiated.
:param dict components: System components to use for printer instance initialization
:return: The ``printer`` instance to use globally.
:rtype: PrinterInterface subclass or None
.. _sec-plugins-hook-server-http-bodysize:
octoprint.server.http.bodysize
+2 -1
View File
@@ -37,7 +37,8 @@ INSTALL_REQUIRES = [
"psutil>=3.2.1,<3.3",
"Click>=6.2,<6.3",
"awesome-slugify>=1.6.5,<1.7",
"feedparser>=5.2.1,<5.3"
"feedparser>=5.2.1,<5.3",
"chainmap>=1.0.2,<1.1"
]
# Additional requirements for optional install options
+60 -1
View File
@@ -201,8 +201,67 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con
def init_pluginsystem(settings):
"""Initializes the plugin manager based on the settings."""
from octoprint.plugin import plugin_manager
return plugin_manager(init=True, settings=settings)
pm = plugin_manager(init=True, settings=settings)
logger = logging.getLogger(__name__)
settings_overlays = dict()
disabled_from_overlays = dict()
def handle_plugin_loaded(name, plugin):
if hasattr(plugin.instance, "__plugin_settings_overlay__"):
plugin.needs_restart = True
# plugin has a settings overlay, inject it
overlay_definition = getattr(plugin.instance, "__plugin_settings_overlay__")
if isinstance(overlay_definition, (tuple, list)):
overlay_definition, order = overlay_definition
else:
order = None
overlay = settings.load_overlay(overlay_definition)
if "plugins" in overlay and "_disabled" in overlay["plugins"]:
disabled_plugins = overlay["plugins"]["_disabled"]
del overlay["plugins"]["_disabled"]
disabled_from_overlays[name] = (disabled_plugins, order)
settings_overlays[name] = overlay
logger.debug("Found settings overlay on plugin {}".format(name))
def handle_plugins_loaded(startup=False, initialize_implementations=True, force_reload=None):
if not startup:
return
sorted_disabled_from_overlays = sorted([(key, value[0], value[1]) for key, value in disabled_from_overlays.items()], key=lambda x: (x[2] is None, x[2], x[0]))
disabled_list = pm.plugin_disabled_list
already_processed = []
for name, addons, _ in sorted_disabled_from_overlays:
if not name in disabled_list and not name.endswith("disabled"):
for addon in addons:
if addon in disabled_list:
continue
if addon in already_processed:
logger.info("Plugin {} wants to disable plugin {}, but that was already processed".format(name, addon))
if not addon in already_processed and not addon in disabled_list:
disabled_list.append(addon)
logger.info("Disabling plugin {} as defined by plugin {} through settings overlay".format(addon, name))
already_processed.append(name)
def handle_plugin_enabled(name, plugin):
if name in settings_overlays:
settings.add_overlay(settings_overlays[name])
logger.info("Added settings overlay from plugin {}".format(name))
pm.on_plugin_loaded = handle_plugin_loaded
pm.on_plugins_loaded = handle_plugins_loaded
pm.on_plugin_enabled = handle_plugin_enabled
pm.reload_plugins(startup=True, initialize_implementations=False)
return pm
#~~ server main method
+19 -4
View File
@@ -244,9 +244,16 @@ class FileManager(object):
def stlProcessed(source_location, source_path, tmp_path, dest_location, dest_path, start_time, printer_profile_id, callback, callback_args, _error=None, _cancelled=False, _analysis=None):
try:
if _error:
eventManager().fire(Events.SLICING_FAILED, {"stl": source_path, "gcode": dest_path, "reason": _error})
eventManager().fire(Events.SLICING_FAILED, dict(stl=source_path,
stl_location=source_location,
gcode=dest_path,
gcode_location=dest_location,
reason=_error))
elif _cancelled:
eventManager().fire(Events.SLICING_CANCELLED, {"stl": source_path, "gcode": dest_path})
eventManager().fire(Events.SLICING_CANCELLED, dict(stl=source_path,
stl_location=source_location,
gcode=dest_path,
gcode_location=dest_location))
else:
source_meta = self.get_metadata(source_location, source_path)
hash = source_meta["hash"]
@@ -262,7 +269,11 @@ class FileManager(object):
self.add_file(dest_location, dest_path, file_obj, links=links, allow_overwrite=True, printer_profile=printer_profile, analysis=_analysis)
end_time = time.time()
eventManager().fire(Events.SLICING_DONE, {"stl": source_path, "gcode": dest_path, "time": end_time - start_time})
eventManager().fire(Events.SLICING_DONE, dict(stl=source_path,
stl_location=source_location,
gcode=dest_path,
gcode_location=dest_location,
time=end_time - start_time))
if callback is not None:
if callback_args is None:
@@ -284,7 +295,11 @@ class FileManager(object):
import time
start_time = time.time()
eventManager().fire(Events.SLICING_STARTED, {"stl": source_path, "gcode": dest_path, "progressAvailable": slicer.get_slicer_properties()["progress_report"] if slicer else False})
eventManager().fire(Events.SLICING_STARTED, {"stl": source_path,
"stl_location": source_location,
"gcode": dest_path,
"gcode_location": dest_location,
"progressAvailable": slicer.get_slicer_properties()["progress_report"] if slicer else False})
import tempfile
f = tempfile.NamedTemporaryFile(suffix=".gco", delete=False)
+10 -4
View File
@@ -81,10 +81,12 @@ class StorageInterface(object):
"children": {
"some_sub_folder": {
"type": "folder",
"typePath": ["folder"],
"children": { ... }
},
"some_file.gcode": {
"type": "machinecode",
"typePath": ["machinecode", "gcode"],
"hash": "<sha1 hash>",
"links": [ ... ],
...
@@ -93,12 +95,14 @@ class StorageInterface(object):
}
"test.gcode": {
"type": "machinecode",
"typePath": ["machinecode", "gcode"],
"hash": "<sha1 hash>",
"links": [...],
...
},
"test.stl": {
"type": "model",
"typePath": ["model", "stl"],
"hash": "<sha1 hash>",
"links": [...],
...
@@ -1035,12 +1039,12 @@ class LocalFileStorage(StorageInterface):
# file handling
if os.path.isfile(entry_path):
file_type = octoprint.filemanager.get_file_type(entry)
if not file_type:
type_path = octoprint.filemanager.get_file_type(entry)
if not type_path:
# only supported extensions
continue
else:
file_type = file_type[0]
file_type = type_path[0]
if entry in metadata and isinstance(metadata[entry], dict):
entry_data = metadata[entry]
@@ -1056,6 +1060,7 @@ class LocalFileStorage(StorageInterface):
extended_entry_data.update(entry_data)
extended_entry_data["name"] = entry
extended_entry_data["type"] = file_type
extended_entry_data["typePath"] = type_path
stat = os.stat(entry_path)
if stat:
extended_entry_data["size"] = stat.st_size
@@ -1069,13 +1074,14 @@ class LocalFileStorage(StorageInterface):
entry_data = dict(
name=entry,
type="folder",
type_path=["folder"],
children=sub_result
)
if not filter or filter(entry, entry_data):
def get_size():
total_size = 0
for element in entry_data["children"].itervalues():
for element in entry_data["children"].values():
if "size" in element:
total_size += element["size"]
+67 -7
View File
@@ -134,6 +134,7 @@ class PluginInfo(object):
self.bundled = False
self.loaded = False
self.managable = True
self.needs_restart = False
self._name = name
self._version = version
@@ -472,6 +473,9 @@ class PluginManager(object):
self.on_plugin_disabled = lambda *args, **kwargs: None
self.on_plugin_implementations_initialized = lambda *args, **kwargs: None
self.on_plugins_loaded = lambda *args, **kwargs: None
self.on_plugins_enabled = lambda *args, **kwargs: None
self.registered_clients = []
self.marked_plugins = defaultdict(list)
@@ -480,8 +484,6 @@ class PluginManager(object):
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
@@ -491,9 +493,9 @@ class PluginManager(object):
cmd.finalize_options()
self._python_install_dir = cmd.install_lib
self._python_prefix = sys.prefix
self._python_prefix = os.path.realpath(sys.prefix)
self._python_virtual_env = hasattr(sys, "real_prefix") \
or (hasattr(sys, "base_prefix") and sys.prefix != sys.base_prefix)
or (hasattr(sys, "base_prefix") and os.path.realpath(sys.prefix) != os.path.realpath(sys.base_prefix))
@property
def plugins(self):
@@ -614,7 +616,11 @@ class PluginManager(object):
# 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))
or is_sub_path_of(plugin.location, self._python_prefix)
or is_editable_install(self._python_install_dir,
package_name,
module_name,
plugin.location))
plugin.enabled = False
result[key] = plugin
@@ -667,16 +673,33 @@ class PluginManager(object):
plugins = self.find_plugins(existing=dict((k, v) for k, v in self.plugins.items() if not k in force_reload))
self.disabled_plugins.update(plugins)
# 1st pass: loading the plugins
for name, plugin in plugins.items():
try:
self.load_plugin(name, plugin, startup=startup, initialize_implementation=initialize_implementations)
if not self._is_plugin_disabled(name):
except PluginNeedsRestart:
pass
except PluginLifecycleException as e:
self.logger.info(str(e))
self.on_plugins_loaded(startup=startup,
initialize_implementations=initialize_implementations,
force_reload=force_reload)
# 2nd pass: enabling those plugins that need enabling
for name, plugin in plugins.items():
try:
if plugin.loaded and not self._is_plugin_disabled(name):
self.enable_plugin(name, plugin=plugin, initialize_implementation=initialize_implementations, startup=startup)
except PluginNeedsRestart:
pass
except PluginLifecycleException as e:
self.logger.info(str(e))
self.on_plugins_enabled(startup=startup,
initialize_implementations=initialize_implementations,
force_reload=force_reload)
if len(self.enabled_plugins) <= 0:
self.logger.info("No plugins found")
else:
@@ -882,7 +905,7 @@ class PluginManager(object):
pass
def is_restart_needing_plugin(self, plugin):
return self.has_restart_needing_implementation(plugin) or self.has_restart_needing_hooks(plugin)
return plugin.needs_restart or self.has_restart_needing_implementation(plugin) or self.has_restart_needing_hooks(plugin)
def has_restart_needing_implementation(self, plugin):
if not plugin.implementation:
@@ -1239,6 +1262,43 @@ class PluginManager(object):
raise ValueError("Invalid hook definition, neither a callable nor a 2-tuple (callback, order): {!r}".format(hook))
def is_sub_path_of(path, parent):
"""
Tests if `path` is a sub path (or identical) to `path`.
>>> is_sub_path_of("/a/b/c", "/a/b")
True
>>> is_sub_path_of("/a/b/c", "/a/b2")
False
>>> is_sub_path_of("/a/b/c", "/b/c")
False
>>> is_sub_path_of("/foo/bar/../../a/b/c", "/a/b")
True
>>> is_sub_path_of("/a/b", "/a/b")
True
"""
rel_path = os.path.relpath(os.path.realpath(path),
os.path.realpath(parent))
return not (rel_path == os.pardir or
rel_path.startswith(os.pardir + os.sep))
def is_editable_install(install_dir, package, module, location):
package_link = os.path.join(install_dir, "{}.egg-link".format(package))
if os.path.isfile(package_link):
expected_target = os.path.normcase(os.path.realpath(location))
try:
with open(package_link) as f:
contents = f.readlines()
for line in contents:
target = os.path.normcase(os.path.realpath(os.path.join(line.strip(), module)))
if target == expected_target:
return True
except:
pass
return False
class InstalledEntryPoint(pkginfo.Installed):
def __init__(self, entry_point, metadata_version=None):
+10
View File
@@ -741,6 +741,16 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
"""
return None
def get_ui_preemptive_caching_enabled(self):
"""
Allows to control whether the view provided by the plugin should be preemptively
cached on server startup (default) or not.
Returns:
bool: Whether to enable preemptive caching or not
"""
return True
def get_ui_data_for_preemptive_caching(self):
"""
Allows defining additional data to be persisted in the preemptive cache configuration, on
@@ -332,7 +332,7 @@ class VirtualPrinter(object):
self._deleteSdFile(filename)
def _gcode_M114(self, data):
output = "C: X:{} Y:{} Z:{} E:{}".format(self._lastX, self._lastY, self._lastZ, self._lastE)
output = "X:{} Y:{} Z:{} E:{} Count: A:{} B:{} C:{}".format(self._lastX, self._lastY, self._lastZ, self._lastE, int(self._lastX*100), int(self.lastY*100), int(self.lastZ*100))
if not self._okBeforeCommandOutput:
output = "ok " + output
self._send(output)
+33 -24
View File
@@ -23,31 +23,15 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import re
import octoprint.util.comm as comm
from octoprint.settings import settings
from octoprint.util import deprecated
@deprecated(message="get_connection_options has been replaced by PrinterInterface.get_connection_options",
includedoc="Replaced by :func:`PrinterInterface.get_connection_options`",
since="1.3.0")
def get_connection_options():
"""
Retrieves the available ports, baudrates, preferred port and baudrate for connecting to the printer.
Returned ``dict`` has the following structure::
ports: <list of available serial ports>
baudrates: <list of available baudrates>
portPreference: <configured default serial port>
baudratePreference: <configured default baudrate>
autoconnect: <whether autoconnect upon server startup is enabled or not>
Returns:
(dict): A dictionary holding the connection options in the structure specified above
"""
return {
"ports": comm.serialList(),
"baudrates": comm.baudrateList(),
"portPreference": settings().get(["serial", "port"]),
"baudratePreference": settings().getInt(["serial", "baudrate"]),
"autoconnect": settings().getBoolean(["serial", "autoconnect"])
}
return PrinterInterface.get_connection_options()
class PrinterInterface(object):
@@ -65,6 +49,31 @@ class PrinterInterface(object):
valid_heater_regex = re.compile("^(tool\d+|bed)$")
"""Regex for valid heater identifiers."""
@classmethod
def get_connection_options(cls):
"""
Retrieves the available ports, baudrates, preferred port and baudrate for connecting to the printer.
Returned ``dict`` has the following structure::
ports: <list of available serial ports>
baudrates: <list of available baudrates>
portPreference: <configured default serial port>
baudratePreference: <configured default baudrate>
autoconnect: <whether autoconnect upon server startup is enabled or not>
Returns:
(dict): A dictionary holding the connection options in the structure specified above
"""
import octoprint.util.comm as comm
return {
"ports": comm.serialList(),
"baudrates": comm.baudrateList(),
"portPreference": settings().get(["serial", "port"]),
"baudratePreference": settings().getInt(["serial", "baudrate"]),
"autoconnect": settings().getBoolean(["serial", "autoconnect"])
}
def connect(self, port=None, baudrate=None, profile=None):
"""
Connects to the printer, using the specified serial ``port``, ``baudrate`` and printer ``profile``. If a
@@ -200,7 +209,7 @@ class PrinterInterface(object):
Arguments:
factor (int, float): The factor for the feed rate to send to the firmware. Percentage expressed as either an
int between 0 and 100 or a float between 0 and 1.
int between 0 and 100 or a float between 0 and 1.
"""
raise NotImplementedError()
@@ -210,7 +219,7 @@ class PrinterInterface(object):
Arguments:
factor (int, float): The factor for the flow rate to send to the firmware. Percentage expressed as either an
int between 0 and 100 or a float between 0 and 1.
int between 0 and 100 or a float between 0 and 1.
"""
raise NotImplementedError()
+69 -26
View File
@@ -53,7 +53,6 @@ user_permission = Permission(RoleNeed("user"))
# only import the octoprint stuff down here, as it might depend on things defined above to be initialized already
from octoprint import __version__, __branch__, __display_version__, __revision__
from octoprint.printer import get_connection_options
from octoprint.printer.profile import PrinterProfileManager
from octoprint.printer.standard import Printer
from octoprint.settings import settings
@@ -193,7 +192,6 @@ class Server(object):
storage_managers = dict()
storage_managers[octoprint.filemanager.FileDestinations.LOCAL] = octoprint.filemanager.storage.LocalFileStorage(self._settings.getBaseFolder("uploads"))
fileManager = octoprint.filemanager.FileManager(analysisQueue, slicingManager, printerProfileManager, initial_storage_managers=storage_managers)
printer = Printer(fileManager, analysisQueue, printerProfileManager)
appSessionManager = util.flask.AppSessionManager()
pluginLifecycleManager = LifecycleManager(pluginManager)
preemptiveCache = PreemptiveCache(os.path.join(self._settings.getBaseFolder("data"), "preemptive_cache_config.yaml"))
@@ -203,29 +201,48 @@ class Server(object):
try:
clazz = octoprint.util.get_class(userManagerName)
userManager = clazz()
except AttributeError, e:
except AttributeError as e:
self._logger.exception("Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(userManagerName))
userManager = octoprint.users.FilebasedUserManager()
finally:
userManager.enabled = self._settings.getBoolean(["accessControl", "enabled"])
components = dict(
plugin_manager=pluginManager,
printer_profile_manager=printerProfileManager,
event_bus=eventManager,
analysis_queue=analysisQueue,
slicing_manager=slicingManager,
file_manager=fileManager,
app_session_manager=appSessionManager,
plugin_lifecycle_manager=pluginLifecycleManager,
user_manager=userManager,
preemptive_cache=preemptiveCache
)
# create printer instance
printer_factories = pluginManager.get_hooks("octoprint.printer.factory")
for name, factory in printer_factories.items():
try:
printer = factory(components)
if printer is not None:
self._logger.debug("Created printer instance from factory {}".format(name))
break
except:
self._logger.exception("Error while creating printer instance from factory {}".format(name))
else:
printer = Printer(fileManager, analysisQueue, printerProfileManager)
components.update(dict(printer=printer))
def octoprint_plugin_inject_factory(name, implementation):
if not isinstance(implementation, octoprint.plugin.OctoPrintPlugin):
return None
return dict(
plugin_manager=pluginManager,
printer_profile_manager=printerProfileManager,
event_bus=eventManager,
analysis_queue=analysisQueue,
slicing_manager=slicingManager,
file_manager=fileManager,
printer=printer,
app_session_manager=appSessionManager,
plugin_lifecycle_manager=pluginLifecycleManager,
data_folder=os.path.join(self._settings.getBaseFolder("data"), name),
user_manager=userManager,
preemptive_cache=preemptiveCache
)
props = dict()
props.update(components)
props.update(dict(
data_folder=os.path.join(self._settings.getBaseFolder("data"), name)
))
return props
def settings_plugin_inject_factory(name, implementation):
plugin_settings = octoprint.plugin.plugin_settings_for_settings_plugin(name, implementation)
@@ -450,7 +467,7 @@ class Server(object):
if self._settings.getBoolean(["serial", "autoconnect"]):
(port, baudrate) = self._settings.get(["serial", "port"]), self._settings.getInt(["serial", "baudrate"])
printer_profile = printerProfileManager.get_default()
connectionOptions = get_connection_options()
connectionOptions = printer.__class__.get_connection_options()
if port in connectionOptions["ports"]:
printer.connect(port=port, baudrate=baudrate, profile=printer_profile["id"] if "id" in printer_profile else "_default")
@@ -733,6 +750,24 @@ class Server(object):
entries = reversed(sorted(cache_data[route], key=lambda x: x.get("_count", 0)))
for kwargs in entries:
plugin = kwargs.get("plugin", None)
if plugin:
try:
plugin_info = pluginManager.get_plugin_info(plugin, require_enabled=True)
if plugin_info is None:
self._logger.debug("Plugin {} is not installed or enabled, preemptive caching makes no sense".format(plugin))
continue
implementation = plugin_info.implementation
if implementation is None or not isinstance(implementation, octoprint.plugin.UiPlugin):
self._logger.debug("Plugin {} is not a UiPlugin, preemptive caching makes no sense".format(plugin))
continue
if not implementation.get_ui_preemptive_caching_enabled():
self._logger.debug("Plugin {} has disabled preemptive caching".format(plugin))
continue
except:
self._logger.exception("Error while trying to check if plugin {} has preemptive caching enabled, skipping entry")
continue
additional_request_data = kwargs.get("_additional_request_data", dict())
kwargs = dict((k, v) for k, v in kwargs.items() if not k.startswith("_") and not k == "plugin")
kwargs.update(additional_request_data)
@@ -742,8 +777,9 @@ class Server(object):
else:
self._logger.info("Preemptively caching {} for {!r}".format(route, kwargs))
builder = EnvironBuilder(**kwargs)
with preemptive_cache.disable_access_logging():
app(builder.get_environ(), lambda *a, **kw: None)
with preemptive_cache.cache_environment(dict(plugin=plugin if plugin is not None else "_default")):
with preemptive_cache.disable_access_logging():
app(builder.get_environ(), lambda *a, **kw: None)
except:
self._logger.exception("Error while trying to preemptively cache {} for {!r}".format(route, kwargs))
@@ -1146,17 +1182,24 @@ class LifecycleManager(object):
self._plugin_lifecycle_callbacks = defaultdict(list)
self._logger = logging.getLogger(__name__)
def wrap_plugin_event(lifecycle_event, new_handler):
orig_handler = getattr(self._plugin_manager, "on_plugin_" + lifecycle_event)
def handler(*args, **kwargs):
if callable(orig_handler):
orig_handler(*args, **kwargs)
if callable(new_handler):
new_handler(*args, **kwargs)
return handler
def on_plugin_event_factory(lifecycle_event):
def on_plugin_event(name, plugin):
self.on_plugin_event(lifecycle_event, name, plugin)
return on_plugin_event
self._plugin_manager.on_plugin_loaded = on_plugin_event_factory("loaded")
self._plugin_manager.on_plugin_unloaded = on_plugin_event_factory("unloaded")
self._plugin_manager.on_plugin_activated = on_plugin_event_factory("activated")
self._plugin_manager.on_plugin_deactivated = on_plugin_event_factory("deactivated")
self._plugin_manager.on_plugin_enabled = on_plugin_event_factory("enabled")
self._plugin_manager.on_plugin_disabled = on_plugin_event_factory("disabled")
for event in ("loaded", "unloaded", "enabled", "disabled"):
wrap_plugin_event(event, on_plugin_event_factory(event))
def on_plugin_event(self, event, name, plugin):
for lifecycle_callback in self._plugin_lifecycle_callbacks[event]:
+3 -5
View File
@@ -8,11 +8,9 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
from flask import request, jsonify, make_response
from octoprint.settings import settings
from octoprint.printer import get_connection_options
from octoprint.server import printer, printerProfileManager, NO_CONTENT
from octoprint.server.api import api
from octoprint.server.util.flask import restricted_access, get_json_command_from_request
import octoprint.util as util
@api.route("/connection", methods=["GET"])
@@ -42,7 +40,7 @@ def connectionCommand():
return response
if command == "connect":
connection_options = get_connection_options()
connection_options = printer.__class__.get_connection_options()
port = None
baudrate = None
@@ -75,7 +73,7 @@ def connectionCommand():
return NO_CONTENT
def _get_options():
connection_options = get_connection_options()
connection_options = printer.__class__.get_connection_options()
profile_options = printerProfileManager.get_all()
default_profile = printerProfileManager.get_default()
@@ -88,4 +86,4 @@ def _get_options():
printerProfilePreference=default_profile["id"] if "id" in default_profile else None
)
return options
return options
+5 -4
View File
@@ -12,9 +12,8 @@ from werkzeug.exceptions import BadRequest
from octoprint.events import eventManager, Events
from octoprint.settings import settings
from octoprint.printer import get_connection_options
from octoprint.server import admin_permission
from octoprint.server import admin_permission, printer
from octoprint.server.api import api
from octoprint.server.util.flask import restricted_access
@@ -30,7 +29,7 @@ def getSettings():
s = settings()
connectionOptions = get_connection_options()
connectionOptions = printer.__class__.get_connection_options()
data = {
"api": {
@@ -74,7 +73,8 @@ def getSettings():
"externalHeatupDetection": s.getBoolean(["feature", "externalHeatupDetection"]),
"keyboardControl": s.getBoolean(["feature", "keyboardControl"]),
"pollWatched": s.getBoolean(["feature", "pollWatched"]),
"ignoreIdenticalResends": s.getBoolean(["feature", "ignoreIdenticalResends"])
"ignoreIdenticalResends": s.getBoolean(["feature", "ignoreIdenticalResends"]),
"modelSizeDetection": s.getBoolean(["feature", "modelSizeDetection"])
},
"serial": {
"port": connectionOptions["portPreference"],
@@ -236,6 +236,7 @@ def _saveSettings(data):
if "keyboardControl" in data["feature"].keys(): s.setBoolean(["feature", "keyboardControl"], data["feature"]["keyboardControl"])
if "pollWatched" in data["feature"]: s.setBoolean(["feature", "pollWatched"], data["feature"]["pollWatched"])
if "ignoreIdenticalResends" in data["feature"]: s.setBoolean(["feature", "ignoreIdenticalResends"], data["feature"]["ignoreIdenticalResends"])
if "modelSizeDetection" in data["feature"]: s.setBoolean(["feature", "modelSizeDetection"], data["feature"]["modelSizeDetection"])
if "serial" in data.keys():
if "autoconnect" in data["serial"].keys(): s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"])
+13 -3
View File
@@ -383,11 +383,14 @@ class PreemptiveCache(object):
def __init__(self, cachefile):
self.cachefile = cachefile
self.environment = None
self._lock = threading.RLock()
self._logger = logging.getLogger(__name__ + "." + self.__class__.__name__)
self._log_access = True
self._lock = threading.RLock()
self._environment_lock = threading.RLock()
def record(self, data, unless=None):
if callable(unless) and unless():
return
@@ -407,6 +410,13 @@ class PreemptiveCache(object):
yield
self._log_access = True
@contextlib.contextmanager
def cache_environment(self, environment):
with self._environment_lock:
self.environment = environment
yield
self.environment = None
def clean_all_data(self, cleanup_function):
assert callable(cleanup_function)
@@ -585,13 +595,13 @@ def conditional(condition, met):
def check_etag(etag):
return flask.request.method in ("GET", "HEAD") and \
flask.request.if_none_match and \
flask.request.if_none_match is not None and \
etag in flask.request.if_none_match
def check_lastmodified(lastmodified):
return flask.request.method in ("GET", "HEAD") and \
flask.request.if_modified_since and \
flask.request.if_modified_since is not None and \
lastmodified >= flask.request.if_modified_since
+53 -16
View File
@@ -37,6 +37,8 @@ _valid_div_re = re.compile("[a-zA-Z_-]+")
def index():
global _templates, _plugin_names, _plugin_vars
preemptive_cache_enabled = settings().getBoolean(["devel", "cache", "preemptive"])
# helper to check if wizards are active
def wizard_active(templates):
return templates is not None and bool(templates["wizard"]["order"])
@@ -116,11 +118,13 @@ def index():
files = collect_files()
lastmodified = compute_lastmodified(files)
lastmodified_ok = util.flask.check_lastmodified(lastmodified)
etag_ok = util.flask.check_etag(compute_etag(files, lastmodified))
etag_ok = util.flask.check_etag(compute_etag(files=files,
lastmodified=lastmodified,
additional=cache_key()))
return lastmodified_ok and etag_ok
def validate_cache(cached):
etag_different = compute_etag() != cached.get_etag()[0]
etag_different = compute_etag(additional=cache_key()) != cached.get_etag()[0]
return force_refresh or etag_different
def collect_files():
@@ -162,7 +166,7 @@ def index():
files = collect_files()
return _compute_date(files)
def compute_etag(files=None, lastmodified=None):
def compute_etag(files=None, lastmodified=None, additional=None):
if callable(custom_etag):
try:
etag = custom_etag()
@@ -178,6 +182,8 @@ def index():
if lastmodified and not isinstance(lastmodified, basestring):
from werkzeug.http import http_date
lastmodified = http_date(lastmodified)
if additional is None:
additional = []
import hashlib
hash = hashlib.sha1()
@@ -186,11 +192,13 @@ def index():
hash.update(",".join(sorted(files)))
if lastmodified:
hash.update(lastmodified)
for add in additional:
hash.update(add)
return hash.hexdigest()
decorated_view = view
decorated_view = util.flask.lastmodified(lambda _: compute_lastmodified())(decorated_view)
decorated_view = util.flask.etagged(lambda _: compute_etag())(decorated_view)
decorated_view = util.flask.etagged(lambda _: compute_etag(additional=cache_key()))(decorated_view)
decorated_view = util.flask.cached(timeout=-1,
refreshif=validate_cache,
key=cache_key,
@@ -198,8 +206,7 @@ def index():
decorated_view = util.flask.conditional(check_etag_and_lastmodified, NOT_MODIFIED)(decorated_view)
return decorated_view
ui_plugins = pluginManager.get_implementations(octoprint.plugin.UiPlugin, sorting_context="UiPlugin.on_ui_render")
for plugin in ui_plugins:
def plugin_view(plugin):
if plugin.will_handle_ui(request):
# plugin claims responsibility, let it render the UI
cached = get_cached_view(plugin._identifier,
@@ -210,17 +217,18 @@ def index():
custom_etag=plugin.get_ui_custom_etag,
custom_lastmodified=plugin.get_ui_custom_lastmodified)
preemptively_cached = get_preemptively_cached_view(plugin._identifier,
cached,
plugin.get_ui_data_for_preemptive_caching,
plugin.get_ui_additional_request_data_for_preemptive_caching,
plugin.get_ui_additional_unless)
if preemptive_cache_enabled and plugin.get_ui_preemptive_caching_enabled():
view = get_preemptively_cached_view(plugin._identifier,
cached,
plugin.get_ui_data_for_preemptive_caching,
plugin.get_ui_additional_request_data_for_preemptive_caching,
plugin.get_ui_additional_unless)
else:
view = cached
response = preemptively_cached(now, request, render_kwargs)
if response is not None:
break
return view(now, request, render_kwargs)
else:
def default_view():
wizard = wizard_active(_templates)
enable_accesscontrol = userManager.enabled
accesscontrol_active = enable_accesscontrol and userManager.hasBeenCustomized()
@@ -250,7 +258,36 @@ def index():
cached,
dict(),
dict())
response = preemptively_cached()
return preemptively_cached()
forced_view = None
preemptive_cache_environment = preemptiveCache.environment
if preemptive_cache_environment is not None and isinstance(preemptive_cache_environment, dict):
forced_view = preemptive_cache_environment.get("plugin", "_default")
if forced_view:
# we have view forced by the preemptive cache
_logger.debug("Forcing rendering of view {}".format(forced_view))
response = None
if forced_view != "_default":
plugin = pluginManager.get_plugin_info(forced_view, require_enabled=True)
if plugin is not None and isinstance(plugin.implementation, octoprint.plugin.UiPlugin):
response = plugin_view(plugin.implementation)
if response is None:
return default_view()
else:
# select view from plugins and fall back on default view if no plugin will handle it
ui_plugins = pluginManager.get_implementations(octoprint.plugin.UiPlugin, sorting_context="UiPlugin.on_ui_render")
for plugin in ui_plugins:
identifier = plugin._identifier
if plugin.will_handle_ui(request):
response = plugin_view(plugin)
if response is not None:
break
else:
response = default_view()
return response
+344 -149
View File
@@ -29,8 +29,14 @@ import yaml
import logging
import re
import uuid
import copy
from octoprint.util import atomic_write, is_hidden_path
try:
from collections import ChainMap
except ImportError:
from chainmap import ChainMap
from octoprint.util import atomic_write, is_hidden_path, dict_merge
_APPNAME = "OctoPrint"
@@ -175,7 +181,8 @@ default_settings = {
"pollWatched": False,
"ignoreIdenticalResends": False,
"identicalResendsCountdown": 7,
"supportFAsCommand": False
"supportFAsCommand": False,
"modelSizeDetection": True
},
"folder": {
"uploads": None,
@@ -336,6 +343,102 @@ class NoSuchSettingsPath(BaseException):
pass
class HierarchicalChainMap(ChainMap):
def deep_dict(self, root=None):
if root is None:
root = self
result = dict()
for key, value in root.items():
if isinstance(value, dict):
result[key] = self.deep_dict(root=self.__class__._get_next(key, root))
else:
result[key] = value
return result
def has_path(self, path, only_local=False, only_defaults=False):
if only_defaults:
current = self.parents
elif only_local:
current = self.__class__(self.maps[0])
else:
current = self
try:
for key in path[:-1]:
value = current[key]
if isinstance(value, dict):
current = self.__class__._get_next(key, current, only_local=only_local)
else:
return False
return path[-1] in current
except KeyError:
return False
def get_by_path(self, path, only_local=False, only_defaults=False):
if only_defaults:
current = self.parents
elif only_local:
current = self.__class__(self.maps[0])
else:
current = self
for key in path[:-1]:
value = current[key]
if isinstance(value, dict):
current = self.__class__._get_next(key, current, only_local=only_local)
else:
raise KeyError(key)
return current[path[-1]]
def set_by_path(self, path, value):
current = self
for key in path[:-1]:
if key not in current.maps[0]:
current.maps[0][key] = dict()
if not isinstance(current[key], dict):
raise KeyError(key)
current = self.__class__._hierarchy_for_key(key, current)
current[path[-1]] = value
def del_by_path(self, path):
if not path:
raise ValueError("Invalid path")
current = self
for key in path[:-1]:
if not isinstance(current[key], dict):
raise KeyError(key)
current = self.__class__._hierarchy_for_key(key, current)
del current[path[-1]]
@classmethod
def _hierarchy_for_key(cls, key, chain):
wrapped_mappings = list()
for mapping in chain.maps:
if key in mapping and mapping[key] is not None:
wrapped_mappings.append(mapping[key])
else:
wrapped_mappings.append(dict())
return HierarchicalChainMap(*wrapped_mappings)
@classmethod
def _get_next(cls, key, node, only_local=False):
if isinstance(node, dict):
return node[key]
elif only_local and not key in node.maps[0]:
raise KeyError(key)
else:
return cls._hierarchy_for_key(key, node)
class Settings(object):
"""
The :class:`Settings` class allows managing all of OctoPrint's settings. It takes care of initializing the settings
@@ -393,6 +496,8 @@ class Settings(object):
self._basedir = None
self._map = HierarchicalChainMap(dict(), default_settings)
self._config = None
self._dirty = False
self._mtime = None
@@ -581,8 +686,7 @@ class Settings(object):
@property
def effective(self):
import octoprint.util
return octoprint.util.dict_merge(default_settings, self._config)
return self._map.deep_dict()
@property
def effective_yaml(self):
@@ -593,16 +697,49 @@ class Settings(object):
def effective_hash(self):
import hashlib
hash = hashlib.md5()
hash.update(repr(self.effective))
hash.update(self.effective_yaml)
return hash.hexdigest()
@property
def config_yaml(self):
import yaml
return yaml.safe_dump(self._config)
@property
def config_hash(self):
import hashlib
hash = hashlib.md5()
hash.update(repr(self._config))
hash.update(self.config_yaml)
return hash.hexdigest()
@property
def _config(self):
return self._map.maps[0]
@_config.setter
def _config(self, value):
self._map.maps[0] = value
@property
def _overlay_maps(self):
if len(self._map.maps) > 2:
return self._map.maps[1:-1]
else:
return []
@property
def _default_map(self):
return self._map.maps[-1]
@property
def last_modified(self):
"""
Returns:
int: The last modification time of the configuration file.
"""
stat = os.stat(self._configfile)
return stat.st_mtime
#~~ load and save
def load(self, migrate=False):
@@ -612,12 +749,44 @@ class Settings(object):
self._mtime = self.last_modified
# changed from else to handle cases where the file exists, but is empty / 0 bytes
if not self._config:
self._config = {}
self._config = dict()
if migrate:
self._migrate_config()
def _migrate_config(self):
def load_overlay(self, overlay, migrate=True):
config = None
if callable(overlay):
try:
overlay = overlay(self)
except:
self._logger.exception("Error loading overlay from callable")
return
if isinstance(overlay, basestring):
if os.path.exists(overlay) and os.path.isfile(overlay):
with open(overlay, "r") as f:
config = yaml.safe_load(f)
elif isinstance(overlay, dict):
config = overlay
else:
raise ValueError("Overlay must be either a path to a yaml file or a dictionary")
if not isinstance(config, dict):
raise ValueError("Configuration data must be a dict but is a {}".format(config.__class__))
if migrate:
self._migrate_config(config)
return config
def add_overlay(self, overlay):
self._map.maps.insert(1, overlay)
def _migrate_config(self, config=None):
if config is None:
config = self._config
dirty = False
migrators = (
@@ -628,20 +797,20 @@ class Settings(object):
)
for migrate in migrators:
dirty = migrate() or dirty
dirty = migrate(config) or dirty
if dirty:
self.save(force=True)
def _migrate_gcode_scripts(self):
def _migrate_gcode_scripts(self, config):
"""
Migrates an old development version of gcode scripts to the new template based format.
"""
dirty = False
if "scripts" in self._config:
if "gcode" in self._config["scripts"]:
if "templates" in self._config["scripts"]["gcode"]:
del self._config["scripts"]["gcode"]["templates"]
if "scripts" in config:
if "gcode" in config["scripts"]:
if "templates" in config["scripts"]["gcode"]:
del config["scripts"]["gcode"]["templates"]
replacements = dict(
disable_steppers="M84",
@@ -650,21 +819,21 @@ class Settings(object):
disable_fan="M106 S0"
)
for name, script in self._config["scripts"]["gcode"].items():
for name, script in config["scripts"]["gcode"].items():
self.saveScript("gcode", name, script.format(**replacements))
del self._config["scripts"]
del config["scripts"]
dirty = True
return dirty
def _migrate_printer_parameters(self):
def _migrate_printer_parameters(self, config):
"""
Migrates the old "printer > parameters" data structure to the new printer profile mechanism.
"""
default_profile = self._config["printerProfiles"]["defaultProfile"] if "printerProfiles" in self._config and "defaultProfile" in self._config["printerProfiles"] else dict()
default_profile = config["printerProfiles"]["defaultProfile"] if "printerProfiles" in config and "defaultProfile" in config["printerProfiles"] else dict()
dirty = False
if "printerParameters" in self._config:
printer_parameters = self._config["printerParameters"]
if "printerParameters" in config:
printer_parameters = config["printerParameters"]
if "movementSpeed" in printer_parameters or "invertAxes" in printer_parameters:
default_profile["axes"] = dict(x=dict(), y=dict(), z=dict(), e=dict())
@@ -672,12 +841,12 @@ class Settings(object):
for axis in ("x", "y", "z", "e"):
if axis in printer_parameters["movementSpeed"]:
default_profile["axes"][axis]["speed"] = printer_parameters["movementSpeed"][axis]
del self._config["printerParameters"]["movementSpeed"]
del config["printerParameters"]["movementSpeed"]
if "invertedAxes" in printer_parameters:
for axis in ("x", "y", "z", "e"):
if axis in printer_parameters["invertedAxes"]:
default_profile["axes"][axis]["inverted"] = True
del self._config["printerParameters"]["invertedAxes"]
del config["printerParameters"]["invertedAxes"]
if "numExtruders" in printer_parameters or "extruderOffsets" in printer_parameters:
if not "extruder" in default_profile:
@@ -685,14 +854,14 @@ class Settings(object):
if "numExtruders" in printer_parameters:
default_profile["extruder"]["count"] = printer_parameters["numExtruders"]
del self._config["printerParameters"]["numExtruders"]
del config["printerParameters"]["numExtruders"]
if "extruderOffsets" in printer_parameters:
extruder_offsets = []
for offset in printer_parameters["extruderOffsets"]:
if "x" in offset and "y" in offset:
extruder_offsets.append((offset["x"], offset["y"]))
default_profile["extruder"]["offsets"] = extruder_offsets
del self._config["printerParameters"]["extruderOffsets"]
del config["printerParameters"]["extruderOffsets"]
if "bedDimensions" in printer_parameters:
bed_dimensions = printer_parameters["bedDimensions"]
@@ -709,49 +878,49 @@ class Settings(object):
default_profile["volume"]["width"] = bed_dimensions["x"]
if "y" in bed_dimensions:
default_profile["volume"]["depth"] = bed_dimensions["y"]
del self._config["printerParameters"]["bedDimensions"]
del config["printerParameters"]["bedDimensions"]
dirty = True
if dirty:
if not "printerProfiles" in self._config:
self._config["printerProfiles"] = dict()
self._config["printerProfiles"]["defaultProfile"] = default_profile
if not "printerProfiles" in config:
config["printerProfiles"] = dict()
config["printerProfiles"]["defaultProfile"] = default_profile
return dirty
def _migrate_reverse_proxy_config(self):
def _migrate_reverse_proxy_config(self, config):
"""
Migrates the old "server > baseUrl" and "server > scheme" configuration entries to
"server > reverseProxy > prefixFallback" and "server > reverseProxy > schemeFallback".
"""
if "server" in self._config.keys() and ("baseUrl" in self._config["server"] or "scheme" in self._config["server"]):
if "server" in config.keys() and ("baseUrl" in config["server"] or "scheme" in config["server"]):
prefix = ""
if "baseUrl" in self._config["server"]:
prefix = self._config["server"]["baseUrl"]
del self._config["server"]["baseUrl"]
if "baseUrl" in config["server"]:
prefix = config["server"]["baseUrl"]
del config["server"]["baseUrl"]
scheme = ""
if "scheme" in self._config["server"]:
scheme = self._config["server"]["scheme"]
del self._config["server"]["scheme"]
if "scheme" in config["server"]:
scheme = config["server"]["scheme"]
del config["server"]["scheme"]
if not "reverseProxy" in self._config["server"] or not isinstance(self._config["server"]["reverseProxy"], dict):
self._config["server"]["reverseProxy"] = dict()
if not "reverseProxy" in config["server"] or not isinstance(config["server"]["reverseProxy"], dict):
config["server"]["reverseProxy"] = dict()
if prefix:
self._config["server"]["reverseProxy"]["prefixFallback"] = prefix
config["server"]["reverseProxy"]["prefixFallback"] = prefix
if scheme:
self._config["server"]["reverseProxy"]["schemeFallback"] = scheme
config["server"]["reverseProxy"]["schemeFallback"] = scheme
self._logger.info("Migrated reverse proxy configuration to new structure")
return True
else:
return False
def _migrate_event_config(self):
def _migrate_event_config(self, config):
"""
Migrates the old event configuration format of type "events > gcodeCommandTrigger" and
"event > systemCommandTrigger" to the new events format.
"""
if "events" in self._config.keys() and ("gcodeCommandTrigger" in self._config["events"] or "systemCommandTrigger" in self._config["events"]):
if "events" in config.keys() and ("gcodeCommandTrigger" in config["events"] or "systemCommandTrigger" in config["events"]):
self._logger.info("Migrating config (event subscriptions)...")
# migrate event hooks to new format
@@ -793,12 +962,12 @@ class Settings(object):
return event, command
disableSystemCommands = False
if "systemCommandTrigger" in self._config["events"] and "enabled" in self._config["events"]["systemCommandTrigger"]:
disableSystemCommands = not self._config["events"]["systemCommandTrigger"]["enabled"]
if "systemCommandTrigger" in config["events"] and "enabled" in config["events"]["systemCommandTrigger"]:
disableSystemCommands = not config["events"]["systemCommandTrigger"]["enabled"]
disableGcodeCommands = False
if "gcodeCommandTrigger" in self._config["events"] and "enabled" in self._config["events"]["gcodeCommandTrigger"]:
disableGcodeCommands = not self._config["events"]["gcodeCommandTrigger"]["enabled"]
if "gcodeCommandTrigger" in config["events"] and "enabled" in config["events"]["gcodeCommandTrigger"]:
disableGcodeCommands = not config["events"]["gcodeCommandTrigger"]["enabled"]
disableAllCommands = disableSystemCommands and disableGcodeCommands
newEvents = {
@@ -806,8 +975,8 @@ class Settings(object):
"subscriptions": []
}
if "systemCommandTrigger" in self._config["events"] and "subscriptions" in self._config["events"]["systemCommandTrigger"]:
for trigger in self._config["events"]["systemCommandTrigger"]["subscriptions"]:
if "systemCommandTrigger" in config["events"] and "subscriptions" in config["events"]["systemCommandTrigger"]:
for trigger in config["events"]["systemCommandTrigger"]["subscriptions"]:
if not ("event" in trigger and "command" in trigger):
continue
@@ -818,8 +987,8 @@ class Settings(object):
newTrigger["event"], newTrigger["command"] = migrateEventHook(trigger["event"], trigger["command"])
newEvents["subscriptions"].append(newTrigger)
if "gcodeCommandTrigger" in self._config["events"] and "subscriptions" in self._config["events"]["gcodeCommandTrigger"]:
for trigger in self._config["events"]["gcodeCommandTrigger"]["subscriptions"]:
if "gcodeCommandTrigger" in config["events"] and "subscriptions" in config["events"]["gcodeCommandTrigger"]:
for trigger in config["events"]["gcodeCommandTrigger"]["subscriptions"]:
if not ("event" in trigger and "command" in trigger):
continue
@@ -831,7 +1000,7 @@ class Settings(object):
newTrigger["command"] = newTrigger["command"].split(",")
newEvents["subscriptions"].append(newTrigger)
self._config["events"] = newEvents
config["events"] = newEvents
self._logger.info("Migrated %d event subscriptions to new format and structure" % len(newEvents["subscriptions"]))
return True
else:
@@ -853,74 +1022,85 @@ class Settings(object):
self.load()
return True
@property
def last_modified(self):
"""
Returns:
int: The last modification time of the configuration file.
"""
stat = os.stat(self._configfile)
return stat.st_mtime
##~~ Internal getter
def _get_value(self, path, asdict=False, config=None, defaults=None, preprocessors=None, merged=False, incl_defaults=True):
import octoprint.util as util
def _get_by_path(self, path, config):
current = config
for key in path:
if key not in current:
raise NoSuchSettingsPath()
current = current[key]
return current
if len(path) == 0:
def _get_value(self, path, asdict=False, config=None, defaults=None, preprocessors=None, merged=False, incl_defaults=True, do_copy=True):
if not path:
raise NoSuchSettingsPath()
if config is None:
config = self._config
if defaults is None:
defaults = default_settings
if preprocessors is None:
preprocessors = self._get_preprocessors
if config is not None or defaults is not None:
if config is None:
config = self._config
while len(path) > 1:
key = path.pop(0)
if key in config and key in defaults:
config = config[key]
defaults = defaults[key]
elif incl_defaults and key in defaults:
config = {}
defaults = defaults[key]
else:
raise NoSuchSettingsPath()
if defaults is None:
defaults = dict(self._map.parents)
if preprocessors and isinstance(preprocessors, dict) and key in preprocessors:
preprocessors = preprocessors[key]
k = path.pop(0)
if not isinstance(k, (list, tuple)):
keys = [k]
# mappings: provided config + any intermediary parents + provided defaults + regular defaults
mappings = [config] + self._overlay_maps + [defaults, self._default_map]
chain = HierarchicalChainMap(*mappings)
else:
keys = k
chain = self._map
preprocessor = None
if preprocessors is not None:
try:
preprocessor = self._get_by_path(path, preprocessors)
except NoSuchSettingsPath:
pass
parent_path = path[:-1]
last = path[-1]
if not isinstance(last, (list, tuple)):
keys = [last]
else:
keys = last
if asdict:
results = {}
results = dict()
else:
results = []
results = list()
for key in keys:
if key in config:
value = config[key]
if merged and key in defaults:
value = util.dict_merge(defaults[key], value)
elif incl_defaults and key in defaults:
value = defaults[key]
else:
try:
value = chain.get_by_path(parent_path + [key], only_local=not incl_defaults)
except KeyError:
raise NoSuchSettingsPath()
if preprocessors and isinstance(preprocessors, dict) and key in preprocessors and callable(preprocessors[key]):
value = preprocessors[key](value)
if isinstance(value, dict) and merged:
try:
default_value = chain.get_by_path(parent_path + [key], only_defaults=True)
if default_value is not None:
value = dict_merge(default_value, value)
except KeyError:
raise NoSuchSettingsPath()
if preprocessors is not None:
try:
preprocessor = self._get_by_path(path, preprocessors)
except:
pass
if callable(preprocessor):
value = preprocessor(value)
if do_copy:
value = copy.deepcopy(value)
if asdict:
results[key] = value
else:
results.append(value)
if not isinstance(k, (list, tuple)):
if not isinstance(last, (list, tuple)):
if asdict:
return results.values().pop()
else:
@@ -951,8 +1131,7 @@ class Settings(object):
except NoSuchSettingsPath:
if error_on_path:
raise
else:
return None
return None
def getInt(self, path, **kwargs):
value = self.get(path, **kwargs)
@@ -1032,65 +1211,81 @@ class Settings(object):
#~~ remove
def remove(self, path, config=None):
if config is None:
config = self._config
def remove(self, path, config=None, error_on_path=False):
if not path:
if error_on_path:
raise NoSuchSettingsPath()
return
while len(path) > 1:
key = path.pop(0)
if not isinstance(config, dict) or key not in config:
return
config = config[key]
if config is not None:
mappings = [config] + self._overlay_maps + [self._default_map]
chain = HierarchicalChainMap(*mappings)
else:
chain = self._map
key = path.pop(0)
if isinstance(config, dict) and key in config:
del config[key]
self._dirty = True
try:
chain.del_by_path(path)
self._dirty = True
except KeyError:
if error_on_path:
raise NoSuchSettingsPath()
pass
#~~ setter
def set(self, path, value, force=False, defaults=None, config=None, preprocessors=None):
if len(path) == 0:
def set(self, path, value, force=False, defaults=None, config=None, preprocessors=None, error_on_path=False):
if not path:
if error_on_path:
raise NoSuchSettingsPath()
return
if self._mtime is not None and self.last_modified != self._mtime:
self.load()
if config is None:
config = self._config
if defaults is None:
defaults = default_settings
if preprocessors is None:
preprocessors = self._set_preprocessors
if config is not None or defaults is not None:
if config is None:
config = self._config
while len(path) > 1:
key = path.pop(0)
if key in config.keys() and key in defaults.keys():
config = config[key]
defaults = defaults[key]
elif key in defaults.keys():
config[key] = {}
config = config[key]
defaults = defaults[key]
if defaults is None:
defaults = dict(self._map.parents)
chain = HierarchicalChainMap(config, defaults)
else:
chain = self._map
preprocessor = None
if preprocessors is not None:
try:
preprocessor = self._get_by_path(path, preprocessors)
except NoSuchSettingsPath:
pass
if callable(preprocessor):
value = preprocessor(value)
try:
current = chain.get_by_path(path)
default_value = chain.get_by_path(path, only_defaults=True)
in_local = chain.has_path(path, only_local=True)
in_defaults = chain.has_path(path, only_defaults=True)
except KeyError:
if error_on_path:
raise NoSuchSettingsPath()
return
if not force and in_defaults and in_local and default_value == value:
try:
chain.del_by_path(path)
self._dirty = True
except KeyError:
if error_on_path:
raise NoSuchSettingsPath()
pass
elif force or (not in_local and in_defaults and default_value != value) or (in_local and current != value):
if value is None and in_local:
chain.del_by_path(path)
else:
return
if preprocessors and isinstance(preprocessors, dict) and key in preprocessors:
preprocessors = preprocessors[key]
key = path.pop(0)
if preprocessors and isinstance(preprocessors, dict) and key in preprocessors and callable(preprocessors[key]):
value = preprocessors[key](value)
if not force and key in defaults and key in config and defaults[key] == value:
del config[key]
self._dirty = True
elif force or (not key in config and key in defaults and defaults[key] != value) or (key in config and config[key] != value):
if value is None and key in config:
del config[key]
else:
config[key] = value
chain.set_by_path(path, value)
self._dirty = True
def setInt(self, path, value, **kwargs):
@@ -1122,7 +1317,7 @@ class Settings(object):
def setBoolean(self, path, value, **kwargs):
if value is None or isinstance(value, bool):
self.set(path, value, **kwargs)
elif value.lower() in valid_boolean_trues:
elif isinstance(value, basestring) and value.lower() in valid_boolean_trues:
self.set(path, True, **kwargs)
else:
self.set(path, False, **kwargs)
+13 -6
View File
@@ -104,8 +104,11 @@ GCODE.ui = (function(){
if(!Modernizr.webworkers)fatal.push("<li>Your browser doesn't seem to support HTML5 Web Workers, this application won't work without it.</li>");
if(!Modernizr.svg)fatal.push("<li>Your browser doesn't seem to support HTML5 SVG, this application won't work without it.</li>");
var errorList = document.getElementById("errorList");
if(fatal.length>0){
document.getElementById('errorList').innerHTML = '<ul>' + fatal.join('') + '</ul>';
if (errorList) {
errorList.innerHTML = '<ul>' + fatal.join('') + '</ul>';
}
console.log("Initialization failed: unsupported browser.")
return false;
}
@@ -117,8 +120,10 @@ GCODE.ui = (function(){
if(!Modernizr.draganddrop)warnings.push("<li>Your browser doesn't seem to support HTML5 Drag'n'Drop, Drop area will not work.</li>");
if(warnings.length>0){
document.getElementById('errorList').innerHTML = '<ul>' + wanings.join('') + '</ul>';
console.log("Initialization succeeded with warnings.")
if (errorList) {
errorList.innerHTML = '<ul>' + warnings.join('') + '</ul>';
}
console.log("Initialization succeeded with warnings.", warnings);
}
return true;
};
@@ -138,12 +143,12 @@ GCODE.ui = (function(){
init: function(options){
if (options) setOptions(options);
if (!options.container) {
return;
return false;
}
var capabilitiesResult = checkCapabilities();
if (!capabilitiesResult) {
return;
return false;
}
setProgress("", 0);
@@ -159,6 +164,8 @@ GCODE.ui = (function(){
toolOffsets: options.toolOffsets
});
GCODE.renderer.render(0, 0);
return true;
},
clear: function() {
@@ -196,4 +203,4 @@ GCODE.ui = (function(){
switchCommands(layerNum, first, last);
}
}
}());
}());
+2
View File
@@ -529,6 +529,7 @@ function showConfirmationDialog(msg, onacknowledge, options) {
var proceed = options.proceed || gettext("Proceed");
var proceedClass = options.proceedClass || "danger";
var onproceed = options.onproceed || undefined;
var dialogClass = options.dialogClass || "";
var modalHeader = $('<a href="javascript:void(0)" class="close" data-dismiss="modal" aria-hidden="true">&times;</a><h3>' + title + '</h3>');
var modalBody = $('<p>' + message + '</p><p>' + question + '</p>');
@@ -541,6 +542,7 @@ function showConfirmationDialog(msg, onacknowledge, options) {
var modal = $('<div></div>')
.addClass('modal hide fade')
.addClass(dialogClass)
.append($('<div></div>').addClass('modal-header').append(modalHeader))
.append($('<div></div>').addClass('modal-body').append(modalBody))
.append($('<div></div>').addClass('modal-footer').append(cancelButton).append(proceedButton));
+70 -45
View File
@@ -74,12 +74,12 @@ $(function() {
// register for browser visibility tracking
var prop = getHiddenProp();
if (!prop) return undefined;
if (prop) {
var eventName = prop.replace(/[H|h]idden/, "") + "visibilitychange";
document.addEventListener(eventName, updateBrowserVisibility);
var eventName = prop.replace(/[H|h]idden/, "") + "visibilitychange";
document.addEventListener(eventName, updateBrowserVisibility);
updateBrowserVisibility();
updateBrowserVisibility();
}
// exports
@@ -182,34 +182,33 @@ $(function() {
}
// helper to create a view model instance with injected constructor parameters from the view model map
var _createViewModelInstance = function(viewModel, viewModelMap){
var viewModelClass = viewModel[0];
var viewModelParameters = viewModel[1];
var _createViewModelInstance = function(viewModel, viewModelMap, optionalDependencyPass) {
if (viewModelParameters != undefined) {
if (!_.isArray(viewModelParameters)) {
viewModelParameters = [viewModelParameters];
// mirror the requested dependencies with an array of the viewModels
var viewModelParametersMap = function(parameter) {
// check if parameter is found within optional array and if all conditions are met return null instead of undefined
if (optionalDependencyPass && viewModel.optional.indexOf(parameter) !== -1 && !viewModelMap[parameter]) {
log.debug("Resolving optional parameter", [parameter], "without viewmodel");
return null; // null == "optional but not available"
}
// now we'll try to resolve all of the view model's constructor parameters via our view model map
var constructorParameters = _.map(viewModelParameters, function(parameter){
return viewModelMap[parameter]
});
} else {
constructorParameters = [];
}
return viewModelMap[parameter] || undefined; // undefined == "not available"
};
if (_.some(constructorParameters, function(parameter) { return parameter === undefined; })) {
var _extractName = function(entry) { return entry[0]; };
var _onlyUnresolved = function(entry) { return entry[1] === undefined; };
var missingParameters = _.map(_.filter(_.zip(viewModelParameters, constructorParameters), _onlyUnresolved), _extractName);
log.debug("Postponing", viewModel[0].name, "due to missing parameters:", missingParameters);
// try to resolve all of the view model's constructor parameters via our view model map
var constructorParameters = _.map(viewModel.dependencies, viewModelParametersMap) || [];
if (constructorParameters.indexOf(undefined) !== -1) {
log.debug("Postponing", viewModel.name, "due to missing parameters:", _.keys(_.pick(_.object(viewModel.dependencies, constructorParameters), _.isUndefined)));
return;
}
// transform array into object if a plugin wants it as an object
constructorParameters = (viewModel.returnObject) ? _.object(viewModel.dependencies, constructorParameters) : constructorParameters;
// if we came this far then we could resolve all constructor parameters, so let's construct that view model
log.debug("Constructing", viewModel[0].name, "with parameters:", viewModelParameters);
return new viewModelClass(constructorParameters);
log.debug("Constructing", viewModel.name, "with parameters:", viewModel.dependencies);
return new viewModel.construct(constructorParameters);
};
// map any additional view model bindings we might need to make
@@ -229,8 +228,7 @@ $(function() {
});
// helper for translating the name of a view model class into an identifier for the view model map
var _getViewModelId = function(viewModel){
var name = viewModel[0].name;
var _getViewModelId = function(name){
return name.substr(0, 1).toLowerCase() + name.substr(1); // FooBarViewModel => fooBarViewModel
};
@@ -243,6 +241,7 @@ $(function() {
var allViewModels = [];
var allViewModelData = [];
var pass = 1;
var optionalDependencyPass = false;
log.info("Starting dependency resolution...");
while (unprocessedViewModels.length > 0) {
log.debug("Dependency resolution, pass #" + pass);
@@ -252,15 +251,38 @@ $(function() {
// now try to instantiate every one of our as of yet unprocessed view model descriptors
while (unprocessedViewModels.length > 0){
var viewModel = unprocessedViewModels.shift();
var viewModelId = _getViewModelId(viewModel);
// make sure that we don't have two view models going by the same name
if (_.has(viewModelMap, viewModelId)) {
log.error("Duplicate name while instantiating " + viewModelId);
// wrap anything not object related into an object
if(!_.isPlainObject(viewModel)) {
viewModel = {
construct: (_.isArray(viewModel)) ? viewModel[0] : viewModel,
dependencies: viewModel[1] || [],
elements: viewModel[2] || [],
optional: viewModel[3] || []
};
}
// make sure we have atleast a function
if (!_.isFunction(viewModel.construct)) {
log.error("No function to instantiate with", viewModel);
continue;
}
var viewModelInstance = _createViewModelInstance(viewModel, viewModelMap);
// if name is not set, get name from constructor, if it's an anonymous function generate one
viewModel.name = viewModel.name || _getViewModelId(viewModel.construct.name) || _.uniqueId("unnamedViewModel");
// make sure all value's are in an array
viewModel.dependencies = (_.isArray(viewModel.dependencies)) ? viewModel.dependencies : [viewModel.dependencies];
viewModel.elements = (_.isArray(viewModel.elements)) ? viewModel.elements : [viewModel.elements];
viewModel.optional = (_.isArray(viewModel.optional)) ? viewModel.optional : [viewModel.optional];
// make sure that we don't have two view models going by the same name
if (_.has(viewModelMap, viewModel.name)) {
log.error("Duplicate name while instantiating " + viewModel.name);
continue;
}
var viewModelInstance = _createViewModelInstance(viewModel, viewModelMap, optionalDependencyPass);
// our view model couldn't yet be instantiated, so postpone it for a bit
if (viewModelInstance === undefined) {
@@ -269,18 +291,15 @@ $(function() {
}
// we could resolve the depdendencies and the view model is not defined yet => add it, it's now fully processed
var viewModelBindTargets = viewModel[2];
if (!_.isArray(viewModelBindTargets)) {
viewModelBindTargets = [viewModelBindTargets];
}
var viewModelBindTargets = viewModel.elements;
if (additionalBindings.hasOwnProperty(viewModelId)) {
viewModelBindTargets = viewModelBindTargets.concat(additionalBindings[viewModelId]);
if (additionalBindings.hasOwnProperty(viewModel.name)) {
viewModelBindTargets = viewModelBindTargets.concat(additionalBindings[viewModel.name]);
}
allViewModelData.push([viewModelInstance, viewModelBindTargets]);
allViewModels.push(viewModelInstance);
viewModelMap[viewModelId] = viewModelInstance;
viewModelMap[viewModel.name] = viewModelInstance;
}
// anything that's now in the postponed list has to be readded to the unprocessedViewModels
@@ -289,12 +308,18 @@ $(function() {
// if we still have the same amount of items in our list of unprocessed view models it means that we
// couldn't instantiate any more view models over a whole iteration, which in turn mean we can't resolve the
// dependencies of remaining ones, so log that as an error and then quit the loop
if (unprocessedViewModels.length == startLength) {
log.error("Could not instantiate the following view models due to unresolvable dependencies:");
_.each(unprocessedViewModels, function(entry) {
log.error(entry[0].name + " (missing: " + _.filter(entry[1], function(id) { return !_.has(viewModelMap, id); }).join(", ") + " )");
});
break;
if (unprocessedViewModels.length === startLength) {
// I'm gonna let you finish but we will do another pass with the optional dependencies flag enabled
if (!optionalDependencyPass) {
log.debug("Resolving next pass with optional dependencies flag enabled");
optionalDependencyPass = true;
} else {
log.error("Could not instantiate the following view models due to unresolvable dependencies:");
_.each(unprocessedViewModels, function(entry) {
log.error(entry.name + " (missing: " + _.filter(entry.dependencies, function(id) { return !_.has(viewModelMap, id); }).join(", ") + " )");
});
break;
}
}
log.debug("Dependency resolution pass #" + pass + " finished, " + unprocessedViewModels.length + " view models left to process");
@@ -447,6 +447,15 @@ $(function() {
};
self.evaluatePrintDimensions = function(data, notify) {
if (!self.settingsViewModel.feature_modelSizeDetection()) {
return true;
}
var analysis = data["gcodeAnalysis"];
if (!analysis) {
return true;
}
var printingArea = data["gcodeAnalysis"]["printingArea"];
if (!printingArea) {
return true;
@@ -507,6 +516,8 @@ $(function() {
warning += pnotifyAdditionalInfo(info);
warning += "<p><small>You can disable this check via Settings &gt; Features &gt; \"Enable model size detection [...]\"</small></p>";
new PNotify({
title: gettext("Object doesn't fit print volume"),
text: warning,
@@ -236,7 +236,7 @@ $(function() {
self.settings.requestData()
.done(function() {
GCODE.ui.init({
var initResult = GCODE.ui.init({
container: "#gcode_canvas",
onProgress: self._onProgress,
onModelLoaded: self._onModelLoaded,
@@ -245,6 +245,12 @@ $(function() {
toolOffsets: self._retrieveToolOffsets(),
invertAxes: self._retrieveAxesConfiguration()
});
if (!initResult) {
log.info("Could not initialize GCODE viewer component");
return;
}
self.synchronizeOptions();
self.enabled = true;
});
@@ -111,7 +111,8 @@ $(function() {
self.allViewModels = allViewModels;
};
self.onServerConnect = self.onServerReconnect = function() {
self.onStartupComplete = self.onServerConnect = self.onServerReconnect = function() {
if (self.allViewModels == undefined) return;
self.requestData();
};
@@ -131,6 +131,7 @@ $(function() {
self.feature_keyboardControl = ko.observable(undefined);
self.feature_pollWatched = ko.observable(undefined);
self.feature_ignoreIdenticalResends = ko.observable(undefined);
self.feature_modelSizeDetection = ko.observable(undefined);
self.serial_port = ko.observable();
self.serial_baudrate = ko.observable();
@@ -40,13 +40,15 @@ $(function() {
var graphColors = ["red", "orange", "green", "brown", "purple"];
var heaterOptions = {};
var tools = self.tools();
var color;
// tools
var numExtruders = self.settingsViewModel.printerProfiles.currentProfileData().extruder.count();
var currentProfileData = self.settingsViewModel.printerProfiles.currentProfileData();
var numExtruders = (currentProfileData ? currentProfileData.extruder.count() : 0);
if (numExtruders && numExtruders > 1) {
// multiple extruders
for (var extruder = 0; extruder < numExtruders; extruder++) {
var color = graphColors.shift();
color = graphColors.shift();
if (!color) color = "black";
heaterOptions["tool" + extruder] = {name: "T" + extruder, color: color};
@@ -56,9 +58,9 @@ $(function() {
tools[extruder]["name"](gettext("Tool") + " " + extruder);
tools[extruder]["key"]("tool" + extruder);
}
} else {
} else if (numExtruders == 1) {
// only one extruder, no need to add numbers
var color = graphColors[0];
color = graphColors[0];
heaterOptions["tool0"] = {name: "T", color: color};
if (tools.length < 1 || !tools[0]) {
@@ -69,7 +71,7 @@ $(function() {
}
// print bed
if (self.settingsViewModel.printerProfiles.currentProfileData().heatedBed()) {
if (currentProfileData && currentProfileData.heatedBed()) {
self.hasBed(true);
heaterOptions["bed"] = {name: gettext("Bed"), color: "blue"};
} else {
@@ -79,11 +81,12 @@ $(function() {
// write back
self.heaterOptions(heaterOptions);
self.tools(tools);
self.updatePlot();
};
self.settingsViewModel.printerProfiles.currentProfileData.subscribe(function() {
self._printerProfileUpdated();
self.settingsViewModel.printerProfiles.currentProfileData().extruder.count.subscribe(self._printerProfileUpdated);
self.settingsViewModel.printerProfiles.currentProfileData().heatedBed.subscribe(self._printerProfileUpdated());
self.settingsViewModel.printerProfiles.currentProfileData().heatedBed.subscribe(self._printerProfileUpdated);
});
self.temperatures = [];
@@ -386,7 +389,11 @@ $(function() {
return;
}
self.updatePlot();
}
};
self.onStartupComplete = function() {
self._printerProfileUpdated();
};
}
@@ -8,7 +8,14 @@
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_modelSizeDetection" id="settings-modelSizeDetection"> {{ _('Enable model size detection and warn if model exceeds print bed') }} <span class="label label-info">{{ _('Beta') }}</span>
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_sdSupport" id="settings-featureSdSupport"> {{ _('Enable SD support') }}
</label>
</div>
+11 -2
View File
@@ -1075,8 +1075,17 @@ class MachineCom(object):
if handled and self._state not in (self.STATE_CONNECTING, self.STATE_DETECT_BAUDRATE):
continue
##~~ Temperature processing
if ' T:' in line or line.startswith('T:') or ' T0:' in line or line.startswith('T0:') or ' B:' in line or line.startswith('B:'):
# position report processing
if 'X:' in line and 'Y:' in line and 'Z:' in line:
# currently only here to prevent any "B:"s in a position report from
# triggering temperature processing and being interpreted as a bed
# temperature - can happen with COREXY in current Marlin
#
# see also issue #1373
pass
# temperature processing
elif ' T:' in line or line.startswith('T:') or ' T0:' in line or line.startswith('T0:') or ((' B:' in line or line.startswith('B:')) and not 'A:' in line):
if not disable_external_heatup_detection and not line.strip().startswith("ok") and not self._heating:
self._logger.debug("Externally triggered heatup detected")
self._heating = True
+5 -5
View File
@@ -1,5 +1,5 @@
# coding=utf-8
from __future__ import absolute_import
from __future__ import absolute_import, print_function
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
@@ -78,14 +78,14 @@ class CleanCommand(Command):
def run(self):
# build folder
if os.path.exists(self.__class__.build_folder):
print "Deleting build directory"
print("Deleting build directory")
shutil.rmtree(self.__class__.build_folder)
# eggs
for egg in self.__class__.eggs:
globbed_eggs = glob.glob(egg)
for globbed_egg in globbed_eggs:
print "Deleting %s directory" % globbed_egg
print("Deleting %s directory" % globbed_egg)
shutil.rmtree(globbed_egg)
# pyc files
@@ -94,11 +94,11 @@ class CleanCommand(Command):
return
if len(os.listdir(path)) == 0:
shutil.rmtree(path)
print "Deleted %s since it was empty" % path
print("Deleted %s since it was empty" % path)
def delete_file(path):
os.remove(path)
print "Deleted %s" % path
print("Deleted %s" % path)
import fnmatch
recursively_handle_files(
+9 -2
View File
@@ -17,9 +17,16 @@ class PluginTestCase(unittest.TestCase):
self.plugin_folder = os.path.join(os.path.dirname(os.path.realpath(__file__)), "_plugins")
plugin_folders = [self.plugin_folder]
plugin_types = [octoprint.plugin.SettingsPlugin, octoprint.plugin.StartupPlugin, octoprint.plugin.AssetPlugin]
plugin_types = [octoprint.plugin.SettingsPlugin,
octoprint.plugin.StartupPlugin,
octoprint.plugin.AssetPlugin]
plugin_entry_points = None
self.plugin_manager = octoprint.plugin.core.PluginManager(plugin_folders, plugin_types, plugin_entry_points, plugin_disabled_list=[], logging_prefix="logging_prefix.")
self.plugin_manager = octoprint.plugin.core.PluginManager(plugin_folders,
plugin_types,
plugin_entry_points,
plugin_disabled_list=[],
logging_prefix="logging_prefix.")
self.plugin_manager.reload_plugins(startup=True, initialize_implementations=False)
self.plugin_manager.initialize_implementations()
def test_plugin_loading(self):
+10
View File
@@ -0,0 +1,10 @@
# coding=utf-8
"""
Unit tests for ``octoprint.settings``.
"""
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License"
+15
View File
@@ -0,0 +1,15 @@
api:
key: test
serial:
timeout:
detection: 1.0
connection: "5"
additionalPorts:
- /dev/portA
- /dev/portB
server:
port: 8080
devel:
virtualPrinter:
enabled: true
+21
View File
@@ -0,0 +1,21 @@
api:
enabled: true
key:
folder:
uploads:
timelapse:
timelapse_tmp:
scripts:
serial:
timeout:
detection: 0.5
connection: 10.0
server:
host: 0.0.0.0
port: 5000
devel:
virtualPrinter:
enabled: false
sendWait: true
waitInterval: 1.0
repetierStyleResends: false
+581
View File
@@ -0,0 +1,581 @@
# coding=utf-8
"""
Tests for OctoPrint's Settings class
.. todo::
* tests for base folder management
* tests for script management
* tests for settings migration
"""
import unittest
import shutil
import contextlib
import os
import tempfile
import yaml
import hashlib
import ddt
import octoprint.settings
@ddt.ddt
class TestSettings(unittest.TestCase):
def setUp(self):
self.base_path = os.path.join(os.path.dirname(__file__), "_files")
self.config_path = os.path.realpath(os.path.join(self.base_path, "config.yaml"))
self.defaults_path = os.path.realpath(os.path.join(self.base_path, "defaults.yaml"))
with open(self.config_path, "r+b") as f:
self.config = yaml.safe_load(f)
with open(self.defaults_path, "r+b") as f:
self.defaults = yaml.safe_load(f)
from octoprint.util import dict_merge
self.expected_effective = dict_merge(self.defaults, self.config)
def test_basedir_initialization(self):
with self.mocked_basedir() as basedir:
# construct settings
settings = octoprint.settings.Settings()
# verify
self.assertTrue(os.path.isdir(basedir))
self.assertTrue(os.path.isfile(os.path.join(basedir, "config.yaml")))
self.assertIsNotNone(settings.get(["api", "key"]))
def test_basedir_folder_creation(self):
with self.mocked_basedir() as basedir:
# construct settings
settings = octoprint.settings.Settings()
expected_upload_folder = os.path.join(basedir, "uploads")
expected_timelapse_folder = os.path.join(basedir, "timelapse")
expected_timelapse_tmp_folder = os.path.join(basedir, "timelapse", "tmp")
# test
self.assertFalse(os.path.isdir(expected_upload_folder))
upload_folder = settings.getBaseFolder("uploads")
timelapse_folder = settings.getBaseFolder("timelapse")
timelapse_tmp_folder = settings.getBaseFolder("timelapse_tmp")
for folder, expected in ((upload_folder, expected_upload_folder),
(timelapse_folder, expected_timelapse_folder),
(timelapse_tmp_folder, expected_timelapse_tmp_folder)):
self.assertIsNotNone(folder)
self.assertEquals(folder, expected)
self.assertTrue(os.path.isdir(folder))
def test_basedir_initialization_with_custom_basedir(self):
with self.mocked_basedir() as default_basedir:
my_basedir = None
try:
my_basedir = tempfile.mkdtemp("octoprint-settings-test-custom")
self.assertNotEqual(my_basedir, default_basedir)
octoprint.settings.Settings(basedir=my_basedir)
self.assertFalse(os.path.isfile(os.path.join(default_basedir, "config.yaml")))
self.assertTrue(os.path.isfile(os.path.join(my_basedir, "config.yaml")))
finally:
try:
shutil.rmtree(my_basedir)
except:
self.fail("Could not remove temporary custom basedir")
def test_basedir_initialization_with_custom_config(self):
config_path = os.path.realpath(os.path.join(os.path.dirname(__file__), "_files", "config.yaml"))
with self.mocked_basedir() as basedir:
my_configdir = None
try:
my_configdir = tempfile.mkdtemp("octoprint-settings-test-custom")
my_configfile = os.path.join(my_configdir, "config.yaml")
shutil.copy(config_path, my_configfile)
expected_upload_folder = os.path.join(basedir, "uploads")
settings = octoprint.settings.Settings(configfile=my_configfile)
upload_folder = settings.getBaseFolder("uploads")
self.assertFalse(os.path.isfile(os.path.join(basedir, "config.yaml")))
self.assertTrue(os.path.isfile(my_configfile))
self.assertIsNotNone(upload_folder)
self.assertTrue(os.path.isdir(upload_folder))
self.assertEqual(expected_upload_folder, upload_folder)
finally:
try:
shutil.rmtree(my_configdir)
except:
self.fail("Could not remove temporary custom basedir")
##~~ test getters
def test_get(self):
with self.mocked_config():
expected_api_key = "test"
settings = octoprint.settings.Settings()
api_key = settings.get(["api", "key"])
self.assertIsNotNone(api_key)
self.assertEqual(api_key, expected_api_key)
def test_get_int(self):
with self.mocked_config():
expected_server_port = 8080
settings = octoprint.settings.Settings()
server_port = settings.get(["server", "port"])
self.assertIsNotNone(server_port)
self.assertEqual(server_port, expected_server_port)
def test_get_int_converted(self):
with self.mocked_config():
settings = octoprint.settings.Settings()
value = settings.getInt(["serial", "timeout", "connection"])
self.assertEqual(5, value)
def test_get_int_invalid(self):
with self.mocked_config():
settings = octoprint.settings.Settings()
value = settings.getInt(["server", "host"])
self.assertIsNone(value)
def test_get_float(self):
with self.mocked_config():
expected_serial_timeout = 1.0
settings = octoprint.settings.Settings()
serial_timeout = settings.get(["serial", "timeout", "detection"])
self.assertIsNotNone(serial_timeout)
self.assertEqual(serial_timeout, expected_serial_timeout)
def test_get_float_converted(self):
with self.mocked_config():
settings = octoprint.settings.Settings()
value = settings.getFloat(["serial", "timeout", "connection"])
self.assertEqual(5.0, value)
def test_get_float_invalid(self):
with self.mocked_config():
settings = octoprint.settings.Settings()
value = settings.getFloat(["server", "host"])
self.assertIsNone(value)
def test_get_boolean(self):
with self.mocked_config():
settings = octoprint.settings.Settings()
value = settings.get(["devel", "virtualPrinter", "enabled"])
self.assertTrue(value)
def test_get_list(self):
with self.mocked_config():
settings = octoprint.settings.Settings()
data = settings.get(["serial", "additionalPorts"])
self.assertEqual(len(data), 2)
self.assertListEqual(["/dev/portA", "/dev/portB"], data)
def test_get_map(self):
with self.mocked_config():
settings = octoprint.settings.Settings()
data = settings.get(["devel", "virtualPrinter"])
self.assertEqual(len(data), 1)
self.assertDictEqual(dict(enabled=True), data)
def test_get_map_merged(self):
with self.mocked_config():
settings = octoprint.settings.Settings()
data = settings.get(["devel", "virtualPrinter"], merged=True)
self.assertGreater(len(data), 1)
self.assertDictContainsSubset(dict(enabled=True,
sendWait=True,
waitInterval=1.0),
data)
def test_get_multiple(self):
with self.mocked_config():
settings = octoprint.settings.Settings()
data = settings.get(["serial", ["timeout", "additionalPorts"]])
self.assertIsInstance(data, list)
self.assertEqual(len(data), 2)
self.assertIsInstance(data[0], dict)
self.assertIsInstance(data[1], list)
def test_get_multiple_asdict(self):
with self.mocked_config():
settings = octoprint.settings.Settings()
data = settings.get(["serial", ["timeout", "additionalPorts"]], asdict=True)
self.assertIsInstance(data, dict)
self.assertEqual(len(data), 2)
self.assertTrue("timeout" in data)
self.assertTrue("additionalPorts" in data)
def test_get_invalid(self):
with self.mocked_config():
settings = octoprint.settings.Settings()
value = settings.get(["i", "do", "not", "exist"])
self.assertIsNone(value)
def test_get_invalid_error(self):
with self.mocked_config():
settings = octoprint.settings.Settings()
try:
settings.get(["i", "do", "not", "exist"], error_on_path=True)
self.fail("Expected NoSuchSettingsPath")
except octoprint.settings.NoSuchSettingsPath:
pass
def test_get_custom_config(self):
with self.mocked_config():
settings = octoprint.settings.Settings()
server_port = settings.getInt(["server", "port"], config=dict(server=dict(port=9090)))
self.assertEqual(9090, server_port)
def test_get_custom_defaults(self):
with self.mocked_config():
settings = octoprint.settings.Settings()
api_enabled = settings.getBoolean(["api", "enabled"], defaults=dict(api=dict(enabled=False)))
self.assertFalse(api_enabled)
def test_get_empty_path(self):
with self.mocked_config():
settings = octoprint.settings.Settings()
self.assertIsNone(settings.get([]))
try:
settings.get([], error_on_path=True)
self.fail("Expected NoSuchSettingsPath")
except octoprint.settings.NoSuchSettingsPath:
pass
##~~ test setters
def test_set(self):
with self.mocked_config():
settings = octoprint.settings.Settings()
settings.set(["server", "host"], "127.0.0.1")
self.assertEqual("127.0.0.1", settings._config["server"]["host"])
def test_set_int(self):
with self.mocked_config():
settings = octoprint.settings.Settings()
settings.setInt(["server", "port"], 8181)
self.assertEqual(8181, settings._config["server"]["port"])
def test_set_int_convert(self):
with self.mocked_config():
settings = octoprint.settings.Settings()
settings.setInt(["server", "port"], "8181")
self.assertEqual(8181, settings._config["server"]["port"])
def test_set_float(self):
with self.mocked_config():
settings = octoprint.settings.Settings()
settings.setFloat(["serial", "timeout", "detection"], 1.2)
self.assertEqual(1.2, settings._config["serial"]["timeout"]["detection"])
def test_set_float_convert(self):
with self.mocked_config():
settings = octoprint.settings.Settings()
settings.setFloat(["serial", "timeout", "detection"], "1.2")
self.assertEqual(1.2, settings._config["serial"]["timeout"]["detection"])
def test_set_boolean(self):
with self.mocked_config():
settings = octoprint.settings.Settings()
settings.setBoolean(["devel", "virtualPrinter", "sendWait"], False)
self.assertEqual(False, settings._config["devel"]["virtualPrinter"]["sendWait"])
@ddt.data("1", "yes", "true", "TrUe", "y", "Y", "YES")
def test_set_boolean_convert_string_true(self, value):
with self.mocked_config():
settings = octoprint.settings.Settings()
settings.setBoolean(["devel", "virtualPrinter", "repetierStyleResends"], value)
self.assertEqual(True, settings._config["devel"]["virtualPrinter"]["repetierStyleResends"])
@ddt.data("0", "no", "false", ["some", "list"], dict(a="dictionary"), lambda: None)
def test_set_boolean_convert_any_false(self, value):
with self.mocked_config():
settings = octoprint.settings.Settings()
settings.setBoolean(["api", "enabled"], value)
self.assertEqual(False, settings._config["api"]["enabled"])
def test_set_default(self):
with self.mocked_config():
settings = octoprint.settings.Settings()
self.assertEqual(8080, settings._config["server"]["port"])
settings.set(["server", "port"], 5000)
self.assertNotIn("port", settings._config["server"])
self.assertEqual(5000, settings.get(["server", "port"]))
def test_set_none(self):
with self.mocked_config():
settings = octoprint.settings.Settings()
self.assertTrue("port" in settings._config["server"])
settings.set(["server", "port"], None)
self.assertFalse("port" in settings._config["server"])
@ddt.data([], ["api", "lock"], ["api", "lock", "door"], ["serial", "additionalPorts", "key"])
def test_set_invalid(self, path):
with self.mocked_config():
settings = octoprint.settings.Settings()
try:
settings.set(path, "value", error_on_path=True)
self.fail("Expected NoSuchSettingsPath")
except octoprint.settings.NoSuchSettingsPath:
pass
##~~ test remove
def test_remove(self):
with self.mocked_config():
settings = octoprint.settings.Settings()
self.assertTrue("port" in settings._config["server"])
settings.remove(["server", "port"])
self.assertFalse("port" in settings._config["server"])
self.assertEqual(5000, settings.get(["server", "port"]))
@ddt.data([], ["server", "lock"], ["serial", "additionalPorts", "key"])
def test_remove_invalid(self, path):
with self.mocked_config():
settings = octoprint.settings.Settings()
try:
settings.remove(path, error_on_path=True)
self.fail("Expected NoSuchSettingsPath")
except octoprint.settings.NoSuchSettingsPath:
pass
##~~ test has
def test_has(self):
with self.mocked_config():
settings = octoprint.settings.Settings()
self.assertTrue(settings.has(["api", "key"]))
self.assertFalse(settings.has(["api", "lock"]))
##~~ test properties
def test_effective(self):
with self.mocked_config():
settings = octoprint.settings.Settings()
effective = settings.effective
self.assertDictEqual(self.expected_effective, effective)
def test_effective_hash(self):
with self.mocked_config():
hash = hashlib.md5()
hash.update(yaml.safe_dump(self.expected_effective))
expected_effective_hash = hash.hexdigest()
print(yaml.safe_dump(self.expected_effective))
settings = octoprint.settings.Settings()
effective_hash = settings.effective_hash
print(yaml.safe_dump(settings.effective))
self.assertEqual(expected_effective_hash, effective_hash)
def test_config_hash(self):
with self.mocked_config():
hash = hashlib.md5()
hash.update(yaml.safe_dump(self.config))
expected_config_hash = hash.hexdigest()
settings = octoprint.settings.Settings()
config_hash = settings.config_hash
self.assertEqual(expected_config_hash, config_hash)
def test_last_modified(self):
with self.mocked_config() as paths:
basedir, configfile = paths
settings = octoprint.settings.Settings()
last_modified = os.stat(configfile).st_mtime
self.assertEqual(settings.last_modified, last_modified)
##~~ test preprocessors
def test_get_preprocessor(self):
with self.mocked_config():
config = dict()
defaults = dict(test="some string")
preprocessors = dict(test=lambda x: x.upper())
settings = octoprint.settings.Settings()
value = settings.get(["test"],
config=config,
defaults=defaults,
preprocessors=preprocessors)
self.assertEqual("SOME STRING", value)
def test_set_preprocessor(self):
with self.mocked_config():
config = dict()
defaults = dict(foo=dict(bar="fnord"))
preprocessors = dict(foo=dict(bar=lambda x: x.upper()))
settings = octoprint.settings.Settings()
settings.set(["foo", "bar"],
"value",
config=config,
defaults=defaults,
preprocessors=preprocessors)
self.assertEqual("VALUE", config["foo"]["bar"])
def test_set_external_modification(self):
with self.mocked_config() as paths:
basedir, configfile = paths
settings = octoprint.settings.Settings()
self.assertEqual("0.0.0.0", settings.get(["server", "host"]))
# modify yaml file externally
with open(configfile, "r+b") as f:
config = yaml.safe_load(f)
config["server"]["host"] = "127.0.0.1"
with open(configfile, "w+b") as f:
yaml.safe_dump(config, f)
# set some value, should also reload file before setting new api key
settings.set(["api", "key"], "key")
# verify updated values
self.assertEqual("127.0.0.1", settings.get(["server", "host"]))
self.assertEqual("key", settings.get(["api", "key"]))
##~~ test save
def test_save(self):
with self.mocked_config() as paths:
basedir, config_path = paths
settings = octoprint.settings.Settings()
# current modification date of config.yaml
current_modified = os.stat(config_path).st_mtime
# set a new value
settings.set(["api", "key"], "newkey")
# should not be written automatically
self.assertEqual(current_modified, os.stat(config_path).st_mtime)
# should be updated after calling save though
settings.save()
self.assertNotEqual(current_modified, os.stat(config_path).st_mtime)
def test_save_unmodified(self):
with self.mocked_config():
settings = octoprint.settings.Settings()
last_modified = settings.last_modified
settings.save()
self.assertEqual(settings.last_modified, last_modified)
settings.save(force=True)
self.assertGreater(settings.last_modified, last_modified)
##~~ helpers
@contextlib.contextmanager
def mocked_basedir(self):
orig_default_basedir = octoprint.settings._default_basedir
directory = None
try:
directory = tempfile.mkdtemp("octoprint-settings-test")
octoprint.settings._default_basedir = lambda *args, **kwargs: directory
yield directory
finally:
octoprint.settings._default_basedir = orig_default_basedir
if directory is not None:
try:
shutil.rmtree(directory)
except:
self.fail("Could not remove temporary basedir")
@contextlib.contextmanager
def mocked_config(self):
orig_defaults = octoprint.settings.default_settings
with self.mocked_basedir() as basedir:
fresh_config_path = os.path.join(basedir, "config.yaml")
shutil.copy(self.config_path, fresh_config_path)
try:
octoprint.settings.default_settings = self.defaults
yield basedir, fresh_config_path
finally:
octoprint.settings.default_settings = orig_defaults
+47 -47
View File
@@ -5,21 +5,20 @@
#
msgid ""
msgstr ""
"Project-Id-Version: OctoPrint\n"
"Project-Id-Version: OctoPrint\n"
"Report-Msgid-Bugs-To: i18n@octoprint.org\n"
"POT-Creation-Date: 2016-06-08 11:03+0200\n"
"POT-Creation-Date: 2016-06-16 12:18+0200\n"
"PO-Revision-Date: 2016-06-08 11:04+0100\n"
"Last-Translator: Gina Häußge <osd@foosel.net>\n"
"Language: de\n"
"Language-Team: German (http://www.transifex.com/projects/p/octoprint/language/de/)\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"Plural-Forms: nplurals=2; plural=(n != 1)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: Babel 2.2.0\n"
"X-Generator: Poedit 1.6.8\n"
#: src/octoprint/plugins/announcements/__init__.py:85
#: src/octoprint/plugins/announcements/__init__.py:89
#: src/octoprint/plugins/announcements/templates/announcements.jinja2:4
#: src/octoprint/plugins/announcements/templates/announcements_navbar.jinja2:1
msgid "Announcements"
@@ -976,73 +975,73 @@ msgstr "Zugriff"
msgid "Interface"
msgstr "Interface"
#: src/octoprint/static/js/app/dataupdater.js:92
#: src/octoprint/static/js/app/dataupdater.js:127
#: src/octoprint/static/js/app/dataupdater.js:96
#: src/octoprint/static/js/app/dataupdater.js:131
#: src/octoprint/static/js/app/helpers.js:451
#: src/octoprint/templates/overlays/offline.jinja2:6
msgid "Server is offline"
msgstr "Der Server ist offline"
#: src/octoprint/static/js/app/dataupdater.js:93
#: src/octoprint/static/js/app/dataupdater.js:97
msgid "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect anytime using the button below."
msgstr "Der Server scheint offline zu sein, zumindest kann ich mich nicht mit ihm verbinden. Ich werde <strong>in den nächsten Minuten</strong> versuchen mich erneut zu verbinden, aber Du kannst mittels des folgenden Buttons auch jederzeit einen manuellen Verbindungsversuch anstoßen."
#: src/octoprint/static/js/app/dataupdater.js:128
#: src/octoprint/static/js/app/dataupdater.js:132
msgid "The server appears to be offline, at least I'm not getting any response from it. I <strong>could not reconnect automatically</strong>, but you may try a manual reconnect using the button below."
msgstr "Der Server scheint offline zu sein, zumindest kann ich mich nicht mit ihm verbinden. Ich <strong>konnte mich nicht automatisch neu verbinden</strong>, aber Du kannst mittels des folgenden Buttons einen manuellen Verbindungsversuch anstoßen."
#: src/octoprint/static/js/app/dataupdater.js:206
#: src/octoprint/static/js/app/dataupdater.js:226
#: src/octoprint/static/js/app/dataupdater.js:217
#: src/octoprint/static/js/app/dataupdater.js:237
#, python-format
msgid "Slicing ... (%(percentage)d%%)"
msgstr "Slice ... (%(percentage)d%%)"
#: src/octoprint/static/js/app/dataupdater.js:228
#: src/octoprint/static/js/app/dataupdater.js:239
msgid "Slicing ..."
msgstr "Slice ..."
#: src/octoprint/static/js/app/dataupdater.js:234
#: src/octoprint/static/js/app/dataupdater.js:245
msgid "Slicing done"
msgstr "Slicing abgeschlossen"
#: src/octoprint/static/js/app/dataupdater.js:234
#: src/octoprint/static/js/app/dataupdater.js:245
#, python-format
msgid "Sliced %(stl)s to %(gcode)s, took %(time).2f seconds"
msgstr "%(stl)s nach %(gcode)s geslicet, dauerte %(time).2f Sekunden"
#: src/octoprint/static/js/app/dataupdater.js:244
#: src/octoprint/static/js/app/dataupdater.js:255
#, python-format
msgid "Could not slice %(stl)s to %(gcode)s: %(reason)s"
msgstr "Konnte %(stl)s nicht nach %(gcode)s slicen: %(reason)s"
#: src/octoprint/static/js/app/dataupdater.js:245
#: src/octoprint/static/js/app/dataupdater.js:256
msgid "Slicing failed"
msgstr "Slicing fehlgeschlagen"
#: src/octoprint/static/js/app/dataupdater.js:249
#: src/octoprint/static/js/app/dataupdater.js:260
msgid "Streaming ..."
msgstr "Streaming ..."
#: src/octoprint/static/js/app/dataupdater.js:255
#: src/octoprint/static/js/app/dataupdater.js:266
msgid "Streaming done"
msgstr "Streaming abgeschlossen"
#: src/octoprint/static/js/app/dataupdater.js:256
#: src/octoprint/static/js/app/dataupdater.js:267
#, python-format
msgid "Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds"
msgstr "%(local)s nach %(remote)s gestreamt, dauerte %(time).2f Sekunden"
#: src/octoprint/static/js/app/dataupdater.js:262
#: src/octoprint/static/js/app/dataupdater.js:270
#: src/octoprint/static/js/app/dataupdater.js:273
#: src/octoprint/static/js/app/dataupdater.js:281
msgid "Unhandled communication error"
msgstr "Unbehandelter Kommunikationsfehler"
#: src/octoprint/static/js/app/dataupdater.js:263
#: src/octoprint/static/js/app/dataupdater.js:274
#, python-format
msgid "There was an unhandled error while talking to the printer. Due to that the ongoing print job was cancelled. Error: %(firmwareError)s"
msgstr "Es gab einen unbehandelten Fehler bei der Kommunikation mit dem Drucker. Daher wurder der laufende Druckauftrag abgebrochen. Fehler: %(firmwareError)s"
#: src/octoprint/static/js/app/dataupdater.js:271
#: src/octoprint/static/js/app/dataupdater.js:282
#, python-format
msgid "The was an unhandled error while talking to the printer. Due to that OctoPrint disconnected. Error: %(error)s"
msgstr "Es gab einen unbehandelten Fehler bei der Kommunikation mit dem Drucker. Daher hat OctoPrint die Verbindung getrennt. Fehler: %(error)s"
@@ -1120,14 +1119,14 @@ msgstr "Trennen"
#: src/octoprint/static/js/app/viewmodels/control.js:65
#: src/octoprint/static/js/app/viewmodels/files.js:329
#: src/octoprint/static/js/app/viewmodels/gcode.js:465
#: src/octoprint/static/js/app/viewmodels/gcode.js:471
#: src/octoprint/static/js/app/viewmodels/printerstate.js:177
#: src/octoprint/static/js/app/viewmodels/temperature.js:56
#: src/octoprint/static/js/app/viewmodels/temperature.js:58
msgid "Tool"
msgstr "Werkzeug"
#: src/octoprint/static/js/app/viewmodels/control.js:71
#: src/octoprint/static/js/app/viewmodels/temperature.js:67
#: src/octoprint/static/js/app/viewmodels/temperature.js:69
msgid "Hotend"
msgstr "Hotend"
@@ -1160,15 +1159,15 @@ msgstr "Zuletzt gedruckt"
msgid "Last Print Time"
msgstr "Letzte Druckdauer"
#: src/octoprint/static/js/app/viewmodels/files.js:520
#: src/octoprint/static/js/app/viewmodels/files.js:515
msgid "Could not upload the file. Make sure that it is a GCODE file and has the extension \".gcode\" or \".gco\" or that it is an STL file with the extension \".stl\"."
msgstr "Konnte die Datei nicht hochladen. Bitte stelle sicher, dass es sich um eine GCODE-Datei mit der Extension \".gcode\" oder \".gco\" oder um eine STL-Datei mit der Extension \".stl\" handelt."
#: src/octoprint/static/js/app/viewmodels/files.js:541
#: src/octoprint/static/js/app/viewmodels/files.js:536
msgid "Uploading ..."
msgstr "Uploade ..."
#: src/octoprint/static/js/app/viewmodels/files.js:548
#: src/octoprint/static/js/app/viewmodels/files.js:543
msgid "Saving ..."
msgstr "Speichere ..."
@@ -1188,52 +1187,52 @@ msgstr "Analysiere..."
msgid "Analyzed"
msgstr "Analysiert"
#: src/octoprint/static/js/app/viewmodels/gcode.js:431
#: src/octoprint/static/js/app/viewmodels/gcode.js:437
msgid "Model size"
msgstr "Modelgröße"
#: src/octoprint/static/js/app/viewmodels/gcode.js:432
#: src/octoprint/static/js/app/viewmodels/gcode.js:438
msgid "Estimated total print time"
msgstr "Geschätzte Gesamtdruckdauer"
#: src/octoprint/static/js/app/viewmodels/gcode.js:433
#: src/octoprint/static/js/app/viewmodels/gcode.js:439
msgid "Estimated layer height"
msgstr "Geschätzte Schichthöhe"
#: src/octoprint/static/js/app/viewmodels/gcode.js:433
#: src/octoprint/static/js/app/viewmodels/gcode.js:439
msgid "mm"
msgstr "mm"
#: src/octoprint/static/js/app/viewmodels/gcode.js:434
#: src/octoprint/static/js/app/viewmodels/gcode.js:440
msgid "Layer count"
msgstr "Schichtanzahl"
#: src/octoprint/static/js/app/viewmodels/gcode.js:434
#: src/octoprint/static/js/app/viewmodels/gcode.js:440
msgid "printed"
msgstr "gedruckt"
#: src/octoprint/static/js/app/viewmodels/gcode.js:434
#: src/octoprint/static/js/app/viewmodels/gcode.js:440
msgid "visited"
msgstr "besucht"
#: src/octoprint/static/js/app/viewmodels/gcode.js:457
#: src/octoprint/static/js/app/viewmodels/gcode.js:463
msgid "Layer number"
msgstr "Schichtnummer"
#: src/octoprint/static/js/app/viewmodels/gcode.js:458
#: src/octoprint/static/js/app/viewmodels/gcode.js:464
msgid "Layer height"
msgstr "Schichthöhe"
#: src/octoprint/static/js/app/viewmodels/gcode.js:459
#: src/octoprint/static/js/app/viewmodels/gcode.js:465
msgid "GCODE commands in layer"
msgstr "GCODE Befehle in Schicht"
#: src/octoprint/static/js/app/viewmodels/gcode.js:462
#: src/octoprint/static/js/app/viewmodels/gcode.js:465
#: src/octoprint/static/js/app/viewmodels/gcode.js:468
#: src/octoprint/static/js/app/viewmodels/gcode.js:471
msgid "Filament used by layer"
msgstr "Genutztes Filament in Schicht"
#: src/octoprint/static/js/app/viewmodels/gcode.js:469
#: src/octoprint/static/js/app/viewmodels/gcode.js:475
msgid "Print time for layer"
msgstr "Druckdauer für Schicht"
@@ -1452,25 +1451,25 @@ msgid "Slicing %(filename)s"
msgstr "Slice %(filename)s"
#: src/octoprint/static/js/app/viewmodels/temperature.js:23
#: src/octoprint/static/js/app/viewmodels/temperature.js:74
#: src/octoprint/static/js/app/viewmodels/temperature.js:76
#: src/octoprint/templates/dialogs/settings/temperatures.jinja2:16
msgid "Bed"
msgstr "Bett"
#: src/octoprint/static/js/app/viewmodels/temperature.js:112
#: src/octoprint/static/js/app/viewmodels/temperature.js:115
msgid "just now"
msgstr "gerade eben"
#: src/octoprint/static/js/app/viewmodels/temperature.js:114
#: src/octoprint/static/js/app/viewmodels/temperature.js:117
msgid "min"
msgstr "Min"
#: src/octoprint/static/js/app/viewmodels/temperature.js:253
#: src/octoprint/static/js/app/viewmodels/temperature.js:256
#: src/octoprint/templates/tabs/temperature.jinja2:11
msgid "Actual"
msgstr "Ist"
#: src/octoprint/static/js/app/viewmodels/temperature.js:258
#: src/octoprint/static/js/app/viewmodels/temperature.js:261
#: src/octoprint/templates/tabs/temperature.jinja2:12
msgid "Target"
msgstr "Soll"
@@ -2927,3 +2926,4 @@ msgstr "Zeitrafferaufnahme rendern"
#~ msgid "Show Announcements..."
#~ msgstr "Ankündigungen anzeigen..."
+45 -45
View File
@@ -6,9 +6,9 @@
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: OctoPrint 1.2.12.dev21+g5006b01.dirty\n"
"Project-Id-Version: OctoPrint 1.2.13.dev7+g6c20e58\n"
"Report-Msgid-Bugs-To: i18n@octoprint.org\n"
"POT-Creation-Date: 2016-06-08 11:03+0200\n"
"POT-Creation-Date: 2016-06-16 12:18+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
@@ -17,7 +17,7 @@ msgstr ""
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: Babel 2.2.0\n"
#: src/octoprint/plugins/announcements/__init__.py:85
#: src/octoprint/plugins/announcements/__init__.py:89
#: src/octoprint/plugins/announcements/templates/announcements.jinja2:4
#: src/octoprint/plugins/announcements/templates/announcements_navbar.jinja2:1
msgid "Announcements"
@@ -1045,14 +1045,14 @@ msgstr ""
msgid "Interface"
msgstr ""
#: src/octoprint/static/js/app/dataupdater.js:92
#: src/octoprint/static/js/app/dataupdater.js:127
#: src/octoprint/static/js/app/dataupdater.js:96
#: src/octoprint/static/js/app/dataupdater.js:131
#: src/octoprint/static/js/app/helpers.js:451
#: src/octoprint/templates/overlays/offline.jinja2:6
msgid "Server is offline"
msgstr ""
#: src/octoprint/static/js/app/dataupdater.js:93
#: src/octoprint/static/js/app/dataupdater.js:97
msgid ""
"The server appears to be offline, at least I'm not getting any response "
"from it. I'll try to reconnect automatically <strong>over the next couple"
@@ -1060,67 +1060,67 @@ msgid ""
"anytime using the button below."
msgstr ""
#: src/octoprint/static/js/app/dataupdater.js:128
#: src/octoprint/static/js/app/dataupdater.js:132
msgid ""
"The server appears to be offline, at least I'm not getting any response "
"from it. I <strong>could not reconnect automatically</strong>, but you "
"may try a manual reconnect using the button below."
msgstr ""
#: src/octoprint/static/js/app/dataupdater.js:206
#: src/octoprint/static/js/app/dataupdater.js:226
#: src/octoprint/static/js/app/dataupdater.js:217
#: src/octoprint/static/js/app/dataupdater.js:237
#, python-format
msgid "Slicing ... (%(percentage)d%%)"
msgstr ""
#: src/octoprint/static/js/app/dataupdater.js:228
#: src/octoprint/static/js/app/dataupdater.js:239
msgid "Slicing ..."
msgstr ""
#: src/octoprint/static/js/app/dataupdater.js:234
#: src/octoprint/static/js/app/dataupdater.js:245
msgid "Slicing done"
msgstr ""
#: src/octoprint/static/js/app/dataupdater.js:234
#: src/octoprint/static/js/app/dataupdater.js:245
#, python-format
msgid "Sliced %(stl)s to %(gcode)s, took %(time).2f seconds"
msgstr ""
#: src/octoprint/static/js/app/dataupdater.js:244
#: src/octoprint/static/js/app/dataupdater.js:255
#, python-format
msgid "Could not slice %(stl)s to %(gcode)s: %(reason)s"
msgstr ""
#: src/octoprint/static/js/app/dataupdater.js:245
#: src/octoprint/static/js/app/dataupdater.js:256
msgid "Slicing failed"
msgstr ""
#: src/octoprint/static/js/app/dataupdater.js:249
#: src/octoprint/static/js/app/dataupdater.js:260
msgid "Streaming ..."
msgstr ""
#: src/octoprint/static/js/app/dataupdater.js:255
#: src/octoprint/static/js/app/dataupdater.js:266
msgid "Streaming done"
msgstr ""
#: src/octoprint/static/js/app/dataupdater.js:256
#: src/octoprint/static/js/app/dataupdater.js:267
#, python-format
msgid "Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds"
msgstr ""
#: src/octoprint/static/js/app/dataupdater.js:262
#: src/octoprint/static/js/app/dataupdater.js:270
#: src/octoprint/static/js/app/dataupdater.js:273
#: src/octoprint/static/js/app/dataupdater.js:281
msgid "Unhandled communication error"
msgstr ""
#: src/octoprint/static/js/app/dataupdater.js:263
#: src/octoprint/static/js/app/dataupdater.js:274
#, python-format
msgid ""
"There was an unhandled error while talking to the printer. Due to that "
"the ongoing print job was cancelled. Error: %(firmwareError)s"
msgstr ""
#: src/octoprint/static/js/app/dataupdater.js:271
#: src/octoprint/static/js/app/dataupdater.js:282
#, python-format
msgid ""
"The was an unhandled error while talking to the printer. Due to that "
@@ -1200,14 +1200,14 @@ msgstr ""
#: src/octoprint/static/js/app/viewmodels/control.js:65
#: src/octoprint/static/js/app/viewmodels/files.js:329
#: src/octoprint/static/js/app/viewmodels/gcode.js:465
#: src/octoprint/static/js/app/viewmodels/gcode.js:471
#: src/octoprint/static/js/app/viewmodels/printerstate.js:177
#: src/octoprint/static/js/app/viewmodels/temperature.js:56
#: src/octoprint/static/js/app/viewmodels/temperature.js:58
msgid "Tool"
msgstr ""
#: src/octoprint/static/js/app/viewmodels/control.js:71
#: src/octoprint/static/js/app/viewmodels/temperature.js:67
#: src/octoprint/static/js/app/viewmodels/temperature.js:69
msgid "Hotend"
msgstr ""
@@ -1240,18 +1240,18 @@ msgstr ""
msgid "Last Print Time"
msgstr ""
#: src/octoprint/static/js/app/viewmodels/files.js:520
#: src/octoprint/static/js/app/viewmodels/files.js:515
msgid ""
"Could not upload the file. Make sure that it is a GCODE file and has the "
"extension \".gcode\" or \".gco\" or that it is an STL file with the "
"extension \".stl\"."
msgstr ""
#: src/octoprint/static/js/app/viewmodels/files.js:541
#: src/octoprint/static/js/app/viewmodels/files.js:536
msgid "Uploading ..."
msgstr ""
#: src/octoprint/static/js/app/viewmodels/files.js:548
#: src/octoprint/static/js/app/viewmodels/files.js:543
msgid "Saving ..."
msgstr ""
@@ -1274,52 +1274,52 @@ msgstr ""
msgid "Analyzed"
msgstr ""
#: src/octoprint/static/js/app/viewmodels/gcode.js:431
#: src/octoprint/static/js/app/viewmodels/gcode.js:437
msgid "Model size"
msgstr ""
#: src/octoprint/static/js/app/viewmodels/gcode.js:432
#: src/octoprint/static/js/app/viewmodels/gcode.js:438
msgid "Estimated total print time"
msgstr ""
#: src/octoprint/static/js/app/viewmodels/gcode.js:433
#: src/octoprint/static/js/app/viewmodels/gcode.js:439
msgid "Estimated layer height"
msgstr ""
#: src/octoprint/static/js/app/viewmodels/gcode.js:433
#: src/octoprint/static/js/app/viewmodels/gcode.js:439
msgid "mm"
msgstr ""
#: src/octoprint/static/js/app/viewmodels/gcode.js:434
#: src/octoprint/static/js/app/viewmodels/gcode.js:440
msgid "Layer count"
msgstr ""
#: src/octoprint/static/js/app/viewmodels/gcode.js:434
#: src/octoprint/static/js/app/viewmodels/gcode.js:440
msgid "printed"
msgstr ""
#: src/octoprint/static/js/app/viewmodels/gcode.js:434
#: src/octoprint/static/js/app/viewmodels/gcode.js:440
msgid "visited"
msgstr ""
#: src/octoprint/static/js/app/viewmodels/gcode.js:457
#: src/octoprint/static/js/app/viewmodels/gcode.js:463
msgid "Layer number"
msgstr ""
#: src/octoprint/static/js/app/viewmodels/gcode.js:458
#: src/octoprint/static/js/app/viewmodels/gcode.js:464
msgid "Layer height"
msgstr ""
#: src/octoprint/static/js/app/viewmodels/gcode.js:459
#: src/octoprint/static/js/app/viewmodels/gcode.js:465
msgid "GCODE commands in layer"
msgstr ""
#: src/octoprint/static/js/app/viewmodels/gcode.js:462
#: src/octoprint/static/js/app/viewmodels/gcode.js:465
#: src/octoprint/static/js/app/viewmodels/gcode.js:468
#: src/octoprint/static/js/app/viewmodels/gcode.js:471
msgid "Filament used by layer"
msgstr ""
#: src/octoprint/static/js/app/viewmodels/gcode.js:469
#: src/octoprint/static/js/app/viewmodels/gcode.js:475
msgid "Print time for layer"
msgstr ""
@@ -1544,25 +1544,25 @@ msgid "Slicing %(filename)s"
msgstr ""
#: src/octoprint/static/js/app/viewmodels/temperature.js:23
#: src/octoprint/static/js/app/viewmodels/temperature.js:74
#: src/octoprint/static/js/app/viewmodels/temperature.js:76
#: src/octoprint/templates/dialogs/settings/temperatures.jinja2:16
msgid "Bed"
msgstr ""
#: src/octoprint/static/js/app/viewmodels/temperature.js:112
#: src/octoprint/static/js/app/viewmodels/temperature.js:115
msgid "just now"
msgstr ""
#: src/octoprint/static/js/app/viewmodels/temperature.js:114
#: src/octoprint/static/js/app/viewmodels/temperature.js:117
msgid "min"
msgstr ""
#: src/octoprint/static/js/app/viewmodels/temperature.js:253
#: src/octoprint/static/js/app/viewmodels/temperature.js:256
#: src/octoprint/templates/tabs/temperature.jinja2:11
msgid "Actual"
msgstr ""
#: src/octoprint/static/js/app/viewmodels/temperature.js:258
#: src/octoprint/static/js/app/viewmodels/temperature.js:261
#: src/octoprint/templates/tabs/temperature.jinja2:12
msgid "Target"
msgstr ""