Merge branch 'maintenance' into devel

# Conflicts:
#	src/octoprint/server/util/flask.py
#	src/octoprint/static/js/app/main.js
#	src/octoprint/users.py
This commit is contained in:
Gina Häußge committed 2017-07-05 09:30:00 +02:00
commit 2e6d65378f
61 files changed
+4181 -1486

No files matched your search

+36
View File
@@ -54,6 +54,12 @@ under Settings > Plugin Manager, or by directly editing ``config.yaml``:
# Time to live for the repository cache
repository_ttl: 1440
# The URL of the plugin notices feed to use
notices: http://plugins.octoprint.org/notices.json
# Time to live for the notices feed cache
notices_ttl: 360
# Additional arguments to use with pip. Defaults to unset,
# you normally shouldn't need to modify this
pip_args: --some --additional --pip --arguments
@@ -76,6 +82,36 @@ under Settings > Plugin Manager, or by directly editing ``config.yaml``:
- hidden
- plugins
.. _sec-bundledplugins-pluginmanager-hooks:
Hooks
-----
.. _sec-bundledplugins-pluginmanager-hooks-reconnect_hooks:
octoprint.plugin.pluginmanager.reconnect_hooks
++++++++++++++++++++++++++++++++++++++++++++++
.. py:function:: reconnect_hooks_hook(*args, **kwargs)
Returns additional hooks defined by the plugin for which the plugin manager
should display the "You should reconnect to your printer" message on plugin
install/uninstall/enabling/disabling.
Handlers should return a Python list containing the affected hook names.
**Example**
.. code-block:: python
def reconnect_hooks_hook(*args, **kwargs):
return ["octoprint.plugin.exampleplugin.some_custom_hook",
"octoprint.plugin.exampleplugin.some_other_custom_hook"]
__plugin_hooks__ = {
"octoprint.plugin.pluginmanager.reconnect_hooks": reconnect_hooks_hook
}
.. _sec-bundledplugins-pluginmanager-sourcecode:
Source Code
+1 -1
View File
@@ -33,7 +33,7 @@ needs_sphinx = '1.3'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['codeblockext', 'onlineinclude', 'sphinx.ext.todo', 'sphinx.ext.autodoc', 'sphinxcontrib.httpdomain',
'sphinx.ext.napoleon']
'sphinx.ext.napoleon', 'sphinxcontrib.mermaid']
todo_include_todos = True
# Add any paths that contain templates here, relative to this directory.
+9
View File
@@ -477,6 +477,15 @@ PositionUpdate
* ``t``: last tool selected *through OctoPrint*
* ``f``: last feedrate for move commands ``G0``, ``G1`` or ``G28`` sent *through OctoPrint*
ToolChange
A tool change command was sent to the printer. The payload contains the former current tool index and the
new current tool index.
Payload:
* ``old``: old tool index
* ``new``: new tool index
Timelapses
----------
+18 -8
View File
@@ -68,7 +68,16 @@ All GCODE scripts have access to the following template variables through the te
* ``printer_profile``: The currently selected Printer Profile, including
information such as the extruder count, the build volume size, the filament diameter etc.
* ``last_position``: Last position reported by the printer via `M114` (might be unset if no `M114` was sent so far!)
* ``last_position``: Last position reported by the printer via `M114` (might be unset if no `M114` was sent so far!).
Consists of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and
current tool ``t`` taken from commands sent through OctoPrint. All of these coordinates might be ``None`` if no
position could be retrieved from the printer or the values could not be tracked (in case of ``f`` and ``t``)!
* ``last_temperature``: Last actual and target temperature reported for all available tools and if available the
heated bed. This is a dictionary of key-value pairs. The keys are the indices of the available tools (``0``, ``1``,
...) and ``b`` for the heated bed. The values are a dictionary consisting of ``actual`` and ``target`` keys mapped
to the corresponding temperature in degrees celsius. Note that not all tools your printer has must necessarily be
present here, neither must the heated bed - it depends on whether OctoPrint has values for a tool or the bed. Also
note that ``actual`` and ``target`` might be ``None``.
* ``script``: An object wrapping the script's type (``gcode``) and name (e.g. ``afterPrintCancelled``) as ``script.type``
and ``script.name`` respectively.
@@ -76,17 +85,18 @@ There are a few additional template variables available for the following specif
* ``afterPrintPaused`` and ``beforePrintResumed``
* ``pause_position``: Position reported by the printer via ``M114`` immediately before the print was paused. Consists
of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and current tool
``t`` taken from commands sent through OctoPrint. All of these coordinates might be ``None`` if no position could be
retrieved from the printer or the values could not be tracked (in case of ``f`` and ``t``)!
* ``pause_position``: Position reported by the printer via ``M114`` immediately before the print was paused. See
``last_position`` above for the structure to expect here.
* ``pause_temperature``: Last known temperature values when the print was paused. See ``last_temperature`` above
for the structure to expect here.
* ``afterPrintCancelled``
* ``cancel_position``: Position reported by the printer via ``M114`` immediately before the print was cancelled.
Consists of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and
current tool ``t`` taken from commands sent through OctoPrint. All of these coordinates might be ``None`` if no
position could be retrieved from the printer or the values could not be tracked (in case of ``f`` and ``t``)!
See ``last_position`` above for the structure to expect here.
* ``cancel_temperature``: Last known temperature values when the print was cancelled. See ``last_temperature`` above
for the structure to expect here.
.. warning::
+10 -7
View File
@@ -451,18 +451,21 @@ This describes actually four hooks:
should use this option.
* A 2-tuple consisting of a rewritten version of the ``cmd`` and the ``cmd_type``, e.g. ``return "M105", "temperature_poll"``.
Handlers which wish to rewrite both the command and the command type should use this option.
* **``queuing`` phase only**: A list of any of the above to allow for expanding one command into
* A list of any of the above to allow for expanding one command into
many. The following example shows how any queued command could be turned into a sequence of a temperature query,
line number reset, display of the ``gcode`` on the printer's display and finally the actual command (this example
does not make a lot of sense to be quiet honest):
does not make a lot of sense to be quite honest):
.. code-block:: python
def multi_expansion(*args, **kwargs):
return [("M105", "temperature_poll"),
("M110",),
"M117 GCODE: {}".format(gcode),
(command, command_type)]
def rewrite_foo(self, comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs):
if gcode or not cmd.startswith("@foo"):
return
return [("M105", "temperature_poll"),
("M110",),
"M117 echo foo: {}".format(cmd)]
Note: Only one command of a given ``cmd_type`` (other than None) may be queued at a time. Trying to rewrite the ``cmd_type``
to one already in the queue will give an error.
+124
View File
@@ -299,6 +299,130 @@ on your view model, taking a list of all bound view models:
});
})
.. _sec-plugins-viewmodels-livecycle:
Lifecycle diagrams
------------------
.. _sec-plugins-viewmodels-startup:
Web interface startup
~~~~~~~~~~~~~~~~~~~~~
.. mermaid::
sequenceDiagram
participant Main
participant onServerConnect
participant fetchSettings
participant bindViewModels
participant DataUpdater
participant LoginStateViewModel
Note right of DataUpdater: connectCallback = undefined
activate Main
Main->>+DataUpdater: connect
Note right of DataUpdater: initialized = false
DataUpdater-->>Main: ok
deactivate Main
DataUpdater->>DataUpdater: asynchronous connect to server...
activate DataUpdater
Note right of DataUpdater: store any callbacks instead of triggering (e.g. onServerConnect, fromHistoryData, fromCurrentData, ...)
DataUpdater-X+Main: done
deactivate DataUpdater
deactivate DataUpdater
Main->>+DataUpdater: connectCallback = onServerConnect
Note right of DataUpdater: connectCallback = onServerConnect
DataUpdater-->>-Main: ok
Main->>+onServerConnect: call
onServerConnect->>+LoginStateViewModel: passiveLogin
LoginStateViewModel-->>onServerConnect: ok
onServerConnect-->>Main: ok
deactivate onServerConnect
deactivate Main
LoginStateViewModel->>+LoginStateViewModel: asynchronous passive login
Note over Main,LoginStateViewModel: Session available!
LoginStateViewModel-X+onServerConnect: done
deactivate LoginStateViewModel
deactivate LoginStateViewModel
onServerConnect->>+DataUpdater: initialized
Note right of DataUpdater: initialized = true
DataUpdater->DataUpdater: trigger stored callbacks
DataUpdater-->>-onServerConnect: ok
onServerConnect-X+Main: done
deactivate onServerConnect
Main->>+fetchSettings: call
Note right of fetchSettings: trigger onStartup
fetchSettings-->>Main: ok
deactivate Main
fetchSettings->>+fetchSettings: asynchronous settings fetch
fetchSettings->>+bindViewModels: call
loop for each view model
bindViewModels->bindViewModels: trigger onBeforeBinding
bindViewModels->bindViewModels: trigger onBoundTo
bindViewModels->bindViewModels: trigger onAfterBinding
end
bindViewModels->bindViewModels: trigger onAllBound
opt User is logged in
bindViewModels->>+LoginStateViewModel: onAllBound
LoginStateViewModel->LoginStateViewModel: trigger onUserLoggedIn
LoginStateViewModel-->>-bindViewModels: ok
end
bindViewModels->bindViewModels: trigger onStartupComplete
bindViewModels-->>-fetchSettings: ok
deactivate fetchSettings
deactivate fetchSettings
.. _sec-plugins-viewmodels-reconnect:
Web interface reconnect
~~~~~~~~~~~~~~~~~~~~~~~
.. mermaid::
sequenceDiagram
participant onServerConnect
participant DataUpdater
participant LoginStateViewModel
activate DataUpdater
DataUpdater->>DataUpdater: call connectCallback
DataUpdater->>+onServerConnect: call
onServerConnect-->>DataUpdater: ok
deactivate DataUpdater
onServerConnect->>+LoginStateViewModel: passiveLogin
LoginStateViewModel-->>onServerConnect: ok
deactivate onServerConnect
LoginStateViewModel->>+LoginStateViewModel: asynchronous passive login
Note over onServerConnect,LoginStateViewModel: Session available!
opt User is logged in
LoginStateViewModel->LoginStateViewModel: trigger onUserLoggedIn
end
activate onServerConnect
LoginStateViewModel-XonServerConnect: done
deactivate LoginStateViewModel
deactivate LoginStateViewModel
onServerConnect->>+DataUpdater: initialized
DataUpdater->DataUpdater: trigger stored callbacks
DataUpdater-->>onServerConnect: ok
deactivate DataUpdater
deactivate onServerConnect
.. seealso::
`OctoPrint's core viewmodels <https://github.com/foosel/OctoPrint/tree/devel/src/octoprint/static/js/app/viewmodels>`_
+85 -27
View File
@@ -7,41 +7,99 @@ __copyright__ = "Copyright (C) 2015 Gina Häußge - Released under terms of the
import codecs
import urllib2
import requests
from contextlib import closing
from sphinx.directives import LiteralInclude, dedent_lines
from sphinx.directives.code import LiteralIncludeReader, LiteralInclude, dedent_lines, \
nodes, set_source_info, parselinenos, logger, container_wrapper
if False:
# For type annotation
from typing import Any, List # NOQA
cache = dict()
class OnlineIncludeReader(LiteralIncludeReader):
def read_file(self, filename, location=None):
# type: (unicode, Any) -> List[unicode]
global cache
try:
if filename in cache:
lines = cache[filename]
else:
with closing(requests.get(filename, stream=True)) as r:
r.encoding = self.encoding
lines = r.text.splitlines(True)
cache[filename] = lines
if 'tab-width' in self.options:
lines = [line.expandtabs(self.options['tab-width']) for line in lines]
return lines
except (IOError, OSError):
raise IOError(_('Include file %r not found or reading it failed') % filename)
except UnicodeError:
raise UnicodeError(_('Encoding %r used for reading included file %r seems to '
'be wrong, try giving an :encoding: option') %
(self.encoding, filename))
class OnlineIncludeDirective(LiteralInclude):
def read_with_encoding(self, filename, document, codec_info, encoding):
global cache
def run(self):
# type: () -> List[nodes.Node]
document = self.state.document
if not document.settings.file_insertion_enabled:
return [document.reporter.warning('File insertion disabled',
line=self.lineno)]
env = document.settings.env
# convert options['diff'] to absolute path
if 'diff' in self.options:
_, path = env.relfn2path(self.options['diff'])
self.options['diff'] = path
f = None
try:
if not self.arguments[0] in cache:
f = codecs.StreamReaderWriter(urllib2.urlopen(self.arguments[0]), codec_info[2],
codec_info[3], 'strict')
lines = f.readlines()
cache[self.arguments[0]] = lines
else:
lines = cache[self.arguments[0]]
location = self.state_machine.get_source_and_line(self.lineno)
url = self.arguments[0]
reader = OnlineIncludeReader(url, self.options, env.config)
text, lines = reader.read(location=location)
retnode = nodes.literal_block(text, text, source=url)
set_source_info(self, retnode)
if self.options.get('diff'): # if diff is set, set udiff
retnode['language'] = 'udiff'
elif 'language' in self.options:
retnode['language'] = self.options['language']
retnode['linenos'] = ('linenos' in self.options or
'lineno-start' in self.options or
'lineno-match' in self.options)
retnode['classes'] += self.options.get('class', [])
extra_args = retnode['highlight_args'] = {}
if 'emphasize-lines' in self.options:
hl_lines = parselinenos(self.options['emphasize-lines'], lines)
if any(i >= lines for i in hl_lines):
logger.warning('line number spec is out of range(1-%d): %r' %
(lines, self.options['emphasize-lines']),
location=location)
extra_args['hl_lines'] = [x + 1 for x in hl_lines if x < lines]
extra_args['linenostart'] = reader.lineno_start
if 'caption' in self.options:
caption = self.options['caption'] or self.arguments[0]
retnode = container_wrapper(self, retnode, caption)
# retnode will be note_implicit_target that is linked from caption and numref.
# when options['name'] is provided, it should be primary ID.
self.add_name(retnode)
return [retnode]
except Exception as exc:
return [document.reporter.warning(str(exc), line=self.lineno)]
lines = dedent_lines(lines, self.options.get('dedent'))
return lines
except (IOError, OSError, urllib2.URLError):
return [document.reporter.warning(
'Include file %r not found or reading it failed' % self.arguments[0],
line=self.lineno)]
except UnicodeError:
return [document.reporter.warning(
'Encoding %r used for reading included file %r seems to '
'be wrong, try giving an :encoding: option' %
(encoding, self.arguments[0]))]
finally:
if f is not None:
f.close()
def visit_onlineinclude(translator, node):
translator.visit_literal_block(node)
@@ -53,4 +111,4 @@ def setup(app):
app.add_directive("onlineinclude", OnlineIncludeDirective)
handler = (visit_onlineinclude, depart_onlineinclude)
app.add_node(OnlineIncludeDirective, html=handler, latex=handler, text=handler)
app.add_node(OnlineIncludeDirective, html=handler, latex=handler, text=handler)
+5 -3
View File
@@ -45,7 +45,8 @@ INSTALL_REQUIRES = [
"future>=0.15,<0.16",
"scandir>=1.3,<1.4",
"websocket-client>=0.40,<0.41",
"python-dateutil>=2.6,<2.7"
"python-dateutil>=2.6,<2.7",
"wrapt>=1.10.10,<1.11"
]
if sys.platform == "darwin":
@@ -61,9 +62,10 @@ EXTRA_REQUIRES = dict(
"ddt",
# Documentation dependencies
"sphinx>=1.3,<1.4",
"sphinx>=1.6,<1.7",
"sphinxcontrib-httpdomain",
"sphinx_rtd_theme",
"sphinxcontrib-mermaid",
"sphinx_bootstrap_theme",
# PyPi upload related
"pypandoc"
+1
View File
@@ -84,6 +84,7 @@ class Events(object):
EJECT = "Eject"
E_STOP = "EStop"
POSITION_UPDATE = "PositionUpdate"
TOOL_CHANGE = "ToolChange"
REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived"
# Timelapse
+81 -27
View File
@@ -19,8 +19,6 @@ import time
from octoprint.events import Events, eventManager
from octoprint.settings import settings
import octoprint.util.gcodeInterpreter as gcodeInterpreter
class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile")):
"""
@@ -305,39 +303,95 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
* The extruded volume in cm³
"""
def _do_analysis(self, high_priority=False):
try:
throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"])
throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"])
if throttle > 0:
def throttle_callback(filePos, readBytes):
if filePos % throttle_lines == 0:
# only apply throttle every 100 lines
time.sleep(throttle)
else:
throttle_callback = None
def __init__(self, finished_callback):
AbstractAnalysisQueue.__init__(self, finished_callback)
self._gcode = gcodeInterpreter.gcode()
self._gcode.load(self._current.absolute_path, self._current.printer_profile, throttle=throttle_callback)
self._aborted = False
self._reenqueue = False
def _do_analysis(self, high_priority=False):
import sarge
import sys
import yaml
try:
throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority \
else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"])
throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"])
max_extruders = settings().getInt(["gcodeAnalysis", "maxExtruders"])
g90_extruder = settings().getBoolean(["feature", "g90InfluencesExtruder"])
speedx = self._current.printer_profile["axes"]["x"]["speed"]
speedy = self._current.printer_profile["axes"]["y"]["speed"]
offsets = self._current.printer_profile["extruder"]["offsets"]
interpreter = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "util", "gcodeInterpreter.py"))
command = [sys.executable, interpreter, "--speed-x={}".format(speedx), "--speed-y={}".format(speedy),
"--max-t={}".format(max_extruders), "--throttle={}".format(throttle),
"--throttle-lines={}".format(throttle_lines)]
for offset in offsets[1:]:
command += ["--offset", str(offset[0]), str(offset[1])]
if g90_extruder:
command += ["--g90-extruder"]
command.append(self._current.absolute_path)
self._logger.info("Invoking analysis command: {}".format(" ".join(command)))
self._aborted = False
p = sarge.run(command, async=True, stdout=sarge.Capture())
while len(p.commands) == 0:
# somewhat ugly... we can't use wait_events because
# the events might not be all set if an exception
# by sarge is triggered within the async process
# thread
time.sleep(0.01)
# by now we should have a command, let's wait for its
# process to have been prepared
p.commands[0].process_ready.wait()
if not p.commands[0].process:
# the process might have been set to None in case of any exception
raise RuntimeError(u"Error while trying to run command {}".format(" ".join(command)))
try:
# let's wait for stuff to finish
while p.returncode is None:
if self._aborted:
# oh, we shall abort, let's do so!
p.commands[0].terminate()
raise AnalysisAborted(reenqueue=self._reenqueue)
# else continue
p.commands[0].poll()
finally:
p.close()
output = p.stdout.text
self._logger.debug("Got output: {!r}".format(output))
if not "RESULTS:" in output:
raise RuntimeError("No analysis result found")
_, output = output.split("RESULTS:")
analysis = yaml.safe_load(output)
result = dict()
result["printingArea"] = self._gcode.printing_area
result["dimensions"] = self._gcode.dimensions
if self._gcode.totalMoveTimeMinute:
result["estimatedPrintTime"] = self._gcode.totalMoveTimeMinute * 60
if self._gcode.extrusionAmount:
result["printingArea"] = analysis["printing_area"]
result["dimensions"] = analysis["dimensions"]
if analysis["total_time"]:
result["estimatedPrintTime"] = analysis["total_time"] * 60
if analysis["extrusion_length"]:
result["filament"] = dict()
for i in range(len(self._gcode.extrusionAmount)):
for i in range(len(analysis["extrusion_length"])):
result["filament"]["tool%d" % i] = {
"length": self._gcode.extrusionAmount[i],
"volume": self._gcode.extrusionVolume[i]
"length": analysis["extrusion_length"][i],
"volume": analysis["extrusion_volume"][i]
}
return result
except gcodeInterpreter.AnalysisAborted as ex:
raise AnalysisAborted(reenqueue=ex.reenqueue)
finally:
self._gcode = None
def _do_abort(self, reenqueue=True):
if self._gcode:
self._gcode.abort(reenqueue=reenqueue)
self._aborted = True
self._reenqueue = reenqueue
+18 -7
View File
@@ -104,7 +104,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
UiPlugin]
if plugin_restart_needing_hooks is None:
plugin_restart_needing_hooks = ["octoprint.server.http"]
plugin_restart_needing_hooks = ["octoprint.server.http.*",
"octoprint.printer.factory"]
if plugin_obsolete_hooks is None:
plugin_obsolete_hooks = ["octoprint.comm.protocol.gcode"]
@@ -263,13 +264,17 @@ class PluginSettings(object):
:returns: The retrieved settings value.
:rtype: object
.. method:: get_int(path)
.. method:: get_int(path, min=None, max=None)
Like :func:`get` but tries to convert the retrieved value to ``int``.
Like :func:`get` but tries to convert the retrieved value to ``int``. If ``min`` is provided and the retrieved
value is less than it, it will be returned instead of the value. Likewise for ``max`` - it will be returned if
the value is greater than it.
.. method:: get_float(path)
.. method:: get_float(path, min=None, max=None)
Like :func:`get` but tries to convert the retrieved value to ``float``.
Like :func:`get` but tries to convert the retrieved value to ``float``. If ``min`` is provided and the retrieved
value is less than it, it will be returned instead of the value. Likewise for ``max`` - it will be returned if
the value is greater than it.
.. method:: get_boolean(path)
@@ -285,13 +290,19 @@ class PluginSettings(object):
:param boolean force: If set to True, the modified configuration will even be written back to disk if
the value didn't change.
.. method:: set_int(path, value, force=False)
.. method:: set_int(path, value, force=False, min=None, max=None)
Like :func:`set` but ensures the value is an ``int`` through attempted conversion before setting it.
If ``min`` and/or ``max`` are provided, it will also be ensured that the value is greater than or equal
to ``min`` and less than or equal to ``max``. If that is not the case, the limit value (``min`` if less than
that, ``max`` if greater than that) will be set instead.
.. method:: set_float(path, value, force=False)
.. method:: set_float(path, value, force=False, min=None, max=None)
Like :func:`set` but ensures the value is an ``float`` through attempted conversion before setting it.
If ``min`` and/or ``max`` are provided, it will also be ensured that the value is greater than or equal
to ``min`` and less than or equal to ``max``. If that is not the case, the limit value (``min`` if less than
that, ``max`` if greater than that) will be set instead.
.. method:: set_boolean(path, value, force=False)
+93 -30
View File
@@ -31,6 +31,7 @@ import os
import imp
from collections import defaultdict, namedtuple, OrderedDict
import logging
import fnmatch
import pkg_resources
import pkginfo
@@ -946,45 +947,107 @@ class PluginManager(object):
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:
return False
return isinstance(plugin.implementation, RestartNeedingPlugin)
return self.has_any_of_mixins(plugin, RestartNeedingPlugin)
def has_restart_needing_hooks(self, plugin):
if not plugin.hooks:
return False
hooks = plugin.hooks.keys()
for hook in hooks:
if self.is_restart_needing_hook(hook):
return True
return False
return self.has_any_of_hooks(plugin, self.plugin_restart_needing_hooks)
def has_obsolete_hooks(self, plugin):
if not plugin.hooks:
return False
hooks = plugin.hooks.keys()
for hook in hooks:
if self.is_obsolete_hook(hook):
return True
return False
return self.has_any_of_hooks(plugin, self.plugin_obsolete_hooks)
def is_restart_needing_hook(self, hook):
if self.plugin_restart_needing_hooks is None:
return False
for h in self.plugin_restart_needing_hooks:
if hook.startswith(h):
return True
return False
return self.hook_matches_hooks(hook, self.plugin_restart_needing_hooks)
def is_obsolete_hook(self, hook):
if self.plugin_obsolete_hooks is None:
return self.hook_matches_hooks(hook, self.plugin_obsolete_hooks)
@staticmethod
def has_any_of_hooks(plugin, *hooks):
"""
Tests if the ``plugin`` contains any of the provided ``hooks``.
Uses :func:`octoprint.plugin.core.PluginManager.hook_matches_hooks`.
Args:
plugin: plugin to test hooks for
*hooks: hooks to test against
Returns:
(bool): True if any of the plugin's hooks match the provided hooks,
False otherwise.
"""
if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)):
hooks = hooks[0]
hooks = filter(lambda hook: hook is not None, hooks)
if not hooks:
return False
return hook in self.plugin_obsolete_hooks
if not plugin or not plugin.hooks:
return False
plugin_hooks = plugin.hooks.keys()
return any(map(lambda hook: PluginManager.hook_matches_hooks(hook, *hooks),
plugin_hooks))
@staticmethod
def hook_matches_hooks(hook, *hooks):
"""
Tests if ``hook`` matches any of the provided ``hooks`` to test for.
``hook`` is expected to be an exact hook name.
``hooks`` is expected to be a list containing one or more hook names or
patterns. That can be either an exact hook name or an
:func:`fnmatch.fnmatch` pattern.
Args:
hook: the hook to test
hooks: the hook name patterns to test against
Returns:
(bool): True if the ``hook`` matches any of the ``hooks``, False otherwise.
"""
if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)):
hooks = hooks[0]
hooks = filter(lambda hook: hook is not None, hooks)
if not hooks:
return False
if not hook:
return False
return any(map(lambda h: fnmatch.fnmatch(hook, h),
hooks))
@staticmethod
def has_any_of_mixins(plugin, *mixins):
"""
Tests if the ``plugin`` has an implementation implementing any
of the provided ``mixins``.
Args:
plugin: plugin for which to check the implementation
*mixins: mixins to test against
Returns:
(bool): True if the plugin's implementation implements any of the
provided mixins, False otherwise.
"""
if mixins and len(mixins) == 1 and isinstance(mixins[0], (list, tuple)):
mixins = mixins[0]
mixins = filter(lambda mixin: mixin is not None, mixins)
if not mixins:
return False
if not plugin or not plugin.implementation:
return False
return isinstance(plugin.implementation, tuple(mixins))
def initialize_implementations(self, additional_injects=None, additional_inject_factories=None, additional_pre_inits=None, additional_post_inits=None):
for name, plugin in self.enabled_plugins.items():
+1 -1
View File
@@ -743,7 +743,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
OctoPrint's version, current ``UI_API_KEY``, tracked file paths and ``LastModified`` value).
Returns:
basestring: An alternatively calculated ETag value. Ignored if ``None`` is returned (default).
str: An alternatively calculated ETag value. Ignored if ``None`` is returned (default).
"""
return None
@@ -5,6 +5,7 @@ __author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
from past.builtins import basestring
import octoprint.plugin
import octoprint.plugin.core
@@ -44,7 +45,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
macos=["darwin"],
freebsd=lambda x: x.startswith("freebsd"))
pip_inapplicable_arguments = dict(uninstall=["--user"])
PIP_INAPPLICABLE_ARGUMENTS = dict(uninstall=["--user"])
RECONNECT_HOOKS = ["octoprint.comm.protocol.*",]
def __init__(self):
self._pending_enable = set()
@@ -415,6 +418,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
source_type=source_type,
needs_restart=True,
needs_refresh=True,
needs_reconnect=True,
was_reinstalled=False,
plugin="unknown")
self._send_result_notification("install", result)
@@ -426,6 +430,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
or reinstall is not None
needs_refresh = new_plugin.implementation \
and isinstance(new_plugin.implementation, octoprint.plugin.ReloadNeedingPlugin)
needs_reconnect = self._plugin_manager.has_any_of_hooks(new_plugin, self._reconnect_hooks) and self._printer.is_operational()
is_reinstall = self._plugin_manager.is_plugin_marked(new_plugin.key, "uninstalled")
self._plugin_manager.mark_plugin(new_plugin.key,
@@ -440,6 +445,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
source_type=source_type,
needs_restart=needs_restart,
needs_refresh=needs_refresh,
needs_reconnect=needs_reconnect,
was_reinstalled=new_plugin.key in all_plugins_before or reinstall is not None,
plugin=self._to_external_plugin(new_plugin))
self._send_result_notification("install", result)
@@ -496,6 +502,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin)
needs_refresh = plugin.implementation and isinstance(plugin.implementation, octoprint.plugin.ReloadNeedingPlugin)
needs_reconnect = self._plugin_manager.has_any_of_hooks(plugin, self._reconnect_hooks) and self._printer.is_operational()
was_pending_install = self._plugin_manager.is_plugin_marked(plugin.key, "installed")
self._plugin_manager.mark_plugin(plugin.key,
@@ -521,7 +528,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._plugin_manager.reload_plugins()
result = dict(result=True, needs_restart=needs_restart, needs_refresh=needs_refresh, plugin=self._to_external_plugin(plugin))
result = dict(result=True,
needs_restart=needs_restart,
needs_refresh=needs_refresh,
needs_reconnect=needs_reconnect,
plugin=self._to_external_plugin(plugin))
self._send_result_notification("uninstall", result)
return jsonify(result)
@@ -531,11 +542,13 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin)
needs_refresh = plugin.implementation and isinstance(plugin.implementation, octoprint.plugin.ReloadNeedingPlugin)
needs_reconnect = self._plugin_manager.has_any_of_hooks(plugin, self._reconnect_hooks) and self._printer.is_operational()
pending = ((command == "disable" and plugin.key in self._pending_enable) or (command == "enable" and plugin.key in self._pending_disable))
safe_mode_victim = getattr(plugin, "safe_mode_victim", False)
needs_restart_api = (needs_restart or safe_mode_victim) and not pending
needs_refresh_api = needs_refresh and not pending
needs_reconnect_api = needs_reconnect and not pending
try:
if command == "disable":
@@ -549,11 +562,13 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
result = dict(result=True,
needs_restart=True,
needs_refresh=True,
needs_reconnect=True,
plugin=self._to_external_plugin(plugin))
else:
result = dict(result=True,
needs_restart=needs_restart_api,
needs_refresh=needs_refresh_api,
needs_reconnect=needs_reconnect_api,
plugin=self._to_external_plugin(plugin))
self._send_result_notification(command, result)
@@ -605,7 +620,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
if additional_args is not None:
inapplicable_arguments = self.__class__.pip_inapplicable_arguments.get(args[0], list())
inapplicable_arguments = self.__class__.PIP_INAPPLICABLE_ARGUMENTS.get(args[0], list())
for inapplicable_argument in inapplicable_arguments:
additional_args = re.sub("(^|\s)" + re.escape(inapplicable_argument) + "\\b", "", additional_args)
@@ -881,6 +896,22 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
octoprint_version = pkg_resources.parse_version(octoprint_version.base_version)
return octoprint_version
@property
def _reconnect_hooks(self):
reconnect_hooks = self.__class__.RECONNECT_HOOKS
reconnect_hook_provider_hooks = self._plugin_manager.get_hooks("octoprint.plugin.pluginmanager.reconnect_hooks")
for name, hook in reconnect_hook_provider_hooks.items():
try:
result = hook()
if isinstance(result, (list, tuple)):
reconnect_hooks.extend(filter(lambda x: isinstance(x, basestring), result))
except:
self._logger.exception("Error while retrieving additional hooks for which a "
"reconnect is required from plugin {name}".format(**locals()))
return reconnect_hooks
def _get_plugins(self):
plugins = self._plugin_manager.plugins
@@ -1 +1 @@
table td.settings_plugin_plugin_manager_plugins_name,table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}table td.settings_plugin_plugin_manager_plugins_actions,table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}table td.settings_plugin_plugin_manager_plugins_actions a,table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}table td.settings_plugin_plugin_manager_plugins_actions a.disabled,table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog .slimScrollDiv{margin-bottom:20px}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:300px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{overflow:hidden;width:auto;height:300px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px 10px 5px 5px}#settings_plugin_pluginmanager_workingdialog_output span{display:block}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009}
table td.settings_plugin_plugin_manager_plugins_name,table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}table td.settings_plugin_plugin_manager_plugins_actions,table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}table td.settings_plugin_plugin_manager_plugins_actions a,table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}table td.settings_plugin_plugin_manager_plugins_actions a.disabled,table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog .slimScrollDiv{margin-bottom:20px}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:300px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{overflow:hidden;width:auto;height:300px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px 10px 5px 5px}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009}
@@ -663,7 +663,7 @@ $(function() {
return self.isCompatible(data) ? (self.installed(data) ? gettext("Reinstall") : gettext("Install")) : (data.disabled ? gettext("Disabled") : gettext("Incompatible"));
};
self._displayNotification = function(response, titleSuccess, textSuccess, textRestart, textReload, titleError, textError) {
self._displayNotification = function(response, titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError) {
var notification;
var beforeClose = function(notification) {
@@ -747,6 +747,15 @@ $(function() {
},
hide: false
})
} else if (response.needs_reconnect) {
notification = new PNotify({
title: titleSuccess,
text: textReconnect,
callbacks: {
before_close: beforeClose
},
hide: false
})
} else {
notification = new PNotify({
title: titleSuccess,
@@ -1060,7 +1069,7 @@ $(function() {
});
self._scrollWorkingOutputToEnd();
} else if (messageType == "result") {
var titleSuccess, textSuccess, textRestart, textReload, titleError, textError;
var titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError;
var action = data.action;
var name = "Unknown";
@@ -1080,16 +1089,19 @@ $(function() {
textSuccess = gettext("A plugin was installed successfully, however it was impossible to detect which one. Please Restart OctoPrint to make sure everything will be registered properly");
textRestart = textSuccess;
textReload = textSuccess;
textReconnect = textSuccess;
} else if (data.was_reinstalled) {
titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" reinstalled"), {name: name});
textSuccess = gettext("The plugin was reinstalled successfully");
textRestart = gettext("The plugin was reinstalled successfully, however a restart of OctoPrint is needed for that to take effect.");
textReload = gettext("The plugin was reinstalled successfully, however a reload of the page is needed for that to take effect.");
textReconnect = gettext("The plugin was reinstalled successfully, however a reconnect to the printer is needed for that to take effect.");
} else {
titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" installed"), {name: name});
textSuccess = gettext("The plugin was installed successfully");
textRestart = gettext("The plugin was installed successfully, however a restart of OctoPrint is needed for that to take effect.");
textReload = gettext("The plugin was installed successfully, however a reload of the page is needed for that to take effect.");
textReconnect = gettext("The plugin was installed successfully, however a reconnect to the printer is needed for that to take effect.");
}
titleError = gettext("Something went wrong");
@@ -1141,6 +1153,7 @@ $(function() {
textSuccess = gettext("The plugin was uninstalled successfully");
textRestart = gettext("The plugin was uninstalled successfully, however a restart of OctoPrint is needed for that to take effect.");
textReload = gettext("The plugin was uninstalled successfully, however a reload of the page is needed for that to take effect.");
textReconnect = gettext("The plugin was uninstalled successfully, however a reconnect to the printer is needed for that to take effect.");
titleError = gettext("Something went wrong");
if (data.hasOwnProperty("reason")) {
@@ -1158,6 +1171,7 @@ $(function() {
textSuccess = gettext("The plugin was enabled successfully.");
textRestart = gettext("The plugin was enabled successfully, however a restart of OctoPrint is needed for that to take effect.");
textReload = gettext("The plugin was enabled successfully, however a reload of the page is needed for that to take effect.");
textReconnect = gettext("The plugin was enabled successfully, however a reconnect to the printer is needed for that to take effect.");
titleError = gettext("Something went wrong");
if (data.hasOwnProperty("reason")) {
@@ -1175,6 +1189,7 @@ $(function() {
textSuccess = gettext("The plugin was disabled successfully.");
textRestart = gettext("The plugin was disabled successfully, however a restart of OctoPrint is needed for that to take effect.");
textReload = gettext("The plugin was disabled successfully, however a reload of the page is needed for that to take effect.");
textReconnect = gettext("The plugin was disabled successfully, however a reconnect to the printer is needed for that to take effect.");
titleError = gettext("Something went wrong");
if (data.hasOwnProperty("reason")) {
@@ -1187,7 +1202,7 @@ $(function() {
return;
}
self._displayNotification(data, titleSuccess, textSuccess, textRestart, textReload, titleError, textError);
self._displayNotification(data, titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError);
self.requestData();
}
};
@@ -85,10 +85,6 @@ table {
}
#settings_plugin_pluginmanager_workingdialog_output {
span {
display: block;
}
.message {
font-weight: bold;
}
@@ -108,7 +108,7 @@
<h3 data-bind="text: workingTitle"></h3>
</div>
<div class="modal-body">
<pre id="settings_plugin_pluginmanager_workingdialog_output" class="terminal pre-scrollable" style="height: 170px" data-bind="foreach: loglines"><span data-bind="text: line, css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message', error: stream == 'error'}"></span></pre>
<pre id="settings_plugin_pluginmanager_workingdialog_output" class="pre-scrollable pre-output" style="height: 170px" data-bind="foreach: loglines"><span data-bind="text: line, css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message', error: stream == 'error'}"></span></pre>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" data-bind="enable: !$root.working()" aria-hidden="true">{{ _('Close') }}</button>
@@ -218,9 +218,13 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
"repo": "OctoPrint",
"update_script": "{{python}} \"{update_script}\" --branch={{branch}} --force={{force}} \"{{folder}}\" {{target}}".format(update_script=update_script),
"restart": "octoprint",
"stable_branch": dict(branch="master", name="Stable"),
"prerelease_branches": [dict(branch="rc/maintenance", name="Maintenance RCs"),
dict(branch="rc/devel", name="Devel RCs")]
"stable_branch": dict(branch="master", commitish=["master"], name="Stable"),
"prerelease_branches": [dict(branch="rc/maintenance",
commitish=["rc/maintenance"], # maintenance RCs
name="Maintenance RCs"),
dict(branch="rc/devel",
commitish=["rc/maintenance", "rc/devel"], # devel & maintenance RCs
name="Devel RCs")]
},
},
"pip_command": None,
@@ -1 +1 @@
td.settings_plugin_softwareupdate_column_update{width:16px}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output span{display:block}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:700}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:700;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}
td.settings_plugin_softwareupdate_column_update{width:16px}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:700}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:700;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}
@@ -5,10 +5,6 @@ td.settings_plugin_softwareupdate_column_update {
#settings_plugin_softwareupdate_workingdialog_output {
font-size: 0.8em;
span {
display: block;
}
.message {
font-weight: bold;
}
@@ -108,7 +108,7 @@
<h3 data-bind="text: workingTitle"></h3>
</div>
<div class="modal-body">
<pre id="settings_plugin_softwareupdate_workingdialog_output" class="terminal pre-scrollable" style="height: 170px" data-bind="foreach: loglines"><span data-bind="text: line, css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message'}"></span></pre>
<pre id="settings_plugin_softwareupdate_workingdialog_output" class="pre-scrollable pre-output" style="height: 170px" data-bind="foreach: loglines"><span data-bind="text: line, css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message'}"></span></pre>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" data-bind="enable: !$root.working()" aria-hidden="true">{{ _('Close') }}</button>
@@ -15,7 +15,7 @@ logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.gith
def _filter_out_latest(releases,
sort_key=None,
include_prerelease=False,
prerelease_channel=None):
commitish=None):
"""
Filters out the newest of all matching releases.
@@ -26,31 +26,43 @@ def _filter_out_latest(releases,
>>> release_1_2_16rc2 = dict(name="1.2.16rc2", tag_name="1.2.16rc2", html_url="some_url", published_at="2016-08-30T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/maintenance")
>>> release_1_2_17rc1 = dict(name="1.2.17rc1", tag_name="1.2.17rc1", html_url="some_url", published_at="2016-08-31T12:00:00Z", prerelease=True, draft=True, target_commitish="rc/maintenance")
>>> release_1_3_0rc1 = dict(name="1.3.0rc1", tag_name="1.3.0rc1", html_url="some_url", published_at="2016-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/devel")
>>> release_1_3_5rc1 = dict(name="1.3.5rc1", tag_name="1.3.5rc1", html_url="some_url", published_at="2017-06-14T10:00:00Z", prerelease=True, draft=False, target_commitish="rc/maintenance")
>>> release_1_2_18 = dict(name="1.2.18", tag_name="1.2.18", html_url="some_url", published_at="2016-12-13T12:00:00Z", prerelease=False, draft=False, target_commitish="master")
>>> release_1_4_0rc1 = dict(name="1.4.0rc1", tag_name="1.4.0rc1", html_url="some_url", published_at="2017-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/future")
>>> release_1_4_0rc1_devel = dict(name="1.4.0rc1", tag_name="1.4.0rc1", html_url="some_url", published_at="2017-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/devel")
>>> releases = [release_1_2_15, release_1_2_16rc1, release_1_2_16rc2, release_1_2_17rc1, release_1_3_0rc1, release_1_4_0rc1]
>>> _filter_out_latest(releases, include_prerelease=False, prerelease_channel=None)
>>> _filter_out_latest(releases, include_prerelease=False, commitish=None)
('1.2.15', '1.2.15', 'some_url')
>>> _filter_out_latest(releases, include_prerelease=True, prerelease_channel="rc/maintenance")
>>> _filter_out_latest(releases, include_prerelease=True, commitish=["rc/maintenance"])
('1.2.16rc2', '1.2.16rc2', 'some_url')
>>> _filter_out_latest(releases, include_prerelease=True, prerelease_channel="rc/devel")
>>> _filter_out_latest(releases, include_prerelease=True, commitish=["rc/devel"])
('1.3.0rc1', '1.3.0rc1', 'some_url')
>>> _filter_out_latest(releases, include_prerelease=True, prerelease_channel=None)
>>> _filter_out_latest(releases, include_prerelease=True, commitish=None)
('1.4.0rc1', '1.4.0rc1', 'some_url')
>>> _filter_out_latest(releases, include_prerelease=True, prerelease_channel="rc/doesntexist")
>>> _filter_out_latest(releases, include_prerelease=True, commitish=["rc/doesntexist"])
('1.2.15', '1.2.15', 'some_url')
>>> _filter_out_latest([release_1_2_17rc1])
(None, None, None)
>>> _filter_out_latest([release_1_2_16rc1, release_1_2_16rc2])
(None, None, None)
>>> comparable_factory = _get_comparable_factory("python", force_base=True)
>>> sort_key = lambda release: comparable_factory(_get_sanitized_version(release["tag_name"]))
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=False, prerelease_channel=None, sort_key=sort_key)
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=False, commitish=None, sort_key=sort_key)
('1.2.18', '1.2.18', 'some_url')
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=True, prerelease_channel="rc/maintenance", sort_key=sort_key)
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=True, commitish=["rc/maintenance"], sort_key=sort_key)
('1.2.18', '1.2.18', 'some_url')
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=True, prerelease_channel="rc/devel", sort_key=sort_key)
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=True, commitish=["rc/devel"], sort_key=sort_key)
('1.3.0rc1', '1.3.0rc1', 'some_url')
>>> _filter_out_latest([release_1_2_18, release_1_3_5rc1], include_prerelease=True, commitish=["rc/maintenance"])
('1.3.5rc1', '1.3.5rc1', 'some_url')
>>> _filter_out_latest([release_1_2_18, release_1_3_5rc1], include_prerelease=True, commitish=["rc/maintenance", "rc/devel"])
('1.3.5rc1', '1.3.5rc1', 'some_url')
>>> _filter_out_latest([release_1_2_18, release_1_3_5rc1, release_1_4_0rc1_devel], include_prerelease=True, commitish=["rc/maintenance"])
('1.3.5rc1', '1.3.5rc1', 'some_url')
>>> _filter_out_latest([release_1_2_18, release_1_3_5rc1, release_1_4_0rc1_devel], include_prerelease=True, commitish=["rc/maintenance", "rc/devel"])
('1.4.0rc1', '1.4.0rc1', 'some_url')
"""
nothing = None, None, None
@@ -61,9 +73,9 @@ def _filter_out_latest(releases,
# filter out prereleases and drafts
filter_function = lambda rel: not rel["prerelease"] and not rel["draft"]
if include_prerelease:
if prerelease_channel:
filter_function = lambda rel: not rel["draft"] and (
not rel["prerelease"] or rel["target_commitish"] == prerelease_channel)
if commitish:
filter_function = lambda rel: not rel["draft"] and \
(not rel["prerelease"] or rel["target_commitish"] in commitish)
else:
filter_function = lambda rel: not rel["draft"]
@@ -82,7 +94,7 @@ def _filter_out_latest(releases,
def _get_latest_release(user, repo, compare_type,
include_prerelease=False,
prerelease_channel=None,
commitish=None,
force_base=True):
nothing = None, None, None
r = requests.get(RELEASE_URL.format(user=user, repo=repo), timeout=30)
@@ -107,7 +119,7 @@ def _get_latest_release(user, repo, compare_type,
return _filter_out_latest(releases,
sort_key=sort_key,
include_prerelease=include_prerelease,
prerelease_channel=prerelease_channel)
commitish=commitish)
def _get_sanitized_version(version_string):
@@ -257,6 +269,16 @@ def get_latest(target, check, custom_compare=None):
include_prerelease = check.get("prerelease", False)
prerelease_channel = check.get("prerelease_channel", None)
# determine valid "commitish" values in case we track prereleases
commitish = None
if prerelease_channel:
prerelease_branches = check.get("prerelease_branches", None)
if prerelease_branches:
# fetch valid commitish list from configured prerelease_branches for selected channel
commitishes = dict((x["branch"], x.get("commitish", [x["branch"]])) for x in prerelease_branches)
commitish = commitishes.get(prerelease_channel, [prerelease_channel])
force_base = check.get("force_base", True)
compare_type = _get_sanitized_compare_type(check.get("release_compare", "python"),
custom=custom_compare)
@@ -265,7 +287,7 @@ def get_latest(target, check, custom_compare=None):
check["repo"],
compare_type,
include_prerelease=include_prerelease,
prerelease_channel=prerelease_channel,
commitish=commitish,
force_base=force_base)
information =dict(
+1 -1
View File
@@ -199,7 +199,7 @@ class PrinterInterface(object):
def set_temperature_offset(self, offsets=None):
"""
Sets the temperature ``offsets`` to apply to target temperatures red from a GCODE file while printing.
Sets the temperature ``offsets`` to apply to target temperatures read from a GCODE file while printing.
Arguments:
offsets (dict): A dictionary specifying the offsets to apply. Keys must match the format for the ``heater``
+7 -3
View File
@@ -209,7 +209,7 @@ class Server(object):
try:
clazz = octoprint.util.get_class(userManagerName)
userManager = clazz()
except AttributeError as e:
except:
self._logger.exception("Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(userManagerName))
userManager = octoprint.users.FilebasedUserManager()
finally:
@@ -344,7 +344,7 @@ class Server(object):
if not userManager.enabled:
loginManager.anonymous_user = users.DummyUser
principals.identity_loaders.appendleft(users.dummy_identity_loader)
loginManager.init_app(app)
loginManager.init_app(app, add_context_processor=False)
# register API blueprint
self._setup_blueprints()
@@ -359,7 +359,8 @@ class Server(object):
ioloop = IOLoop()
ioloop.install()
self._router = SockJSRouter(self._create_socket_connection, "/sockjs")
self._router = SockJSRouter(self._create_socket_connection, "/sockjs",
session_kls=util.sockjs.ThreadSafeSession)
upload_suffixes = dict(name=self._settings.get(["server", "uploads", "nameSuffix"]), path=self._settings.get(["server", "uploads", "pathSuffix"]))
@@ -1066,6 +1067,9 @@ class Server(object):
"js/lib/jquery/jquery.ui.widget.js",
"js/lib/jquery/jquery.ui.mouse.js",
"js/lib/jquery/jquery.flot.js",
"js/lib/jquery/jquery.flot.time.js",
"js/lib/jquery/jquery.flot.crosshair.js",
"js/lib/jquery/jquery.flot.resize.js",
"js/lib/jquery/jquery.iframe-transport.js",
"js/lib/jquery/jquery.fileupload.js",
"js/lib/jquery/jquery.slimscroll.min.js",
+1 -1
View File
@@ -210,7 +210,7 @@ def login():
if octoprint.server.userManager.checkPassword(username, password):
if octoprint.server.userManager.enabled:
user = octoprint.server.userManager.login_user(user)
session["usersession.id"] = user.get_session()
session["usersession.id"] = user.session
g.user = user
login_user(user, remember=remember)
identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id()))
+7 -1
View File
@@ -168,7 +168,9 @@ def getSettings():
},
"temperature": {
"profiles": s.get(["temperature", "profiles"]),
"cutoff": s.getInt(["temperature", "cutoff"])
"cutoff": s.getInt(["temperature", "cutoff"]),
"sendAutomatically": s.getBoolean(["temperature", "sendAutomatically"]),
"sendAutomaticallyAfter": s.getInt(["temperature", "sendAutomaticallyAfter"], min=0, max=30),
},
"system": {
"actions": s.get(["system", "actions"]),
@@ -184,6 +186,8 @@ def getSettings():
"afterPrintDone": None,
"beforePrintPaused": None,
"afterPrintResumed": None,
"beforeToolChange": None,
"afterToolChange": None,
"snippets": dict()
}
},
@@ -389,6 +393,8 @@ def _saveSettings(data):
if "temperature" in data.keys():
if "profiles" in data["temperature"]: s.set(["temperature", "profiles"], data["temperature"]["profiles"])
if "cutoff" in data["temperature"]: s.setInt(["temperature", "cutoff"], data["temperature"]["cutoff"])
if "sendAutomatically" in data["temperature"]: s.setBoolean(["temperature", "sendAutomatically"], data["temperature"]["sendAutomatically"])
if "sendAutomaticallyAfter" in data["temperature"]: s.setInt(["temperature", "sendAutomaticallyAfter"], data["temperature"]["sendAutomaticallyAfter"], min=0, max=30)
if "terminalFilters" in data.keys():
s.set(["terminalFilters"], data["terminalFilters"])
+7 -1
View File
@@ -7,6 +7,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import os
import threading
import logging
from flask import request, jsonify, url_for, make_response
from werkzeug.utils import secure_filename
@@ -128,7 +129,12 @@ def deleteTimelapse(filename):
timelapse_folder = settings().getBaseFolder("timelapse")
full_path = os.path.realpath(os.path.join(timelapse_folder, filename))
if full_path.startswith(timelapse_folder) and os.path.exists(full_path):
os.remove(full_path)
try:
os.remove(full_path)
except Exception as ex:
logging.getLogger(__file__).exception("Error deleting timelapse file {}".format(full_path))
return make_response("Unexpected error: {}".format(ex), 500)
return getTimelapseData()
+3 -3
View File
@@ -507,8 +507,8 @@ def passive_login():
if user is not None and not user.is_anonymous:
flask_principal.identity_changed.send(flask.current_app._get_current_object(), identity=flask_principal.Identity(user.get_id()))
if hasattr(user, "get_session"):
flask.session["usersession.id"] = user.get_session()
if hasattr(user, "session"):
flask.session["usersession.id"] = user.session
flask.g.user = user
return flask.jsonify(user.asDict())
elif settings().getBoolean(["accessControl", "autologinLocal"]) \
@@ -526,7 +526,7 @@ def passive_login():
user = octoprint.server.userManager.findUser(autologinAs)
if user is not None:
user = octoprint.server.userManager.login_user(user)
flask.session["usersession.id"] = user.get_session()
flask.session["usersession.id"] = user.session
flask.g.user = user
flask_login.login_user(user)
flask_principal.identity_changed.send(flask.current_app._get_current_object(), identity=flask_principal.Identity(user.get_id()))
+36 -10
View File
@@ -8,6 +8,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import logging
import threading
import sockjs.tornado
import sockjs.tornado.session
import time
import octoprint.timelapse
@@ -21,6 +22,34 @@ from octoprint.settings import settings
import octoprint.printer
class ThreadSafeSession(sockjs.tornado.session.Session):
def __init__(self, conn, server, session_id, expiry=None):
sockjs.tornado.session.Session.__init__(self, conn, server, session_id, expiry=expiry)
def set_handler(self, handler, start_heartbeat=True):
if getattr(handler, "__orig_send_pack", None) is None:
orig_send_pack = handler.send_pack
mutex = threading.RLock()
def send_pack(*args, **kwargs):
with mutex:
return orig_send_pack(*args, **kwargs)
handler.send_pack = send_pack
setattr(handler, "__orig_send_pack", orig_send_pack)
return sockjs.tornado.session.Session.set_handler(self, handler, start_heartbeat=start_heartbeat)
def remove_handler(self, handler):
result = sockjs.tornado.session.Session.remove_handler(self, handler)
if getattr(handler, "__orig_send_pack", None) is not None:
handler.send_pack = getattr(handler, "__orig_send_pack")
delattr(handler, "__orig_send_pack")
return result
class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.PrinterCallback):
def __init__(self, printer, fileManager, analysisQueue, userManager, eventManager, pluginManager, session):
sockjs.tornado.SockJSConnection.__init__(self, session)
@@ -47,8 +76,6 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.
self._lastCurrent = 0
self._baseRateLimit = 0.5
self._emit_mutex = threading.RLock()
def _getRemoteAddress(self, info):
forwardedFor = info.headers.get("X-Forwarded-For")
if forwardedFor is not None:
@@ -205,11 +232,10 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.
self.sendEvent(event, payload)
def _emit(self, type, payload):
with self._emit_mutex:
try:
self.send({type: payload})
except Exception as e:
if self._logger.isEnabledFor(logging.DEBUG):
self._logger.exception("Could not send message to client {}".format(self._remoteAddress))
else:
self._logger.warn("Could not send message to client {}: {}".format(self._remoteAddress, e))
try:
self.send({type: payload})
except Exception as e:
if self._logger.isEnabledFor(logging.DEBUG):
self._logger.exception("Could not send message to client {}".format(self._remoteAddress))
else:
self._logger.warn("Could not send message to client {}: {}".format(self._remoteAddress, e))
+41 -3
View File
@@ -231,7 +231,9 @@ default_settings = {
{"name": "ABS", "extruder" : 210, "bed" : 100 },
{"name": "PLA", "extruder" : 180, "bed" : 60 }
],
"cutoff": 30
"cutoff": 30,
"sendAutomatically": False,
"sendAutomaticallyAfter": 1,
},
"printerProfiles": {
"default": None
@@ -1275,23 +1277,43 @@ class Settings(object):
return None
def getInt(self, path, **kwargs):
minimum = kwargs.pop("min", None)
maximum = kwargs.pop("max", None)
value = self.get(path, **kwargs)
if value is None:
return None
try:
return int(value)
intValue = int(value)
if minimum is not None and intValue < minimum:
return minimum
elif maximum is not None and intValue > maximum:
return maximum
else:
return intValue
except ValueError:
self._logger.warn("Could not convert %r to a valid integer when getting option %r" % (value, path))
return None
def getFloat(self, path, **kwargs):
minimum = kwargs.pop("min", None)
maximum = kwargs.pop("max", None)
value = self.get(path, **kwargs)
if value is None:
return None
try:
return float(value)
floatValue = float(value)
if minimum is not None and floatValue < minimum:
return minimum
elif maximum is not None and floatValue > maximum:
return maximum
else:
return floatValue
except ValueError:
self._logger.warn("Could not convert %r to a valid integer when getting option %r" % (value, path))
return None
@@ -1447,8 +1469,16 @@ class Settings(object):
self.set(path, None, **kwargs)
return
minimum = kwargs.pop("min", None)
maximum = kwargs.pop("max", None)
try:
intValue = int(value)
if minimum is not None and intValue < minimum:
intValue = minimum
if maximum is not None and intValue > maximum:
intValue = maximum
except ValueError:
self._logger.warn("Could not convert %r to a valid integer when setting option %r" % (value, path))
return
@@ -1460,8 +1490,16 @@ class Settings(object):
self.set(path, None, **kwargs)
return
minimum = kwargs.pop("min", None)
maximum = kwargs.pop("max", None)
try:
floatValue = float(value)
if minimum is not None and floatValue < minimum:
floatValue = minimum
if maximum is not None and floatValue > maximum:
floatValue = maximum
except ValueError:
self._logger.warn("Could not convert %r to a valid integer when setting option %r" % (value, path))
return
+1 -1
View File
@@ -1 +1 @@
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
+35 -28
View File
@@ -301,10 +301,16 @@ var doParse = function () {
var tool = 0;
var prev_extrude = [{a: 0, b: 0, c: 0, e: 0, abs: 0}];
var prev_retract = [0];
var offset = toolOffsets[0];
// we keep track of our active toolOffset here so that our visualization lines up - if we didn't
// offset the coordinates from the GCODE file with the tool offset, stuff would look wonky since our
// visualizer doesn't actually have a physical offset ;)
var activeToolOffset = toolOffsets[0];
var i, j, args;
model = [];
for (var i = 0; i < gcode.length; i++) {
for (i = 0; i < gcode.length; i++) {
x = undefined;
y = undefined;
z = undefined;
@@ -325,24 +331,24 @@ var doParse = function () {
var log = false;
if (/^(?:G0|G1|G2|G3)\s/i.test(line)) {
var args = line.split(/\s/);
args = line.split(/\s/);
for (var j = 0; j < args.length; j++) {
for (j = 0; j < args.length; j++) {
switch (argChar = args[j].charAt(0).toLowerCase()) {
case 'x':
if (relativeMode) {
x = prevX + Number(args[j].slice(1)) + offset.x;
x = prevX + Number(args[j].slice(1)) + activeToolOffset.x;
} else {
x = Number(args[j].slice(1)) + offset.x;
x = Number(args[j].slice(1)) + activeToolOffset.x;
}
break;
case 'y':
if (relativeMode) {
y = prevY + Number(args[j].slice(1)) + offset.y;
y = prevY + Number(args[j].slice(1)) + activeToolOffset.y;
} else {
y = Number(args[j].slice(1)) + offset.y;
y = Number(args[j].slice(1)) + activeToolOffset.y;
}
break;
@@ -376,7 +382,7 @@ var doParse = function () {
if (prev_extrude[tool]["abs"] < 0) {
prev_retract[tool] = -1;
retract = -1;
} else if (prev_extrude[tool]["abs"] == 0) {
} else if (prev_extrude[tool]["abs"] === 0) {
retract = 0;
} else if (prev_extrude[tool]["abs"] > 0 && prev_retract[tool] < 0) {
prev_retract[tool] = 0;
@@ -398,9 +404,9 @@ var doParse = function () {
center_j = Number(args[j].slice(1));
break;
case 'g':
if(args[j].charAt(1).toLowerCase()=='2')
if(args[j].charAt(1).toLowerCase() === '2')
direction=1;
if(args[j].charAt(1).toLowerCase()=='3')
if(args[j].charAt(1).toLowerCase() === '3')
direction=-1;
break;
}
@@ -411,7 +417,7 @@ var doParse = function () {
prev_extrude[tool]["abs"] = Math.sqrt((prevX - x) * (prevX - x) + (prevY - y) * (prevY - y));
}
if (typeof(x) !== 'undefined' || typeof(y) !== 'undefined' || typeof(z) !== 'undefined' || retract != 0) {
if (typeof(x) !== 'undefined' || typeof(y) !== 'undefined' || typeof(z) !== 'undefined' || retract !== 0) {
addToModel = true;
move = true;
}
@@ -434,12 +440,12 @@ var doParse = function () {
} else if (/^(?:M103)/i.test(line)) {
dcExtrude = false;
} else if (/^(?:G92)/i.test(line)) {
var args = line.split(/\s/);
args = line.split(/\s/);
for (var j = 0; j < args.length; j++) {
for (j = 0; j < args.length; j++) {
if (!args[j]) continue;
if (args.length == 1) {
if (args.length === 1) {
// G92 without coordinates => reset all axes to 0
x = 0;
y = 0;
@@ -451,11 +457,11 @@ var doParse = function () {
} else {
switch (argChar = args[j].charAt(0).toLowerCase()) {
case 'x':
x = Number(args[j].slice(1)) + offset.x;
x = Number(args[j].slice(1)) + activeToolOffset.x;
break;
case 'y':
y = Number(args[j].slice(1)) + offset.y;
y = Number(args[j].slice(1)) + activeToolOffset.y;
break;
case 'z':
@@ -484,9 +490,9 @@ var doParse = function () {
}
} else if (/^(?:G28)/i.test(line)) {
var args = line.split(/\s/);
args = line.split(/\s/);
if (args.length == 1) {
if (args.length === 1) {
// G28 with no arguments => home all axis
x = 0;
y = 0;
@@ -510,11 +516,11 @@ var doParse = function () {
}
// if it's the first layer and G28 was without z
if (layer == 0 && typeof(z) === 'undefined') {
if (layer === 0 && typeof(z) === 'undefined') {
z = 0;
}
if (typeof(x) !== 'undefined' || typeof(y) !== 'undefined' || typeof(z) !== 'undefined' || retract != 0) {
if (typeof(x) !== 'undefined' || typeof(y) !== 'undefined' || typeof(z) !== 'undefined' || retract !== 0) {
addToModel = true;
move = true;
}
@@ -523,13 +529,13 @@ var doParse = function () {
if (!prev_extrude[tool]) prev_extrude[tool] = {a: 0, b: 0, c: 0, e: 0, abs: 0};
if (!prev_retract[tool]) prev_retract[tool] = 0;
offset = toolOffsets[tool];
if (!offset) offset = {x: 0, y: 0};
activeToolOffset = toolOffsets[tool];
if (!activeToolOffset) activeToolOffset = {x: 0, y: 0};
}
// If move is on a new height and it's not extruding and
// it's not currently already in a Z-lift, assume it's possibly a Z-lift
if (typeof(z) !== 'undefined' && z != prevZ && !extrude && !zLift) {
if (typeof(z) !== 'undefined' && z !== prevZ && !extrude && !zLift) {
zLift = true;
zLiftZ = prevZ;
}
@@ -538,7 +544,7 @@ var doParse = function () {
zLift = false;
}
if (typeof(z) !== 'undefined' && z != prevZ) {
if (typeof(z) !== 'undefined' && z !== prevZ) {
if (z_heights[z]) {
layer = z_heights[z];
} else {
@@ -549,7 +555,7 @@ var doParse = function () {
sendLayer = layer;
sendLayerZ = z;
prevZ = z;
} else if (typeof(z) == 'undefined' && typeof(prevZ) != 'undefined') {
} else if (typeof(z) === 'undefined' && typeof(prevZ) !== 'undefined') {
if (z_heights.hasOwnProperty(prevZ)) {
layer = z_heights[prevZ];
} else {
@@ -609,7 +615,7 @@ var doParse = function () {
}
if (typeof(sendLayer) !== "undefined") {
if (i - lastSend > gcode.length * 0.02 && sendMultiLayer.length != 0) {
if (i - lastSend > gcode.length * 0.02 && sendMultiLayer.length !== 0) {
lastSend = i;
sendMultiLayerToParent(sendMultiLayer, sendMultiLayerZ, i / gcode.length * 100);
sendMultiLayer = [];
@@ -629,7 +635,7 @@ var parseGCode = function (message) {
gcode = message.gcode;
firstReport = message.options.firstReport;
toolOffsets = message.options.toolOffsets;
if (!toolOffsets || toolOffsets.length == 0) toolOffsets = [{x: 0, y: 0}];
if (!toolOffsets || toolOffsets.length === 0) toolOffsets = [{x: 0, y: 0}];
bed = message.options.bed;
ignoreOutsideBed = message.options.ignoreOutsideBed;
g90InfluencesExtruder = message.options.g90InfluencesExtruder;
@@ -666,6 +672,7 @@ var runAnalyze = function (message) {
var setOption = function (options) {
for (var opt in options) {
if (!options.hasOwnProperty(opt)) continue;
gCodeOptions[opt] = options[opt];
}
};
@@ -106,6 +106,7 @@
var onOpen = function() {
self.reconnecting = false;
self.reconnectTrial = 0;
self.onConnected();
};
var onClose = function(e) {
@@ -117,6 +118,8 @@
return;
}
self.onDisconnected(e.code);
if (self.reconnectTrial < self.options.timeouts.length) {
var timeout = self.options.timeouts[self.reconnectTrial];
setTimeout(function() { self.reconnect() }, timeout * 1000);
@@ -160,6 +163,8 @@
OctoPrintSocketClient.prototype.onReconnectAttempt = function(trial) {};
OctoPrintSocketClient.prototype.onReconnectFailed = function() {};
OctoPrintSocketClient.prototype.onConnected = function() {};
OctoPrintSocketClient.prototype.onDisconnected = function(code) {};
OctoPrintSocketClient.prototype.onRateTooLow = function(measured, minimum) {
this.increaseRate();
+150 -99
View File
@@ -1,13 +1,17 @@
function DataUpdater(allViewModels) {
function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
var self = this;
self.allViewModels = allViewModels;
self.connectCallback = connectCallback;
self.disconnectCallback = disconnectCallback;
self._pluginHash = undefined;
self._configHash = undefined;
self._connectedDeferred = undefined;
self._initializedDeferred = undefined;
self._throttleFactor = 1;
self._baseProcessingLimit = 500.0;
self._lastProcessingTimes = [];
@@ -57,6 +61,13 @@ function DataUpdater(allViewModels) {
return self._connectedDeferred.promise();
};
self.initialized = function() {
if (self._initializedDeferred) {
self._initializedDeferred.resolve();
self._initializedDeferred = undefined;
}
};
self._onReconnectAttempt = function(trial) {
if (trial <= 0) {
// Only consider it a real disconnect if the trial number has exceeded our threshold.
@@ -99,7 +110,27 @@ function DataUpdater(allViewModels) {
$("#offline_overlay_message").html(gettext("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."));
};
self._onConnected = function(event) {
self._onDisconnected = function(code) {
if (self._initializedDeferred) {
self._initializedDeferred.reject();
}
self._initializedDeferred = undefined;
if (self.disconnectCallback) {
self.disconnectCallback();
}
};
self._onConnectMessage = function(event) {
if (self._initializedDeferred) {
self._initializedDeferred.reject();
}
self._initializedDeferred = $.Deferred();
if (self.connectCallback) {
self.connectCallback();
}
var data = event.data;
// update version information
@@ -117,37 +148,40 @@ function DataUpdater(allViewModels) {
var oldConfigHash = self._configHash;
self._configHash = data["config_hash"];
// process safe mode
if (self._safeModePopup) self._safeModePopup.remove();
if (data["safe_mode"]) {
// safe mode is active, let's inform the user
log.info("Safe mode is active. Third party plugins are disabled and cannot be enabled.");
self._ifInitialized(function() {
// process safe mode
if (self._safeModePopup) self._safeModePopup.remove();
if (data["safe_mode"]) {
// safe mode is active, let's inform the user
log.info("Safe mode is active. Third party plugins are disabled and cannot be enabled.");
self._safeModePopup = new PNotify({
title: gettext("Safe mode is active"),
text: gettext("The server is currently running in safe mode. Third party plugins are disabled and cannot be enabled."),
hide: false
});
}
self._safeModePopup = new PNotify({
title: gettext("Safe mode is active"),
text: gettext("The server is currently running in safe mode. Third party plugins are disabled and cannot be enabled."),
hide: false
});
}
// if the offline overlay is still showing, now's a good time to
// hide it, plus reload the camera feed if it's currently displayed
if ($("#offline_overlay").is(":visible")) {
hideOfflineOverlay();
callViewModels(self.allViewModels, "onServerReconnect");
callViewModels(self.allViewModels, "onDataUpdaterReconnect");
} else {
callViewModels(self.allViewModels, "onServerConnect");
}
// if the offline overlay is still showing, now's a good time to
// hide it, plus reload the camera feed if it's currently displayed
if ($("#offline_overlay").is(":visible")) {
hideOfflineOverlay();
callViewModels(self.allViewModels, "onServerReconnect");
callViewModels(self.allViewModels, "onDataUpdaterReconnect");
} else {
callViewModels(self.allViewModels, "onServerConnect");
}
// if the version, the plugin hash or the config hash changed, we
// want the user to reload the UI since it might be stale now
var versionChanged = oldVersion != VERSION;
var pluginsChanged = oldPluginHash != undefined && oldPluginHash != self._pluginHash;
var configChanged = oldConfigHash != undefined && oldConfigHash != self._configHash;
if (versionChanged || pluginsChanged || configChanged) {
showReloadOverlay();
}
// if the version, the plugin hash or the config hash changed, we
// want the user to reload the UI since it might be stale now
var versionChanged = oldVersion !== VERSION;
var pluginsChanged = oldPluginHash !== undefined && oldPluginHash !== self._pluginHash;
var configChanged = oldConfigHash !== undefined && oldConfigHash !== self._configHash;
if (versionChanged || pluginsChanged || configChanged) {
showReloadOverlay();
}
});
log.info("Connected to the server");
@@ -159,81 +193,89 @@ function DataUpdater(allViewModels) {
};
self._onHistoryData = function(event) {
callViewModels(self.allViewModels, "fromHistoryData", [event.data]);
};
self._onCurrentData = function(event) {
callViewModels(self.allViewModels, "fromCurrentData", [event.data]);
};
self._onSlicingProgress = function(event) {
$("#gcode_upload_progress").find(".bar").text(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: Math.round(event.data["progress"])}));
var data = event.data;
callViewModels(self.allViewModels, "onSlicingProgress", [
data["slicer"],
data["model_path"],
data["machinecode_path"],
data["progress"]
]);
};
self._onEvent = function(event) {
var gcodeUploadProgress = $("#gcode_upload_progress");
var gcodeUploadProgressBar = $(".bar", gcodeUploadProgress);
var type = event.data["type"];
var payload = event.data["payload"];
var html = "";
log.debug("Got event " + type + " with payload: " + JSON.stringify(payload));
if (type == "PrintCancelled") {
if (payload.firmwareError) {
new PNotify({
title: gettext("Unhandled communication error"),
text: _.sprintf(gettext("There was an unhandled error while talking to the printer. Due to that the ongoing print job was cancelled. Error: %(firmwareError)s"), payload),
type: "error",
hide: false
});
}
} else if (type == "Error") {
if (payload.error && payload.error.indexOf("autodetect") == -1) { // ignore "failed to autodetect"
new PNotify({
title: gettext("Unhandled communication error"),
text: _.sprintf(gettext("The was an unhandled error while talking to the printer. Due to that OctoPrint disconnected. Error: %(error)s"), payload),
type: "error",
hide: false
});
}
}
var legacyEventHandlers = {
"UpdatedFiles": "onUpdatedFiles",
"MetadataStatisticsUpdated": "onMetadataStatisticsUpdated",
"MetadataAnalysisFinished": "onMetadataAnalysisFinished",
"SlicingDone": "onSlicingDone",
"SlicingCancelled": "onSlicingCancelled",
"SlicingFailed": "onSlicingFailed"
};
_.each(self.allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty("onEvent" + type)) {
viewModel["onEvent" + type](payload);
} else if (legacyEventHandlers.hasOwnProperty(type) && viewModel.hasOwnProperty(legacyEventHandlers[type])) {
// there might still be code that uses the old callbacks, make sure those still get called
// but log a warning
log.warn("View model " + viewModel.name + " is using legacy event handler " + legacyEventHandlers[type] + ", new handler is called " + legacyEventHandlers[type]);
viewModel[legacyEventHandlers[type]](payload);
}
self._ifInitialized(function() {
callViewModels(self.allViewModels, "fromHistoryData", [event.data]);
});
};
self._onCurrentData = function(event) {
self._ifInitialized(function() {
callViewModels(self.allViewModels, "fromCurrentData", [event.data]);
});
};
self._onSlicingProgress = function(event) {
self._ifInitialized(function() {
$("#gcode_upload_progress").find(".bar").text(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: Math.round(event.data["progress"])}));
var data = event.data;
callViewModels(self.allViewModels, "onSlicingProgress", [
data["slicer"],
data["model_path"],
data["machinecode_path"],
data["progress"]
]);
});
};
self._onEvent = function(event) {
self._ifInitialized(function() {
var type = event.data["type"];
var payload = event.data["payload"];
log.debug("Got event " + type + " with payload: " + JSON.stringify(payload));
if (type == "PrintCancelled") {
if (payload.firmwareError) {
new PNotify({
title: gettext("Unhandled communication error"),
text: _.sprintf(gettext("There was an unhandled error while talking to the printer. Due to that the ongoing print job was cancelled. Error: %(firmwareError)s"), payload),
type: "error",
hide: false
});
}
} else if (type == "Error") {
if (payload.error && payload.error.indexOf("autodetect") == -1) { // ignore "failed to autodetect"
new PNotify({
title: gettext("Unhandled communication error"),
text: _.sprintf(gettext("The was an unhandled error while talking to the printer. Due to that OctoPrint disconnected. Error: %(error)s"), payload),
type: "error",
hide: false
});
}
}
var legacyEventHandlers = {
"UpdatedFiles": "onUpdatedFiles",
"MetadataStatisticsUpdated": "onMetadataStatisticsUpdated",
"MetadataAnalysisFinished": "onMetadataAnalysisFinished",
"SlicingDone": "onSlicingDone",
"SlicingCancelled": "onSlicingCancelled",
"SlicingFailed": "onSlicingFailed"
};
_.each(self.allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty("onEvent" + type)) {
viewModel["onEvent" + type](payload);
} else if (legacyEventHandlers.hasOwnProperty(type) && viewModel.hasOwnProperty(legacyEventHandlers[type])) {
// there might still be code that uses the old callbacks, make sure those still get called
// but log a warning
log.warn("View model " + viewModel.name + " is using legacy event handler " + legacyEventHandlers[type] + ", new handler is called " + legacyEventHandlers[type]);
viewModel[legacyEventHandlers[type]](payload);
}
});
})
};
self._onTimelapse = function(event) {
callViewModels(self.allViewModels, "fromTimelapseData", [event.data]);
self._ifInitialized(function() {
callViewModels(self.allViewModels, "fromTimelapseData", [event.data]);
})
};
self._onPluginMessage = function(event) {
callViewModels(self.allViewModels, "onDataUpdaterPluginMessage", [event.data.plugin, event.data.data]);
self._ifInitialized(function() {
callViewModels(self.allViewModels, "onDataUpdaterPluginMessage", [event.data.plugin, event.data.data]);
})
};
self._onIncreaseRate = function(measurement, minimum) {
@@ -246,12 +288,21 @@ function DataUpdater(allViewModels) {
OctoPrint.socket.decreaseRate();
};
self._ifInitialized = function(callback) {
if (self._initializedDeferred) {
self._initializedDeferred.done(callback);
} else {
callback();
}
};
OctoPrint.socket.onDisconnected = self._onDisconnected;
OctoPrint.socket.onReconnectAttempt = self._onReconnectAttempt;
OctoPrint.socket.onReconnectFailed = self._onReconnectFailed;
OctoPrint.socket.onRateTooHigh = self._onDecreaseRate;
OctoPrint.socket.onRateTooLow = self._onIncreaseRate;
OctoPrint.socket
.onMessage("connected", self._onConnected)
.onMessage("connected", self._onConnectMessage)
.onMessage("history", self._onHistoryData)
.onMessage("current", self._onCurrentData)
.onMessage("slicingProgress", self._onSlicingProgress)
+46 -11
View File
@@ -524,12 +524,14 @@ function formatFilament(filament) {
}
function cleanTemperature(temp) {
if (!temp || temp < 10) return gettext("off");
if (temp === undefined || !_.isNumber(temp)) return "-";
if (temp < 10) return gettext("off");
return temp;
}
function formatTemperature(temp, showF) {
if (!temp || temp < 10) return gettext("off");
if (temp === undefined || !_.isNumber(temp)) return "-";
if (temp < 10) return gettext("off");
if (showF) {
return _.sprintf("%.1f&deg;C (%.1f&deg;F)", temp, temp * 9 / 5 + 32);
} else {
@@ -688,9 +690,14 @@ function showConfirmationDialog(msg, onacknowledge, options) {
* Will listen to the supplied promise, update the progress on .progress events and
* enabling the close button and (optionally) closing the dialog on promise resolve.
*
* The calling code should call "notify" on the deferred backing the promise and supply
* two parameters: the text to display on the progress bar and the optional output field and
* a boolean value indicating whether the operation behind that update was successful or not.
* The calling code should call "notify" on the deferred backing the promise and supply:
*
* * the text to display on the progress bar and the optional output field and
* a boolean value indicating whether the operation behind that update was successful or not
* * a short text to display on the progress bar, a long text to display on the optional output
* field and a boolean value indicating whether the operation behind that update was
* successful or not
*
* Non-successful progress updates will remove the barClassSuccess class from the progress bar and
* apply the barClassFailure class and also apply the outputClassFailure to the produced line
* in the output.
@@ -770,7 +777,7 @@ function showProgressModal(options, promise) {
var pre;
if (output) {
pre = $("<pre class='terminal pre-scrollable' style='height: 70px; font-size: 0.8em'></pre>");
pre = $("<pre class='pre-scrollable pre-output' style='height: 70px; font-size: 0.8em'></pre>");
modalBody.append(pre);
}
@@ -784,7 +791,19 @@ function showProgressModal(options, promise) {
var counter = 0;
promise
.progress(function(text, success) {
.progress(function() {
var short, long, success;
if (arguments.length === 2) {
short = long = arguments[0];
success = arguments[1];
} else if (arguments.length === 3) {
short = arguments[0];
long = arguments[1];
success = arguments[2];
} else {
throw Error("Invalid parameters for showProgressModal, expected either (text, success) or (short, long, success)");
}
var value;
if (max === undefined || max <= 0) {
@@ -796,8 +815,8 @@ function showProgressModal(options, promise) {
// update progress bar
progressBar.width(String(value) + "%");
progressTextFront.text(text);
progressTextBack.text(text);
progressTextFront.text(short);
progressTextBack.text(short);
progressTextFront.width(progress.width());
// if not successful, apply failure class
@@ -809,9 +828,9 @@ function showProgressModal(options, promise) {
if (output && pre) {
if (success) {
pre.append($("<span class='" + outputClassSuccess + "'>" + text + "</span><br>"));
pre.append($("<span class='" + outputClassSuccess + "'>" + long + "</span>"));
} else {
pre.append($("<span class='" + outputClassFailure + "'>" + text + "</span><br>"));
pre.append($("<span class='" + outputClassFailure + "'>" + long + "</span>"));
}
pre.scrollTop(pre[0].scrollHeight - pre.height());
}
@@ -964,6 +983,22 @@ function getOnlyChangedData(data, oldData) {
return f(data, oldData);
}
function setOnViewModels(allViewModels, key, value) {
setOnViewModelsIf(allViewModels, key, value, undefined);
}
function setOnViewModelsIf(allViewModels, key, value, condition) {
if (condition === undefined || !_.isFunction(condition)) {
condition = function() { return true; };
}
_.each(allViewModels, function(viewModel) {
if (condition(viewModel)) {
viewModel[key] = value;
}
})
}
function callViewModels(allViewModels, method, callback) {
callViewModelsIf(allViewModels, method, undefined, callback);
}
+84 -53
View File
@@ -7,35 +7,6 @@ $(function() {
//~~ Logging setup
var logFormats = {
trace: "color: grey",
debug: "color: blue",
warn: "color: red",
error: "color: red; font-weight: bold"
};
var origLogFactory = log.methodFactory;
log.methodFactory = function(methodName, logLevel, loggerName) {
var rawMethod = origLogFactory(methodName, logLevel, loggerName);
var format = logFormats[methodName];
var level = _.padRight(methodName.toUpperCase(), 5, " ");
return function() {
var newArgs;
if (format && (OctoPrint.coreui.browser.chrome || OctoPrint.coreui.browser.firefox)) {
newArgs = ["%c[" + level + "]", format];
} else {
newArgs = ["[" + level + "]"];
}
for (var i = 0; i < arguments.length; i++) {
newArgs.push(arguments[i]);
}
return rawMethod.apply(null, newArgs);
}
};
log.setLevel(CONFIG_DEBUG ? log.levels.DEBUG : log.levels.INFO);
//~~ OctoPrint client setup
@@ -563,7 +534,15 @@ $(function() {
}
}
//~~ view model binding
//~~ final initialization - passive login, settings fetch, view model binding
if (!_.has(viewModelMap, "settingsViewModel")) {
throw new Error("settingsViewModel is missing, can't run UI");
}
if (!_.has(viewModelMap, "loginStateViewModel")) {
throw new Error("loginStateViewModel is missing, can't run UI");
}
var bindViewModels = function() {
log.info("Going to bind " + allViewModelData.length + " view models...");
@@ -632,7 +611,8 @@ $(function() {
});
}
viewModel._unbound = viewModel._bindings != undefined && viewModel._bindings.length == 0;
viewModel._unbound = viewModel._bindings !== undefined && viewModel._bindings.length === 0;
viewModel._bound = viewModel._bindings.length > 0;
if (viewModel.hasOwnProperty("onAfterBinding")) {
viewModel.onAfterBinding();
@@ -644,6 +624,7 @@ $(function() {
// startup complete
callViewModels(allViewModels, "onStartupComplete");
setOnViewModels(allViewModels, "_startupComplete", true);
// make sure we can track the browser tab visibility
OctoPrint.coreui.onBrowserVisibilityChange(function(status) {
@@ -663,34 +644,84 @@ $(function() {
log.info("Application startup complete");
};
if (!_.has(viewModelMap, "settingsViewModel")) {
throw new Error("settingsViewModel is missing, can't run UI")
}
var fetchSettings = function() {
log.info("Finalizing application startup");
//~~ Starting up the app
callViewModels(allViewModels, "onStartup");
viewModelMap["settingsViewModel"].requestData()
.done(function() {
// There appears to be an odd race condition either in JQuery's AJAX implementation or
// the browser's implementation of XHR, causing a second GET request from inside the
// completion handler of the very same request to never get its completion handler called
// if ETag headers are present on the response (the status code of the request does NOT
// seem to matter here, only that the ETag header is present).
//
// Minimal example with which I was able to reproduce this behaviour can be found
// at https://gist.github.com/foosel/b2ddb9ebd71b0b63a749444651bfce3f
//
// Decoupling all consecutive calls from this done event handler hence is an easy way
// to avoid this problem. A zero timeout should do the trick nicely.
window.setTimeout(bindViewModels, 0);
});
};
log.info("Initial application setup done, connecting to server...");
/**
* The following looks a bit complicated, so let me explain...
*
* Once we connect to the server (and that also includes consecutive reconnects), the
* first thing we need to do is perform a passive login to a) establish a proper request
* session with the server and b) figure out the login status of our client. That passive
* login will be responded to with our session cookie and we must make absolutely sure that
* this cannot be overridden by any concurrent requests. E.g. if we would send the passive
* login request and also something like a settings fetch, the settings would not have the
* cookie yet, hence the server would generate a new session for that request, and if the
* response for the settings now arrives later than the passive login we'll get our
* session cookie from that login directly overwritten again. That will not only lead to
* us losing our login session with the server but also the client _thinking_ it is logged
* in when in fact it isn't. See also #1881.
*
* So what we do here is ensure that we send the passive login request _and nothing else_
* until that has been responded to and hence our session been properly established. Only
* then we may trigger stuff like the various view model callbacks that might cause
* additional requests.
*
* onServerConnect below takes care of the passive login. Only once that's completed it tells
* our DataUpdater that it's ok to trigger any callbacks in view models. On the initial
* server connect (during first initialization) we also trigger the settings fetch and
* binding proceedure once that's done, but only then.
*
* Or, as a fancy diagram: https://gist.githubusercontent.com/foosel/0cdc3a03cf5311804271f12e87293c0c/raw/abc84fdc3b13030d70961539d9c132ae39c32085/octoprint_web_startup.txt
*/
var onServerConnect = function() {
// Always perform a passive login on server (re)connect. No need for
// onServerConnect/onServerReconnect on the LoginStateViewModel with this in place.
return viewModelMap["loginStateViewModel"].requestData()
.done(function() {
// Only mark our data updater as initialized once we've done our initial
// passive login request.
//
// This is to ensure that we have no concurrent requests triggered by socket events
// overriding each other's session during app intialization
dataUpdater.initialized();
});
};
var dataUpdater = new DataUpdater(allViewModels);
dataUpdater.connect()
.done(function() {
log.info("Finalizing application startup");
// make sure we trigger onServerConnect should we dis- and reconnect to the server
dataUpdater.connectCallback = onServerConnect;
//~~ Starting up the app
callViewModels(allViewModels, "onStartup");
viewModelMap["settingsViewModel"].requestData()
.done(function() {
// There appears to be an odd race condition either in JQuery's AJAX implementation or
// the browser's implementation of XHR, causing a second GET request from inside the
// completion handler of the very same request to never get its completion handler called
// if ETag headers are present on the response (the status code of the request does NOT
// seem to matter here, only that the ETag header is present).
//
// Minimal example with which I was able to reproduce this behaviour can be found
// at https://gist.github.com/foosel/b2ddb9ebd71b0b63a749444651bfce3f
//
// Decoupling all consecutive calls from this done event handler hence is an easy way
// to avoid this problem. A zero timeout should do the trick nicely.
window.setTimeout(bindViewModels, 0);
});
// perform passive login first
onServerConnect().done(function() {
// then trigger a settings fetch
window.setTimeout(fetchSettings, 0);
});
});
}
);
@@ -100,7 +100,7 @@ $(function() {
self.isReady(data.flags.ready);
self.isLoading(data.flags.loading);
if (self.loginState.isUser() && self.previousIsOperational != self.isOperational()) {
if (self.loginState.isUser() && self.previousIsOperational !== self.isOperational()) {
// only open or close if the panel is visible (for admins) and
// the state just changed to avoid thwarting manual open/close
self.openOrCloseOnStateChange();
@@ -132,16 +132,14 @@ $(function() {
self.onStartup = function() {
self.requestData();
};
// when isAdmin becomes true the first time, set the panel open or
// closed based on the connection state
var subscription = self.loginState.isAdmin.subscribe(function(newValue) {
if (newValue) {
// wait until after the isAdmin state has run through all subscriptions
setTimeout(self.openOrCloseOnStateChange, 0);
subscription.dispose();
}
});
self.onUserLoggedIn = function() {
self.openOrCloseOnStateChange();
};
self.onUserLoggedOut = function() {
self.openOrCloseOnStateChange();
};
}
@@ -257,7 +257,7 @@ $(function() {
self._configureLayerSlider(layerSliderElement);
self._configureLayerCommandSlider(commandSliderElement);
self.settings.requestData()
self.settings.firstRequest
.done(function() {
var initResult = GCODE.ui.init({
container: "#gcode_canvas",
@@ -12,6 +12,7 @@ $(function() {
self.isUser = ko.observable(false);
self.allViewModels = undefined;
self.startupDeferred = $.Deferred();
self.currentUser = ko.observable(undefined);
@@ -36,28 +37,45 @@ $(function() {
});
self.reloadUser = function() {
if (self.currentUser() == undefined) {
if (self.currentUser() === undefined) {
return;
}
OctoPrint.users.get(self.currentUser().name)
return OctoPrint.users.get(self.currentUser().name)
.done(self.updateCurrentUserData);
};
self.requestData = function() {
OctoPrint.browser.passiveLogin()
return OctoPrint.browser.passiveLogin()
.done(self.fromResponse);
};
self.fromResponse = function(response) {
if (response && response.name) {
self.loggedIn(true);
self.updateCurrentUserData(response);
callViewModels(self.allViewModels, "onUserLoggedIn", [response]);
var process = function() {
var currentLoggedIn = self.loggedIn();
if (response && response.name) {
self.loggedIn(true);
self.updateCurrentUserData(response);
if (!currentLoggedIn) {
callViewModels(self.allViewModels, "onUserLoggedIn", [response]);
log.info("User " + response.name + " logged in")
}
} else {
self.loggedIn(false);
self.resetCurrentUserData();
if (currentLoggedIn) {
callViewModels(self.allViewModels, "onUserLoggedOut");
log.info("User logged out");
}
}
};
if (self.startupDeferred !== undefined) {
// Make sure we only fire our "onUserLogged(In|Out)" message after the application
// has started up.
self.startupDeferred.done(process);
} else {
self.loggedIn(false);
self.resetCurrentUserData();
callViewModels(self.allViewModels, "onUserLoggedOut");
process();
}
};
@@ -101,7 +119,7 @@ $(function() {
};
self.logout = function() {
OctoPrint.browser.logout()
return OctoPrint.browser.logout()
.done(function(response) {
new PNotify({title: gettext("Logout successful"), text: gettext("You are now logged out"), type: "success"});
self.fromResponse(response);
@@ -122,11 +140,8 @@ $(function() {
self.onAllBound = function(allViewModels) {
self.allViewModels = allViewModels;
};
self.onStartupComplete = self.onServerConnect = self.onServerReconnect = function() {
if (self.allViewModels == undefined) return;
self.requestData();
self.startupDeferred.resolve();
self.startupDeferred = undefined;
};
self.onStartup = function() {
@@ -7,6 +7,11 @@ $(function() {
self.printerProfiles = parameters[2];
self.about = parameters[3];
// use this promise to do certain things once the SettingsViewModel has processed
// its first request
var firstRequest = $.Deferred();
self.firstRequest = firstRequest.promise();
self.allViewModels = [];
self.receiving = ko.observable(false);
@@ -185,9 +190,13 @@ $(function() {
self.scripts_gcode_beforePrintResumed = ko.observable(undefined);
self.scripts_gcode_afterPrinterConnected = ko.observable(undefined);
self.scripts_gcode_beforePrinterDisconnected = ko.observable(undefined);
self.scripts_gcode_afterToolChange = ko.observable(undefined);
self.scripts_gcode_beforeToolChange = ko.observable(undefined);
self.temperature_profiles = ko.observableArray(undefined);
self.temperature_cutoff = ko.observable(undefined);
self.temperature_sendAutomatically = ko.observable(undefined);
self.temperature_sendAutomaticallyAfter = ko.observable(undefined);
self.system_actions = ko.observableArray([]);
@@ -761,6 +770,8 @@ $(function() {
};
mapToObservables(serverChangedData, specialMappings, clientChangedData);
firstRequest.resolve();
};
self.saveData = function (data, successCallback, setAsSending) {
@@ -875,12 +886,14 @@ $(function() {
};
self.onUserLoggedIn = function() {
// we might have other user rights now, refresh
// we might have other user rights now, refresh (but only if startup has fully completed)
if (!self._startupComplete) return;
self.requestData();
};
self.onUserLoggedOut = function() {
// we might have other user rights now, refresh
// we might have other user rights now, refresh (but only if startup has fully completed)
if (!self._startupComplete) return;
self.requestData();
}
}
@@ -6,7 +6,7 @@ $(function() {
self.settingsViewModel = parameters[1];
self._createToolEntry = function() {
return {
var entry = {
name: ko.observable(),
key: ko.observable(),
actual: ko.observable(0),
@@ -14,11 +14,63 @@ $(function() {
offset: ko.observable(0),
newTarget: ko.observable(),
newOffset: ko.observable()
}
};
entry.newTargetValid = ko.pureComputed(function() {
var value = entry.newTarget();
try {
value = parseInt(value);
} catch (exc) {
return false;
}
return (value >= 0 && value <= 999);
});
entry.newOffsetValid = ko.pureComputed(function() {
var value = entry.newOffset();
try {
value = parseInt(value);
} catch (exc) {
return false;
}
return (-50 <= value <= 50);
});
entry.offset.subscribe(function(newValue) {
if (self.changingOffset.item !== undefined && self.changingOffset.item.key() == entry.key()) {
// if our we currently have the offset dialog open for this entry and the offset changed
// meanwhile, update the displayed value in the dialog
self.changingOffset.offset(newValue);
}
});
return entry;
};
self.changingOffset = {
offset: ko.observable(0),
newOffset: ko.observable(0),
name: ko.observable(""),
item: undefined,
title: ko.pureComputed(function() {
return _.sprintf(gettext("Changing Offset of %(name)s"), {name: self.changingOffset.name()});
}),
description: ko.pureComputed(function() {
return _.sprintf(gettext("Use the form below to specify a new offset to apply to all temperature commands sent from printed files for \"%(name)s\""),
{name: self.changingOffset.name()});
})
};
self.changeOffsetDialog = undefined;
self.tools = ko.observableArray([]);
self.hasBed = ko.observable(true);
self.bedTemp = self._createToolEntry();
self.bedTemp["name"](gettext("Bed"));
self.bedTemp["key"]("bed");
@@ -90,7 +142,7 @@ $(function() {
if (!self._printerProfileInitialized) {
self._triggerBacklog();
}
self.updatePlot();
self.updatePlot(false);
};
self.settingsViewModel.printerProfiles.currentProfileData.subscribe(function() {
self._printerProfileUpdated();
@@ -99,39 +151,10 @@ $(function() {
});
self.temperatures = [];
self.plotOptions = {
yaxis: {
min: 0,
max: 310,
ticks: 10
},
xaxis: {
mode: "time",
minTickSize: [2, "minute"],
tickFormatter: function(val, axis) {
if (val == undefined || val == 0)
return ""; // we don't want to display the minutes since the epoch if not connected yet ;)
// current time in milliseconds in UTC
var timestampUtc = Date.now();
// calculate difference in milliseconds
var diff = timestampUtc - val;
// convert to minutes
var diffInMins = Math.round(diff / (60 * 1000));
if (diffInMins == 0)
return gettext("just now");
else
return "- " + diffInMins + " " + gettext("min");
}
},
legend: {
position: "sw",
noColumns: 2,
backgroundOpacity: 0
}
};
self.plot = undefined;
self.plotHoverPos = undefined;
self.plotLegendTimeout = undefined;
self.fromCurrentData = function(data) {
self._processStateData(data.state);
@@ -197,12 +220,12 @@ $(function() {
if (!CONFIG_TEMPERATURE_GRAPH) return;
self.temperatures = self._processTemperatureData(serverTime, data, self.temperatures);
self.updatePlot();
self.updatePlot(false);
};
self._processTemperatureHistoryData = function(serverTime, data) {
self.temperatures = self._processTemperatureData(serverTime, data);
self.updatePlot();
self.updatePlot(false);
};
self._processOffsetData = function(data) {
@@ -261,7 +284,9 @@ $(function() {
return result;
};
self.updatePlot = function() {
self.updatePlot = function(force) {
force = force == undefined ? true : force;
var graph = $("#temperature-graph");
if (graph.length) {
var data = [];
@@ -270,6 +295,8 @@ $(function() {
var maxTemps = [310/1.1];
var showFahrenheit = self._shallShowFahrenheit();
_.each(_.keys(heaterOptions), function(type) {
if (type == "bed" && !self.hasBed()) {
return;
@@ -283,9 +310,6 @@ $(function() {
targets = self.temperatures[type].target;
}
var showFahrenheit = (self.settingsViewModel.settings !== undefined )
? self.settingsViewModel.settings.appearance.showFahrenheitAlso()
: false;
var actualTemp = actuals && actuals.length ? formatTemperature(actuals[actuals.length - 1][1], showFahrenheit) : "-";
var targetTemp = targets && targets.length ? formatTemperature(targets[targets.length - 1][1], showFahrenheit) : "-";
@@ -303,11 +327,115 @@ $(function() {
maxTemps.push(self.getMaxTemp(actuals, targets));
});
self.plotOptions.yaxis.max = Math.max.apply(null, maxTemps) * 1.1;
$.plot(graph, data, self.plotOptions);
if (!self.plot || force) {
// we don't have a plot yet, we need to set stuff up
var options = {
yaxis: {
min: 0,
max: Math.max(Math.max.apply(null, maxTemps) * 1.1, 310),
ticks: 10
},
xaxis: {
mode: "time",
minTickSize: [2, "minute"],
tickFormatter: function(val, axis) {
if (val == undefined || val == 0)
return ""; // we don't want to display the minutes since the epoch if not connected yet ;)
// current time in milliseconds in UTC
var timestampUtc = Date.now();
// calculate difference in milliseconds
var diff = timestampUtc - val;
// convert to minutes
var diffInMins = Math.round(diff / (60 * 1000));
if (diffInMins == 0)
return gettext("just now");
else
return "- " + diffInMins + " " + gettext("min");
}
},
legend: {
position: "sw",
noColumns: 2,
backgroundOpacity: 0
}
};
if (!OctoPrint.coreui.browser.mobile) {
options["crosshair"] = { mode: "x" };
options["grid"] = { hoverable: true, autoHighlight: false };
}
self.plot = $.plot(graph, data, options);
} else {
// graph already active, let's just update the data
self.plot.setData(data);
self.plot.getAxes().yaxis.max = Math.max(Math.max.apply(null, maxTemps) * 1.1, 310);
self.updateLegend(self._replaceLegendLabel);
self.plot.draw();
}
}
};
self.updateLegend = function(replaceLegendLabel) {
self.plotLegendTimeout = undefined;
var resetLegend = function() {
_.each(dataset, function(series, index) {
var value = series.data && series.data.length ? series.data[series.data.length - 1][1] : undefined;
replaceLegendLabel(index, series, value);
});
};
var pos = self.plotHoverPos;
if (pos && !OctoPrint.coreui.browser.mobile) {
// we got a hover position, let's see what we need to do with that
var i;
var axes = self.plot.getAxes();
var dataset = self.plot.getData();
if (pos.x < axes.xaxis.min || pos.x > axes.xaxis.max ||
pos.y < axes.yaxis.min || pos.y > axes.yaxis.max) {
// position outside of the graph, show latest temperature in legend
resetLegend();
} else {
// position inside the graph, determine temperature at point and display that in the legend
_.each(dataset, function(series, index) {
for (i = 0; i < series.data.length; i++) {
if (series.data[i][0] > pos.x) {
break;
}
}
var y;
var p1 = series.data[i - 1];
var p2 = series.data[i];
if (p1 === undefined && p2 === undefined) {
y = undefined;
} else if (p1 === undefined) {
y = p2[1];
} else if (p2 === undefined) {
y = p1[1];
} else {
y = p1[1] + (p2[1] - p1[1]) * (pos.x - p1[0]) / (p2[0] - p1[0]);
}
replaceLegendLabel(index, series, y, true);
});
}
} else {
resetLegend();
}
// update the grid
self.plot.setupGrid();
};
self.getMaxTemp = function(actuals, targets) {
var pair;
var maxTemp = 0;
@@ -324,66 +452,191 @@ $(function() {
return maxTemp;
};
self.setTarget = function(item) {
self.incrementTarget = function(item) {
var value = item.newTarget();
if (!value) return;
var onSuccess = function() {
item.newTarget("");
};
if (item.key() == "bed") {
self._setBedTemperature(value)
.done(onSuccess);
} else {
self._setToolTemperature(item.key(), value)
.done(onSuccess);
if (value === undefined || (typeof(value) == "string" && value.trim() == "")) {
value = item.target();
}
try {
value = parseInt(value);
if (value > 999) return;
item.newTarget(value + 1);
self.autosendTarget(item);
} catch (ex) {
// do nothing
}
};
self.decrementTarget = function(item) {
var value = item.newTarget();
if (value === undefined || (typeof(value) == "string" && value.trim() == "")) {
value = item.target();
}
try {
value = parseInt(value);
if (value <= 0) return;
item.newTarget(value - 1);
self.autosendTarget(item);
} catch (ex) {
// do nothing
}
};
var _sendTimeout = {};
self.autosendTarget = function(item) {
if (!self.settingsViewModel.temperature_sendAutomatically()) return;
var delay = self.settingsViewModel.temperature_sendAutomaticallyAfter() * 1000;
var name = item.name();
if (_sendTimeout[name]) {
window.clearTimeout(_sendTimeout[name]);
}
_sendTimeout[name] = window.setTimeout(function() {
self.setTarget(item);
delete _sendTimeout[name];
}, delay);
};
self.clearAutosendTarget = function(item) {
var name = item.name();
if (_sendTimeout[name]) {
window.clearTimeout(_sendTimeout[name]);
delete _sendTimeout[name];
}
};
self.setTarget = function(item, form) {
var value = item.newTarget();
if (form !== undefined) {
$(form).find("input").blur();
}
if (value === undefined || (typeof(value) == "string" && value.trim() == "")) return OctoPrintClient.createRejectedDeferred();
self.clearAutosendTarget(item);
return self.setTargetToValue(item, value);
};
self.setTargetFromProfile = function(item, profile) {
if (!profile) return;
if (!profile) return OctoPrintClient.createRejectedDeferred();
self.clearAutosendTarget(item);
return self.setTargetToValue(item, (item.key() == "bed" ? profile.bed : profile.extruder));
};
self.setTargetToZero = function(item) {
self.clearAutosendTarget(item);
return self.setTargetToValue(item, 0);
};
self.setTargetToValue = function(item, value) {
self.clearAutosendTarget(item);
try {
value = parseInt(value);
} catch (ex) {
return OctoPrintClient.createRejectedDeferred();
}
if (value < 0 || value > 999) return OctoPrintClient.createRejectedDeferred();
var onSuccess = function() {
item.target(value);
item.newTarget("");
};
if (item.key() == "bed") {
self._setBedTemperature(profile.bed)
return self._setBedTemperature(value)
.done(onSuccess);
} else {
self._setToolTemperature(item.key(), profile.extruder)
return self._setToolTemperature(item.key(), value)
.done(onSuccess);
}
};
self.setTargetToZero = function(item) {
var onSuccess = function() {
item.newTarget("");
};
self.changeOffset = function(item) {
// copy values
self.changingOffset.item = item;
self.changingOffset.name(item.name());
self.changingOffset.offset(item.offset());
self.changingOffset.newOffset(item.offset());
if (item.key() == "bed") {
self._setBedTemperature(0)
.done(onSuccess);
} else {
self._setToolTemperature(item.key(), 0)
.done(onSuccess);
self.changeOffsetDialog.modal("show");
};
self.incrementChangeOffset = function() {
var value = self.changingOffset.newOffset();
if (value === undefined || (typeof(value) == "string" && value.trim() == "")) value = self.changingOffset.offset();
try {
value = parseInt(value);
if (value >= 50) return;
self.changingOffset.newOffset(value + 1);
} catch (ex) {
// do nothing
}
};
self.decrementChangeOffset = function() {
var value = self.changingOffset.newOffset();
if (value === undefined || (typeof(value) == "string" && value.trim() == "")) value = self.changingOffset.offset();
try {
value = parseInt(value);
if (value <= -50) return;
self.changingOffset.newOffset(value - 1);
} catch (ex) {
// do nothing
}
};
self.deleteChangeOffset = function() {
self.changingOffset.newOffset(0);
};
self.confirmChangeOffset = function() {
var item = self.changingOffset.item;
item.newOffset(self.changingOffset.newOffset());
self.setOffset(item)
.done(function() {
self.changeOffsetDialog.modal("hide");
// reset
self.changingOffset.offset(0);
self.changingOffset.newOffset(0);
self.changingOffset.name("");
self.changingOffset.item = undefined;
})
};
self.setOffset = function(item) {
var value = item.newOffset();
if (!value) return;
if (value === undefined || (typeof(value) == "string" && value.trim() == "")) return OctoPrintClient.createRejectedDeferred();
return self.setOffsetToValue(item, value);
};
self.setOffsetToZero = function(item) {
return self.setOffsetToValue(item, 0);
};
self.setOffsetToValue = function(item, value) {
try {
value = parseInt(value);
} catch (ex) {
return OctoPrintClient.createRejectedDeferred();
}
if (value < -50 || value > 50) return OctoPrintClient.createRejectedDeferred();
var onSuccess = function() {
item.offset(value);
item.newOffset("");
};
if (item.key() == "bed") {
self._setBedOffset(value)
return self._setBedOffset(value)
.done(onSuccess);
} else {
self._setToolOffset(item.key(), value)
return self._setToolOffset(item.key(), value)
.done(onSuccess);
}
};
@@ -408,21 +661,70 @@ $(function() {
return OctoPrint.printer.setBedTemperatureOffset(parseInt(offset));
};
self._replaceLegendLabel = function(index, series, value, emph) {
var showFahrenheit = self._shallShowFahrenheit();
var temp = formatTemperature(value, showFahrenheit);
if (emph) {
temp = "<em>" + temp + "</em>";
}
series.label = series.label.replace(/:.*/, ": " + temp);
};
self._shallShowFahrenheit = function() {
return (self.settingsViewModel.settings !== undefined )
? self.settingsViewModel.settings.appearance.showFahrenheitAlso()
: false;
};
self.handleEnter = function(event, type, item) {
if (event.keyCode == 13) {
if (type == "target") {
self.setTarget(item);
self.setTarget(item)
.done(function() {
event.target.blur();
});
} else if (type == "offset") {
self.setOffset(item);
self.confirmChangeOffset();
}
}
};
self.handleFocus = function(event, type, item) {
if (type == "target") {
var value = item.newTarget();
if (value === undefined || (typeof(value) == "string" && value.trim() == "")) {
item.newTarget(item.target());
}
event.target.select();
} else if (type == "offset") {
event.target.select();
}
};
self.onAfterTabChange = function(current, previous) {
if (current != "#temp") {
return;
}
self.updatePlot();
self.updatePlot(false);
};
self.onStartup = function() {
var graph = $("#temperature-graph");
if (graph.length && !OctoPrint.coreui.browser.mobile) {
graph.bind("plothover", function (event, pos, item) {
self.plotHoverPos = pos;
if (!self.plotLegendTimeout) {
self.plotLegendTimeout = window.setTimeout(function() {
self.updateLegend(self._replaceLegendLabel)
}, 50);
}
});
}
};
self.onStartup = function() {
self.changeOffsetDialog = $("#change_offset_dialog");
};
self.onStartupComplete = function() {
@@ -434,6 +736,6 @@ $(function() {
OCTOPRINT_VIEWMODELS.push([
TemperatureViewModel,
["loginStateViewModel", "settingsViewModel"],
"#temp"
["#temp", "#change_offset_dialog"]
]);
});
@@ -51,10 +51,6 @@ $(function() {
return self.isDirty() && !self.isPrinting() && self.loginState.isUser();
});
self.isOperational.subscribe(function() {
self.requestData();
});
self.timelapseType.subscribe(function() {
self.isDirty(true);
});
@@ -229,6 +225,16 @@ $(function() {
.done(function() {
self.markedForFileDeletion.remove(filename);
self.requestData()
})
.fail(function(jqXHR) {
var html = "<p>" + _.sprintf(gettext("Failed to remove timelapse %(name)s.</p><p>Please consult octoprint.log for details.</p>"), {name: filename});
html += pnotifyAdditionalInfo('<pre style="overflow: auto">' + jqXHR.responseText + '</pre>');
new PNotify({
title: gettext("Could not remove timelapse"),
text: html,
type: "error",
hide: false
});
});
};
@@ -288,7 +294,7 @@ $(function() {
self._bulkRemove = function(files, type) {
var title, message, handler;
if (type == "files") {
if (type === "files") {
title = gettext("Deleting timelapse files");
message = _.sprintf(gettext("Deleting %(count)d timelapse files..."), {count: files.length});
handler = function(filename) {
@@ -296,11 +302,13 @@ $(function() {
.done(function() {
deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: filename}), true);
})
.fail(function() {
deferred.notify(_.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: filename}), false);
.fail(function(jqXHR) {
var short = _.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: filename});
var long = _.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"), {filename: filename, error: jqXHR.responseText});
deferred.notify(short, long, false);
});
}
} else if (type == "unrendered") {
} else if (type === "unrendered") {
title = gettext("Deleting unrendered timelapses");
message = _.sprintf(gettext("Deleting %(count)d unrendered timelapses..."), {count: files.length});
handler = function(filename) {
@@ -0,0 +1,176 @@
/* Flot plugin for showing crosshairs when the mouse hovers over the plot.
Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.
The plugin supports these options:
crosshair: {
mode: null or "x" or "y" or "xy"
color: color
lineWidth: number
}
Set the mode to one of "x", "y" or "xy". The "x" mode enables a vertical
crosshair that lets you trace the values on the x axis, "y" enables a
horizontal crosshair and "xy" enables them both. "color" is the color of the
crosshair (default is "rgba(170, 0, 0, 0.80)"), "lineWidth" is the width of
the drawn lines (default is 1).
The plugin also adds four public methods:
- setCrosshair( pos )
Set the position of the crosshair. Note that this is cleared if the user
moves the mouse. "pos" is in coordinates of the plot and should be on the
form { x: xpos, y: ypos } (you can use x2/x3/... if you're using multiple
axes), which is coincidentally the same format as what you get from a
"plothover" event. If "pos" is null, the crosshair is cleared.
- clearCrosshair()
Clear the crosshair.
- lockCrosshair(pos)
Cause the crosshair to lock to the current location, no longer updating if
the user moves the mouse. Optionally supply a position (passed on to
setCrosshair()) to move it to.
Example usage:
var myFlot = $.plot( $("#graph"), ..., { crosshair: { mode: "x" } } };
$("#graph").bind( "plothover", function ( evt, position, item ) {
if ( item ) {
// Lock the crosshair to the data point being hovered
myFlot.lockCrosshair({
x: item.datapoint[ 0 ],
y: item.datapoint[ 1 ]
});
} else {
// Return normal crosshair operation
myFlot.unlockCrosshair();
}
});
- unlockCrosshair()
Free the crosshair to move again after locking it.
*/
(function ($) {
var options = {
crosshair: {
mode: null, // one of null, "x", "y" or "xy",
color: "rgba(170, 0, 0, 0.80)",
lineWidth: 1
}
};
function init(plot) {
// position of crosshair in pixels
var crosshair = { x: -1, y: -1, locked: false };
plot.setCrosshair = function setCrosshair(pos) {
if (!pos)
crosshair.x = -1;
else {
var o = plot.p2c(pos);
crosshair.x = Math.max(0, Math.min(o.left, plot.width()));
crosshair.y = Math.max(0, Math.min(o.top, plot.height()));
}
plot.triggerRedrawOverlay();
};
plot.clearCrosshair = plot.setCrosshair; // passes null for pos
plot.lockCrosshair = function lockCrosshair(pos) {
if (pos)
plot.setCrosshair(pos);
crosshair.locked = true;
};
plot.unlockCrosshair = function unlockCrosshair() {
crosshair.locked = false;
};
function onMouseOut(e) {
if (crosshair.locked)
return;
if (crosshair.x != -1) {
crosshair.x = -1;
plot.triggerRedrawOverlay();
}
}
function onMouseMove(e) {
if (crosshair.locked)
return;
if (plot.getSelection && plot.getSelection()) {
crosshair.x = -1; // hide the crosshair while selecting
return;
}
var offset = plot.offset();
crosshair.x = Math.max(0, Math.min(e.pageX - offset.left, plot.width()));
crosshair.y = Math.max(0, Math.min(e.pageY - offset.top, plot.height()));
plot.triggerRedrawOverlay();
}
plot.hooks.bindEvents.push(function (plot, eventHolder) {
if (!plot.getOptions().crosshair.mode)
return;
eventHolder.mouseout(onMouseOut);
eventHolder.mousemove(onMouseMove);
});
plot.hooks.drawOverlay.push(function (plot, ctx) {
var c = plot.getOptions().crosshair;
if (!c.mode)
return;
var plotOffset = plot.getPlotOffset();
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
if (crosshair.x != -1) {
var adj = plot.getOptions().crosshair.lineWidth % 2 ? 0.5 : 0;
ctx.strokeStyle = c.color;
ctx.lineWidth = c.lineWidth;
ctx.lineJoin = "round";
ctx.beginPath();
if (c.mode.indexOf("x") != -1) {
var drawX = Math.floor(crosshair.x) + adj;
ctx.moveTo(drawX, 0);
ctx.lineTo(drawX, plot.height());
}
if (c.mode.indexOf("y") != -1) {
var drawY = Math.floor(crosshair.y) + adj;
ctx.moveTo(0, drawY);
ctx.lineTo(plot.width(), drawY);
}
ctx.stroke();
}
ctx.restore();
});
plot.hooks.shutdown.push(function (plot, eventHolder) {
eventHolder.unbind("mouseout", onMouseOut);
eventHolder.unbind("mousemove", onMouseMove);
});
}
$.plot.plugins.push({
init: init,
options: options,
name: 'crosshair',
version: '1.0'
});
})(jQuery);
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,59 @@
/* Flot plugin for automatically redrawing plots as the placeholder resizes.
Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.
It works by listening for changes on the placeholder div (through the jQuery
resize event plugin) - if the size changes, it will redraw the plot.
There are no options. If you need to disable the plugin for some plots, you
can just fix the size of their placeholders.
*/
/* Inline dependency:
* jQuery resize event - v1.1 - 3/14/2010
* http://benalman.com/projects/jquery-resize-plugin/
*
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
(function($,e,t){"$:nomunge";var i=[],n=$.resize=$.extend($.resize,{}),a,r=false,s="setTimeout",u="resize",m=u+"-special-event",o="pendingDelay",l="activeDelay",f="throttleWindow";n[o]=200;n[l]=20;n[f]=true;$.event.special[u]={setup:function(){if(!n[f]&&this[s]){return false}var e=$(this);i.push(this);e.data(m,{w:e.width(),h:e.height()});if(i.length===1){a=t;h()}},teardown:function(){if(!n[f]&&this[s]){return false}var e=$(this);for(var t=i.length-1;t>=0;t--){if(i[t]==this){i.splice(t,1);break}}e.removeData(m);if(!i.length){if(r){cancelAnimationFrame(a)}else{clearTimeout(a)}a=null}},add:function(e){if(!n[f]&&this[s]){return false}var i;function a(e,n,a){var r=$(this),s=r.data(m)||{};s.w=n!==t?n:r.width();s.h=a!==t?a:r.height();i.apply(this,arguments)}if($.isFunction(e)){i=e;return a}else{i=e.handler;e.handler=a}}};function h(t){if(r===true){r=t||1}for(var s=i.length-1;s>=0;s--){var l=$(i[s]);if(l[0]==e||l.is(":visible")){var f=l.width(),c=l.height(),d=l.data(m);if(d&&(f!==d.w||c!==d.h)){l.trigger(u,[d.w=f,d.h=c]);r=t||true}}else{d=l.data(m);d.w=0;d.h=0}}if(a!==null){if(r&&(t==null||t-r<1e3)){a=e.requestAnimationFrame(h)}else{a=setTimeout(h,n[o]);r=false}}}if(!e.requestAnimationFrame){e.requestAnimationFrame=function(){return e.webkitRequestAnimationFrame||e.mozRequestAnimationFrame||e.oRequestAnimationFrame||e.msRequestAnimationFrame||function(t,i){return e.setTimeout(function(){t((new Date).getTime())},n[l])}}()}if(!e.cancelAnimationFrame){e.cancelAnimationFrame=function(){return e.webkitCancelRequestAnimationFrame||e.mozCancelRequestAnimationFrame||e.oCancelRequestAnimationFrame||e.msCancelRequestAnimationFrame||clearTimeout}()}})(jQuery,this);
(function ($) {
var options = { }; // no options
function init(plot) {
function onResize() {
var placeholder = plot.getPlaceholder();
// somebody might have hidden us and we can't plot
// when we don't have the dimensions
if (placeholder.width() == 0 || placeholder.height() == 0)
return;
plot.resize();
plot.setupGrid();
plot.draw();
}
function bindEvents(plot, eventHolder) {
plot.getPlaceholder().resize(onResize);
}
function shutdown(plot, eventHolder) {
plot.getPlaceholder().unbind("resize", onResize);
}
plot.hooks.bindEvents.push(bindEvents);
plot.hooks.shutdown.push(shutdown);
}
$.plot.plugins.push({
init: init,
options: options,
name: 'resize',
version: '1.0'
});
})(jQuery);
@@ -0,0 +1,432 @@
/* Pretty handling of time axes.
Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.
Set axis.mode to "time" to enable. See the section "Time series data" in
API.txt for details.
*/
(function($) {
var options = {
xaxis: {
timezone: null, // "browser" for local to the client or timezone for timezone-js
timeformat: null, // format string to use
twelveHourClock: false, // 12 or 24 time in time mode
monthNames: null // list of names of months
}
};
// round to nearby lower multiple of base
function floorInBase(n, base) {
return base * Math.floor(n / base);
}
// Returns a string with the date d formatted according to fmt.
// A subset of the Open Group's strftime format is supported.
function formatDate(d, fmt, monthNames, dayNames) {
if (typeof d.strftime == "function") {
return d.strftime(fmt);
}
var leftPad = function(n, pad) {
n = "" + n;
pad = "" + (pad == null ? "0" : pad);
return n.length == 1 ? pad + n : n;
};
var r = [];
var escape = false;
var hours = d.getHours();
var isAM = hours < 12;
if (monthNames == null) {
monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
}
if (dayNames == null) {
dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
}
var hours12;
if (hours > 12) {
hours12 = hours - 12;
} else if (hours == 0) {
hours12 = 12;
} else {
hours12 = hours;
}
for (var i = 0; i < fmt.length; ++i) {
var c = fmt.charAt(i);
if (escape) {
switch (c) {
case 'a': c = "" + dayNames[d.getDay()]; break;
case 'b': c = "" + monthNames[d.getMonth()]; break;
case 'd': c = leftPad(d.getDate()); break;
case 'e': c = leftPad(d.getDate(), " "); break;
case 'h': // For back-compat with 0.7; remove in 1.0
case 'H': c = leftPad(hours); break;
case 'I': c = leftPad(hours12); break;
case 'l': c = leftPad(hours12, " "); break;
case 'm': c = leftPad(d.getMonth() + 1); break;
case 'M': c = leftPad(d.getMinutes()); break;
// quarters not in Open Group's strftime specification
case 'q':
c = "" + (Math.floor(d.getMonth() / 3) + 1); break;
case 'S': c = leftPad(d.getSeconds()); break;
case 'y': c = leftPad(d.getFullYear() % 100); break;
case 'Y': c = "" + d.getFullYear(); break;
case 'p': c = (isAM) ? ("" + "am") : ("" + "pm"); break;
case 'P': c = (isAM) ? ("" + "AM") : ("" + "PM"); break;
case 'w': c = "" + d.getDay(); break;
}
r.push(c);
escape = false;
} else {
if (c == "%") {
escape = true;
} else {
r.push(c);
}
}
}
return r.join("");
}
// To have a consistent view of time-based data independent of which time
// zone the client happens to be in we need a date-like object independent
// of time zones. This is done through a wrapper that only calls the UTC
// versions of the accessor methods.
function makeUtcWrapper(d) {
function addProxyMethod(sourceObj, sourceMethod, targetObj, targetMethod) {
sourceObj[sourceMethod] = function() {
return targetObj[targetMethod].apply(targetObj, arguments);
};
};
var utc = {
date: d
};
// support strftime, if found
if (d.strftime != undefined) {
addProxyMethod(utc, "strftime", d, "strftime");
}
addProxyMethod(utc, "getTime", d, "getTime");
addProxyMethod(utc, "setTime", d, "setTime");
var props = ["Date", "Day", "FullYear", "Hours", "Milliseconds", "Minutes", "Month", "Seconds"];
for (var p = 0; p < props.length; p++) {
addProxyMethod(utc, "get" + props[p], d, "getUTC" + props[p]);
addProxyMethod(utc, "set" + props[p], d, "setUTC" + props[p]);
}
return utc;
};
// select time zone strategy. This returns a date-like object tied to the
// desired timezone
function dateGenerator(ts, opts) {
if (opts.timezone == "browser") {
return new Date(ts);
} else if (!opts.timezone || opts.timezone == "utc") {
return makeUtcWrapper(new Date(ts));
} else if (typeof timezoneJS != "undefined" && typeof timezoneJS.Date != "undefined") {
var d = new timezoneJS.Date();
// timezone-js is fickle, so be sure to set the time zone before
// setting the time.
d.setTimezone(opts.timezone);
d.setTime(ts);
return d;
} else {
return makeUtcWrapper(new Date(ts));
}
}
// map of app. size of time units in milliseconds
var timeUnitSize = {
"second": 1000,
"minute": 60 * 1000,
"hour": 60 * 60 * 1000,
"day": 24 * 60 * 60 * 1000,
"month": 30 * 24 * 60 * 60 * 1000,
"quarter": 3 * 30 * 24 * 60 * 60 * 1000,
"year": 365.2425 * 24 * 60 * 60 * 1000
};
// the allowed tick sizes, after 1 year we use
// an integer algorithm
var baseSpec = [
[1, "second"], [2, "second"], [5, "second"], [10, "second"],
[30, "second"],
[1, "minute"], [2, "minute"], [5, "minute"], [10, "minute"],
[30, "minute"],
[1, "hour"], [2, "hour"], [4, "hour"],
[8, "hour"], [12, "hour"],
[1, "day"], [2, "day"], [3, "day"],
[0.25, "month"], [0.5, "month"], [1, "month"],
[2, "month"]
];
// we don't know which variant(s) we'll need yet, but generating both is
// cheap
var specMonths = baseSpec.concat([[3, "month"], [6, "month"],
[1, "year"]]);
var specQuarters = baseSpec.concat([[1, "quarter"], [2, "quarter"],
[1, "year"]]);
function init(plot) {
plot.hooks.processOptions.push(function (plot, options) {
$.each(plot.getAxes(), function(axisName, axis) {
var opts = axis.options;
if (opts.mode == "time") {
axis.tickGenerator = function(axis) {
var ticks = [];
var d = dateGenerator(axis.min, opts);
var minSize = 0;
// make quarter use a possibility if quarters are
// mentioned in either of these options
var spec = (opts.tickSize && opts.tickSize[1] ===
"quarter") ||
(opts.minTickSize && opts.minTickSize[1] ===
"quarter") ? specQuarters : specMonths;
if (opts.minTickSize != null) {
if (typeof opts.tickSize == "number") {
minSize = opts.tickSize;
} else {
minSize = opts.minTickSize[0] * timeUnitSize[opts.minTickSize[1]];
}
}
for (var i = 0; i < spec.length - 1; ++i) {
if (axis.delta < (spec[i][0] * timeUnitSize[spec[i][1]]
+ spec[i + 1][0] * timeUnitSize[spec[i + 1][1]]) / 2
&& spec[i][0] * timeUnitSize[spec[i][1]] >= minSize) {
break;
}
}
var size = spec[i][0];
var unit = spec[i][1];
// special-case the possibility of several years
if (unit == "year") {
// if given a minTickSize in years, just use it,
// ensuring that it's an integer
if (opts.minTickSize != null && opts.minTickSize[1] == "year") {
size = Math.floor(opts.minTickSize[0]);
} else {
var magn = Math.pow(10, Math.floor(Math.log(axis.delta / timeUnitSize.year) / Math.LN10));
var norm = (axis.delta / timeUnitSize.year) / magn;
if (norm < 1.5) {
size = 1;
} else if (norm < 3) {
size = 2;
} else if (norm < 7.5) {
size = 5;
} else {
size = 10;
}
size *= magn;
}
// minimum size for years is 1
if (size < 1) {
size = 1;
}
}
axis.tickSize = opts.tickSize || [size, unit];
var tickSize = axis.tickSize[0];
unit = axis.tickSize[1];
var step = tickSize * timeUnitSize[unit];
if (unit == "second") {
d.setSeconds(floorInBase(d.getSeconds(), tickSize));
} else if (unit == "minute") {
d.setMinutes(floorInBase(d.getMinutes(), tickSize));
} else if (unit == "hour") {
d.setHours(floorInBase(d.getHours(), tickSize));
} else if (unit == "month") {
d.setMonth(floorInBase(d.getMonth(), tickSize));
} else if (unit == "quarter") {
d.setMonth(3 * floorInBase(d.getMonth() / 3,
tickSize));
} else if (unit == "year") {
d.setFullYear(floorInBase(d.getFullYear(), tickSize));
}
// reset smaller components
d.setMilliseconds(0);
if (step >= timeUnitSize.minute) {
d.setSeconds(0);
}
if (step >= timeUnitSize.hour) {
d.setMinutes(0);
}
if (step >= timeUnitSize.day) {
d.setHours(0);
}
if (step >= timeUnitSize.day * 4) {
d.setDate(1);
}
if (step >= timeUnitSize.month * 2) {
d.setMonth(floorInBase(d.getMonth(), 3));
}
if (step >= timeUnitSize.quarter * 2) {
d.setMonth(floorInBase(d.getMonth(), 6));
}
if (step >= timeUnitSize.year) {
d.setMonth(0);
}
var carry = 0;
var v = Number.NaN;
var prev;
do {
prev = v;
v = d.getTime();
ticks.push(v);
if (unit == "month" || unit == "quarter") {
if (tickSize < 1) {
// a bit complicated - we'll divide the
// month/quarter up but we need to take
// care of fractions so we don't end up in
// the middle of a day
d.setDate(1);
var start = d.getTime();
d.setMonth(d.getMonth() +
(unit == "quarter" ? 3 : 1));
var end = d.getTime();
d.setTime(v + carry * timeUnitSize.hour + (end - start) * tickSize);
carry = d.getHours();
d.setHours(0);
} else {
d.setMonth(d.getMonth() +
tickSize * (unit == "quarter" ? 3 : 1));
}
} else if (unit == "year") {
d.setFullYear(d.getFullYear() + tickSize);
} else {
d.setTime(v + step);
}
} while (v < axis.max && v != prev);
return ticks;
};
axis.tickFormatter = function (v, axis) {
var d = dateGenerator(v, axis.options);
// first check global format
if (opts.timeformat != null) {
return formatDate(d, opts.timeformat, opts.monthNames, opts.dayNames);
}
// possibly use quarters if quarters are mentioned in
// any of these places
var useQuarters = (axis.options.tickSize &&
axis.options.tickSize[1] == "quarter") ||
(axis.options.minTickSize &&
axis.options.minTickSize[1] == "quarter");
var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]];
var span = axis.max - axis.min;
var suffix = (opts.twelveHourClock) ? " %p" : "";
var hourCode = (opts.twelveHourClock) ? "%I" : "%H";
var fmt;
if (t < timeUnitSize.minute) {
fmt = hourCode + ":%M:%S" + suffix;
} else if (t < timeUnitSize.day) {
if (span < 2 * timeUnitSize.day) {
fmt = hourCode + ":%M" + suffix;
} else {
fmt = "%b %d " + hourCode + ":%M" + suffix;
}
} else if (t < timeUnitSize.month) {
fmt = "%b %d";
} else if ((useQuarters && t < timeUnitSize.quarter) ||
(!useQuarters && t < timeUnitSize.year)) {
if (span < timeUnitSize.year) {
fmt = "%b";
} else {
fmt = "%b %Y";
}
} else if (useQuarters && t < timeUnitSize.year) {
if (span < timeUnitSize.year) {
fmt = "Q%q";
} else {
fmt = "Q%q %Y";
}
} else {
fmt = "%Y";
}
var rt = formatDate(d, fmt, opts.monthNames, opts.dayNames);
return rt;
};
}
});
});
}
$.plot.plugins.push({
init: init,
options: options,
name: 'time',
version: '1.0'
});
// Time-axis support used to be in Flot core, which exposed the
// formatDate function on the plot object. Various plugins depend
// on the function, so we need to re-expose it here.
$.plot.formatDate = formatDate;
$.plot.dateGenerator = dateGenerator;
})(jQuery);
+86 -9
View File
@@ -400,7 +400,6 @@ table {
width: 80px;
.actioncol;
}
}
}
@@ -413,12 +412,52 @@ table {
background: url("../img/graph-background.png") no-repeat center;
}
.tab-content, .tab-pane {
overflow: visible;
#temperature-table {
table-layout: fixed;
width: 100%;
margin-top: 20px;
th, td {
&.temperature_tool,
&.temperature_actual,
&.temperature_target,
&.temperature_offset {
vertical-align: middle;
text-align: center;
form {
margin: 0;
}
.dropdown-menu {
text-align: left;
}
}
&.temperature_tool {
width: 18%;
text-align: left;
}
&.temperature_actual {
width: 12%;
}
&.temperature_target {
width: 40%;
overflow: visible;
}
&.temperature_offset {
width: 30%;
}
}
}
.tempInput {
width: 50px;
/** Various */
.tab-content, .tab-pane {
overflow: visible;
}
#temp_newTemp, #temp_newBedTemp, #speed_innerWall, #speed_outerWall, #speed_fill, #speed_support,
@@ -840,10 +879,6 @@ ul.dropdown-menu li a {
#terminal-sendpanel {
text-align: right;
}
#terminal-output span {
display: block;
}
}
#settings_dialog {
@@ -1228,6 +1263,12 @@ _::-webkit-full-page-media, _:future, :root .full-sized-box {
-webkit-overflow-scrolling: touch;
}
.pre-output {
span {
display: block; // so we don't need to add individual <br> tags to each line
}
}
.input-append, .input-prepend {
.add-on {
&.add-on-limited {
@@ -1236,6 +1277,27 @@ _::-webkit-full-page-media, _:future, :root .full-sized-box {
width: inherit;
}
}
.btn-group:first-child {
.btn:first-child {
-webkit-border-radius: 4px 0 0 4px;
-moz-border-radius: 4px 0 0 4px;
border-radius: 4px 0 0 4px;
}
}
.btn-group {
.btn:first-child {
-webkit-border-radius: 0;
-moz-border-radius: 0;
border-radius: 0;
}
}
}
.btn-input-dec,
.btn-input-enc {
//font-size: 80%;
}
.control-group.error .input-prepend .fileinput-button,
@@ -1243,10 +1305,25 @@ _::-webkit-full-page-media, _:future, :root .full-sized-box {
border-color: #b94a48;
}
.control-text {
// like control-label, but without cursor, float, width or text-align
padding-top: 5px;
cursor: default;
}
input[type=number] {
text-align: right;
}
input[type="number"].input-nospin::-webkit-outer-spin-button,
input[type="number"].input-nospin::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
input[type="number"].input-nospin {
-moz-appearance: textfield;
}
// Progress bars with text
//
// .progress-text-front will also need to have the full width of the enclosing
@@ -29,6 +29,18 @@
<textarea rows="4" class="block" data-bind="value: scripts_gcode_beforePrintResumed"></textarea>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Before tool change') }}</label>
<div class="controls">
<textarea rows="4" class="block" data-bind="value: scripts_gcode_beforeToolChange"></textarea>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('After tool change') }}</label>
<div class="controls">
<textarea rows="4" class="block" data-bind="value: scripts_gcode_afterToolChange"></textarea>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('After connection to printer is established') }}</label>
<div class="controls">
@@ -39,7 +51,7 @@
<label class="control-label">{{ _('Before connection to printer is closed') }}</label>
<div class="controls">
<textarea rows="4" class="block" data-bind="value: scripts_gcode_beforePrinterDisconnected"></textarea>
<small>{{ _('This will only be executed when closing the connection actively. If the connection to the printer is suddenly lost nothing will be sent.') }}</small>
</div>
<small>{{ _('This will only be executed when closing the connection actively. If the connection to the printer is suddenly lost nothing will be sent.') }}</small>
</div>
</form>
@@ -1,5 +1,5 @@
<form class="form-horizontal">
<h3>{{ _('Temperature Graph') }}</h3>
<h3>{{ _('Graph') }}</h3>
<div class="control-group">
<label class="control-label">{{ _('Graph cutoff') }}</label>
<div class="controls">
@@ -10,7 +10,26 @@
<span class="help-block">{{ _('Needs a restart of OctoPrint to become active.') }}</span>
</div>
</div>
<h3>{{ _('Temperature Presets') }}</h3>
<h3>{{ _('Fine adjustments') }}</h3>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: temperature_sendAutomatically"> {{ _('Send temperature fine adjustments automatically') }}
</label>
<span class="help-block">{{ _('Enable this to have temperature fine adjustments you do via the + or - button be sent to the printer automatically.') }}</span>
</div>
</div>
<div class="control-group" data-bind="visible: temperature_sendAutomatically">
<label class="control-label">{{ _('Sending delay') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" class="input-mini" min="0" max="30" data-bind="value: temperature_sendAutomaticallyAfter">
<span class="add-on">sec</span>
</div>
<span class="help-block">{{ _('OctoPrint will use this delay to limit the number of sent temperature commands should you perform multiple fine adjustments in a short time.') }}</span>
</div>
</div>
<h3>{{ _('Presets') }}</h3>
<div class="row-fluid">
<div class="offset4 span3"><h4>{{ _('Extruder') }}</h4></div>
<div class="span3"><h4>{{ _('Bed') }}</h4></div>
@@ -0,0 +1,34 @@
<div id="change_offset_dialog" class="modal hide fade">
<div class="modal-header">
<a href="javascript:void(0)" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3 data-bind="text: changingOffset.title"></h3>
</div>
<div class="modal-body">
<p data-bind="text: changingOffset.description"></p>
<form class="form-horizontal">
<div class="control-group">
<label class="control-label">{{ _('Current Offset') }}</label>
<div class="controls">
<label class="control-text" data-bind="html: changingOffset.offset() + ' &deg;C'"></label>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('New Offset') }}</label>
<div class="controls">
<div class="input-prepend input-append">
<button type="button" class="btn btn-input-dec" data-bind="click: $root.decrementChangeOffset" title="{{ _('-1') }}"><i class="fa fa-minus"></i></button>
<input type="number" min="-50" max="50" class="input-mini input-nospin" style="width: 30px" data-bind="value: changingOffset.newOffset, event: { focus: function(d, e) {$root.handleFocus(e, 'target', changingOffset.item);}, keyup: function(d, e) {$root.handleEnter(e, 'offset', changingOffset.item);} }">
<span class="add-on">&deg;C</span>
<button type="button" class="btn btn-input-inc" data-bind="click: $root.incrementChangeOffset" title="{{ _('+1') }}"><i class="fa fa-plus"></i></button>
</div>
<button type="button" class="btn" data-bind="click: $root.deleteChangeOffset" title="{{ _('Delete Offset') }}"><i class="fa fa-trash"></i></button>
<span class="help-block">{{ _('Hint: Hitting <kbd>Enter</kbd> in the input field will also submit the form') }}</span>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<a href="javascript:void(0)" class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Cancel') }}</a>
<a href="javascript:void(0)" class="btn btn-primary" data-bind="click: confirmChangeOffset">{{ _('Submit') }}</a>
</div>
</div>
+2 -1
View File
@@ -92,7 +92,7 @@
{% endfor %}
</ul>
<div class="tab-content">
<div id="tabs_content" class="tab-content">
{% for key in templates.tab.order %}
{% set entry, data = templates.tab.entries[key] %}
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- ko allowBindings: false -->{% endif %}
@@ -131,6 +131,7 @@
{% include 'dialogs/wizard.jinja2' %}
{% include 'dialogs/about.jinja2' %}
{% include 'dialogs/files.jinja2' %}
{% include 'dialogs/temperature.jinja2' %}
<!-- End of dialogs -->
<!-- Overlays -->
+33 -25
View File
@@ -5,12 +5,12 @@
{% endif %}
<div class="row-fluid">
<table class="table table-bordered table-hover" style="table-layout: fixed; width: 100%; margin-top: 20px">
<table id="temperature-table" class="table table-bordered table-hover">
<tr>
<th style="width: 18%"></th>
<th style="width: 12%; text-align: right">{{ _('Actual') }}</th>
<th style="width: 35%">{{ _('Target') }}</th>
<th style="width: 35%">{{ _('Offset') }}</th>
<th class="temperature_tool"></th>
<th class="temperature_actual" title="{{ _('Current actual temperature as reported by your printer') }}">{{ _('Actual') }}</th>
<th class="temperature_target" title="{{ _('Current target temperature as reported by your printer') }}">{{ _('Target') }}</th>
<th class="temperature_offset" title="{{ _('Offset to apply to temperature commands sent from files') }}">{{ _('Offset') }}</th>
</tr>
<!-- ko foreach: tools -->
<tr data-bind="template: { name: 'temprow-template' }"></tr>
@@ -19,37 +19,45 @@
</table>
<script type="text/html" id="temprow-template">
<th style="vertical-align: middle" data-bind="text: name"></th>
<td style="text-align: right; vertical-align: middle" data-bind="html: formatTemperature(actual())"></td>
<td style="vertical-align: middle; overflow: visible">
<div class="input-append">
<input type="number" class="input-mini text-right tempInput" data-bind="attr: {placeholder: cleanTemperature(target()) }, value: newTarget, enable: $root.isOperational() && $root.loginState.isUser(), event: { keyup: function(d, e) {$root.handleEnter(e, 'target', $data);} }">
<span class="add-on">&deg;C</span>
<th class="temperature_tool" data-bind="text: name"></th>
<td class="temperature_actual" data-bind="html: formatTemperature(actual())"></td>
<td class="temperature_target">
<form class="form-inline" style="margin:0" data-bind="submit: function(element) { $root.setTarget($data, element) }">
<div class="input-prepend input-append">
<button type="button" class="btn btn-input-dec" data-bind="click: $root.decrementTarget, enable: $root.isOperational() && $root.loginState.isUser()" title="{{ _('Fine adjust: -1°C') }}"><i class="fa fa-minus"></i></button>
<input type="number" min="0" max="999" class="input-mini input-nospin" style="width: 30px" data-bind="attr: {placeholder: cleanTemperature(target())}, value: newTarget, valueUpdate: 'input', enable: $root.isOperational() && $root.loginState.isUser(), event: { focus: function(d, e) {$root.handleFocus(e, 'target', $data) } }">
<span class="add-on">&deg;C</span>
<button type="button" class="btn btn-input-inc" data-bind="click: $root.incrementTarget, enable: $root.isOperational() && $root.loginState.isUser()" title="{{ _('Fine adjust: +1°C') }}"><i class="fa fa-plus"></i></button>
</div>
<div class="btn-group">
<button type="submit" data-bind="click: $parent.setTarget, enable: $root.isOperational() && $root.loginState.isUser()" class="btn">{{ _('Set') }}</button>
<button class="btn dropdown-toggle" data-toggle="dropdown" data-bind="enable: $root.isOperational() && $root.loginState.isUser()">
<button type="submit" data-bind="enable: $root.isOperational() && $root.loginState.isUser() && $data.newTargetValid()" class="btn btn-primary" title="{{ _('Set') }}"><i class="fa fa-check"></i></button>
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" data-bind="enable: $root.isOperational() && $root.loginState.isUser()">
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li>
<a href="javascript:void(0)" data-bind="click: $root.setTargetToZero">{{ _('Off') }}</a>
</li>
<li class="divider"></li>
<!-- ko foreach: $root.temperature_profiles -->
<li>
<a href="#" data-bind="click: function() {$root.setTargetFromProfile($parent, $data);}, text: 'Set ' + name + ' (' + ($parent.key() == 'bed' ? bed : extruder) + '&deg;C)'"></a>
<a href="javascript:void(0)" data-bind="click: function() {$root.setTargetFromProfile($parent, $data);}, text: 'Set ' + name + ' (' + ($parent.key() == 'bed' ? bed : extruder) + '&deg;C)'"></a>
</li>
<!-- /ko -->
<li class="divider"></li>
<li>
<a href="#" data-bind="click: $root.setTargetToZero">{{ _('Off') }}</a>
</li>
</ul>
</div>
</div>
</form>
</td>
<td style="vertical-align: middle">
<div class="input-append">
<input type="number" min="-50" max="50" class="input-mini text-right tempInput" data-bind="attr: {placeholder: offset}, value: newOffset, enable: $root.isOperational() && $root.loginState.isUser(), event: { keyup: function(d, e) {$root.handleEnter(e, 'offset', $data);} }">
<span class="add-on">&deg;C</span>
<button type="submit" data-bind="click: $root.setOffset, enable: $root.isOperational() && $root.loginState.isUser()" class="btn">{{ _('Set') }}</button>
</div>
<td class="temperature_offset">
<form class="form-inline" style="margin:0">
<div class="input-append">
<span class="input-mini uneditable-input text-right" style="width: 30px" data-bind="text: offset"></span>
<span class="add-on">&deg;C</span>
<button class="btn" title="{{ _('Change Offset') }}" data-bind="click: $root.changeOffset, enable: $root.isOperational() && $root.loginState.isUser()"><i class="fa fa-pencil"></i></button>
<button class="btn" title="{{ _('Delete Offset') }}" data-bind="click: $root.setOffsetToZero, enable: $root.isOperational() && $root.loginState.isUser()"><i class="fa fa-trash"></i></button>
</div>
</form>
</td>
</script>
</div>
+1 -1
View File
@@ -1,5 +1,5 @@
<div class="terminal">
<pre id="terminal-output" class="pre-scrollable" data-bind="foreach: displayedLines, visible: fancyFunctionality()"><span data-bind="text: line, css: {muted: type == 'filtered' || type == 'cut'}"></span></pre>
<pre id="terminal-output" class="pre-scrollable pre-output" data-bind="foreach: displayedLines, visible: fancyFunctionality()"><span data-bind="text: line, css: {muted: type == 'filtered' || type == 'cut'}"></span></pre>
<pre id="terminal-output-lowfi" style="display: none" class="pre-scrollable" data-bind="text: plainLogOutput, visible: !fancyFunctionality()"></pre>
<small class="pull-left" data-bind="visible: fancyFunctionality()"><button class="btn btn-mini" data-bind="click: toggleAutoscroll, css: {active: autoscrollEnabled}">{{ _('Autoscroll') }}</button> <span data-bind="text: lineCount, visible: enableFancyFunctionality"></span></small>
<small class="pull-right" data-bind="visible: fancyFunctionality()"><a href="#" data-bind="click: scrollToEnd">{{ _("Scroll to end") }}</a>&nbsp;|&nbsp;<a href="#" data-bind="click: selectAll">{{ _("Select all") }}</a></small>
+21 -22
View File
@@ -13,12 +13,14 @@ import os
import yaml
import uuid
import wrapt
import logging
from builtins import range, bytes
from octoprint.settings import settings
from octoprint.util import atomic_write, to_str
from octoprint.util import atomic_write, to_str, deprecated
class UserManager(object):
valid_roles = ["user", "admin"]
@@ -58,13 +60,13 @@ class UserManager(object):
if not isinstance(user, SessionUser):
user = SessionUser(user)
self._session_users_by_session[user.get_session()] = user
self._session_users_by_session[user.session] = user
userid = user.get_id()
if not userid in self._sessionids_by_userid:
self._sessionids_by_userid[userid] = set()
self._sessionids_by_userid[userid].add(user.get_session())
self._sessionids_by_userid[userid].add(user.session)
self._logger.debug("Logged in user: %r" % user)
@@ -81,7 +83,7 @@ class UserManager(object):
return
userid = user.get_id()
sessionid = user.get_session()
sessionid = user.session
if userid in self._sessionids_by_userid:
try:
@@ -99,7 +101,7 @@ class UserManager(object):
for session, user in self._session_users_by_session.items():
if not isinstance(user, SessionUser):
continue
if user._created + (24 * 60 * 60) < time.time():
if user.created + (24 * 60 * 60) < time.time():
self.logout_user(user)
@staticmethod
@@ -591,37 +593,34 @@ class AnonymousUser(AnonymousUserMixin):
return FlaskLoginMethodReplacedByBooleanProperty("is_active", lambda: False)
class SessionUser(User):
class SessionUser(wrapt.ObjectProxy):
def __init__(self, user):
self._user = user
wrapt.ObjectProxy.__init__(self, user)
import string
import random
import time
chars = string.ascii_uppercase + string.ascii_lowercase + string.digits
self._session = "".join(random.choice(chars) for _ in range(10))
self._created = time.time()
self._self_session = "".join(random.choice(chars) for _ in range(10))
self._self_created = time.time()
def __getattribute__(self, item):
if item in ("get_session", "update_user", "_user", "_session", "_created"):
return object.__getattribute__(self, item)
else:
return getattr(object.__getattribute__(self, "_user"), item)
@property
def session(self):
return self._self_session
def __setattr__(self, item, value):
if item in ("_user", "_session", "_created"):
return object.__setattr__(self, item, value)
else:
return setattr(self._user, item, value)
@property
def created(self):
return self._self_created
@deprecated("SessionUser.get_session() has been deprecated, use SessionUser.session instead", since="1.3.5")
def get_session(self):
return self._session
return self.session
def update_user(self, user):
self._user = user
self.__wrapped__ = user
def __repr__(self):
return "SessionUser(id=%s,name=%s,active=%r,user=%r,admin=%r,session=%s,created=%s)" % (self.get_id(), self.get_name(), bool(self.is_active), bool(self.is_user), bool(self.is_admin), self._session, self._created)
return "SessionUser({!r},session={},created={})".format(self.__wrapped__, self.session, self.created)
##~~ DummyUser object to use when accessControl is disabled
+61 -13
View File
@@ -174,8 +174,6 @@ def get_class(name):
"""
Retrieves the class object for a given fully qualified class name.
Taken from http://stackoverflow.com/a/452981/2028598.
Arguments:
name (string): The fully qualified class name, including all modules separated by ``.``
@@ -183,15 +181,17 @@ def get_class(name):
type: The class if it could be found.
Raises:
AttributeError: The class could not be found.
ImportError
"""
parts = name.split(".")
module = ".".join(parts[:-1])
m = __import__(module)
for comp in parts[1:]:
m = getattr(m, comp)
return m
import importlib
mod_name, cls_name = name.rsplit(".", 1)
m = importlib.import_module(mod_name)
try:
return getattr(m, cls_name)
except AttributeError:
raise ImportError("No module named " + name)
def get_exception_string():
@@ -1046,19 +1046,58 @@ class InvariantContainer(object):
return self._data.__iter__()
class TypedQueue(queue.Queue):
class PrependQueue(queue.Queue):
def __init__(self, maxsize=0):
queue.Queue.__init__(self, maxsize=maxsize)
def prepend(self, item, block=True, timeout=True):
from time import time as _time
self.not_full.acquire()
try:
if self.maxsize > 0:
if not block:
if self._qsize() == self.maxsize:
raise queue.Full
elif timeout is None:
while self._qsize() >= self.maxsize:
self.not_full.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a non-negative number")
else:
endtime = _time() + timeout
while self._qsize() == self.maxsize:
remaining = endtime - _time()
if remaining <= 0.0:
raise queue.Full
self.not_full.wait(remaining)
self._prepend(item)
self.unfinished_tasks += 1
self.not_empty.notify()
finally:
self.not_full.release()
def _prepend(self, item):
self.queue.appendleft(item)
class TypedQueue(PrependQueue):
def __init__(self, maxsize=0):
PrependQueue.__init__(self, maxsize=maxsize)
self._lookup = set()
def put(self, item, item_type=None, *args, **kwargs):
queue.Queue.put(self, (item, item_type), *args, **kwargs)
PrependQueue.put(self, (item, item_type), *args, **kwargs)
def get(self, *args, **kwargs):
item, _ = queue.Queue.get(self, *args, **kwargs)
item, _ = PrependQueue.get(self, *args, **kwargs)
return item
def prepend(self, item, item_type=None, *args, **kwargs):
PrependQueue.prepend(self, (item, item_type), *args, **kwargs)
def _put(self, item):
_, item_type = item
if item_type is not None:
@@ -1070,7 +1109,7 @@ class TypedQueue(queue.Queue):
queue.Queue._put(self, item)
def _get(self):
item = queue.Queue._get(self)
item = PrependQueue._get(self)
_, item_type = item
if item_type is not None:
@@ -1078,6 +1117,15 @@ class TypedQueue(queue.Queue):
return item
def _prepend(self, item):
_, item_type = item
if item_type is not None:
if item_type in self._lookup:
raise TypeAlreadyInQueue(item_type, "Type {} is already in queue".format(item_type))
else:
self._lookup.add(item_type)
PrependQueue._prepend(self, item)
class TypeAlreadyInQueue(Exception):
def __init__(self, t, *args, **kwargs):
+151 -93
View File
@@ -19,6 +19,7 @@ from past.builtins import basestring
import logging
import serial
import octoprint.plugin
from collections import deque
@@ -242,6 +243,62 @@ class PositionRecord(object):
t=self.t,
f=self.f)
class TemperatureRecord(object):
def __init__(self):
self._tools = dict()
self._bed = (None, None)
def copy_from(self, other):
self._tools = other.tools
self._bed = other.bed
def set_tool(self, tool, actual=None, target=None):
current = self._tools.get(tool, (None, None))
self._tools[tool] = self._to_new_tuple(current, actual, target)
def set_bed(self, actual=None, target=None):
current = self._bed
self._bed = self._to_new_tuple(current, actual, target)
@property
def tools(self):
return dict(self._tools)
@property
def bed(self):
return self._bed
def as_script_dict(self):
result = dict()
tools = self.tools
for tool, data in tools.items():
result[tool] = dict(actual=data[0],
target=data[1])
bed = self.bed
result["b"] = dict(actual=bed[0],
target=bed[1])
return result
@classmethod
def _to_new_tuple(cls, current, actual, target):
if current is None or not isinstance(current, tuple) or len(current) != 2:
current = (None, None)
if actual is None and target is None:
return current
old_actual, old_target = current
if actual is None:
return old_actual, target
elif target is None:
return actual, old_target
else:
return actual, target
class MachineCom(object):
STATE_NONE = 0
STATE_OPEN_SERIAL = 1
@@ -281,8 +338,6 @@ class MachineCom(object):
self._serial = None
self._baudrateDetectList = baudrateList()
self._baudrateDetectRetry = 0
self._temp = {}
self._bedTemp = None
self._temperatureTargetSetThreshold = 25
self._tempOffsets = dict()
self._command_queue = TypedQueue()
@@ -396,11 +451,16 @@ class MachineCom(object):
self._ignore_select = False
self._manualStreaming = False
self.last_temperature = TemperatureRecord()
self.pause_temperature = TemperatureRecord()
self.cancel_temperature = TemperatureRecord()
self.last_position = PositionRecord()
self.pause_position = PositionRecord()
self._record_pause_position = False
self.cancel_position = PositionRecord()
self._record_cancel_position = False
self._record_pause_data = False
self._record_cancel_data = False
# print job
self._currentFile = None
@@ -579,10 +639,10 @@ class MachineCom(object):
return cleanedPrintTime
def getTemp(self):
return self._temp
return self.last_temperature.tools
def getBedTemp(self):
return self._bedTemp
return self.last_temperature.bed
def getOffsets(self):
return dict(self._tempOffsets)
@@ -695,31 +755,29 @@ class MachineCom(object):
elif self.isOperational() or force:
return self._sendCommand(cmd, cmd_type=cmd_type, on_sent=on_sent)
def sendGcodeScript(self, scriptName, replacements=None):
def _getGcodeScript(self, scriptName, replacements=None):
context = dict()
if replacements is not None and isinstance(replacements, dict):
context.update(replacements)
context.update(dict(
printer_profile=self._printerProfileManager.get_current_or_default(),
last_position=self.last_position
last_position=self.last_position,
last_temperature=self.last_temperature.as_script_dict()
))
if scriptName == "afterPrintPaused" or scriptName == "beforePrintResumed":
context.update(dict(pause_position=self.pause_position))
context.update(dict(pause_position=self.pause_position,
pause_temperature=self.pause_temperature.as_script_dict()))
elif scriptName == "afterPrintCancelled":
context.update(dict(cancel_position=self.cancel_position))
context.update(dict(cancel_position=self.cancel_position,
cancel_temperature=self.cancel_temperature.as_script_dict()))
template = settings().loadScript("gcode", scriptName, context=context)
if template is None:
scriptLines = []
else:
scriptLines = filter(
lambda x: x is not None and x.strip() != "",
map(
lambda x: process_gcode_line(x, offsets=self._tempOffsets, current_tool=self._currentTool),
template.split("\n")
)
)
scriptLines = template.split("\n")
for hook in self._gcodescript_hooks:
try:
@@ -749,6 +807,13 @@ class MachineCom(object):
if suffix:
scriptLines += list(suffix)
return filter(lambda x: x is not None and x.strip() != "",
map(lambda x: process_gcode_line(x, offsets=self._tempOffsets, current_tool=self._currentTool),
scriptLines))
def sendGcodeScript(self, scriptName, replacements=None):
scriptLines = self._getGcodeScript(scriptName, replacements=replacements)
for line in scriptLines:
self.sendCommand(line)
return "\n".join(scriptLines)
@@ -864,7 +929,7 @@ class MachineCom(object):
# we don't call on_print_job_cancelled on our callback here
# because we do this only after our M114 has been answered
# by the firmware
self._record_cancel_position = True
self._record_cancel_data = True
self.sendCommand("M114")
with self._jobLock:
@@ -924,7 +989,7 @@ class MachineCom(object):
# we don't call on_print_job_paused on our callback here
# because we do this only after our M114 has been answered
# by the firmware
self._record_pause_position = True
self._record_pause_data = True
self.sendCommand("M114")
self.sendCommand("M400", on_sent=_on_M400_sent)
@@ -1025,24 +1090,12 @@ class MachineCom(object):
continue
actual, target = parsedTemps[tool]
if target is not None:
self._temp[n] = (actual, target)
elif n in self._temp and self._temp[n] is not None and isinstance(self._temp[n], tuple):
(oldActual, oldTarget) = self._temp[n]
self._temp[n] = (actual, oldTarget)
else:
self._temp[n] = (actual, None)
self.last_temperature.set_tool(n, actual=actual, target=target)
# bed temperature
if "B" in parsedTemps.keys():
actual, target = parsedTemps["B"]
if target is not None:
self._bedTemp = (actual, target)
elif self._bedTemp is not None and isinstance(self._bedTemp, tuple):
(oldActual, oldTarget) = self._bedTemp
self._bedTemp = (actual, oldTarget)
else:
self._bedTemp = (actual, None)
self.last_temperature.set_bed(actual=actual, target=target)
##~~ Serial monitor processing received messages
@@ -1205,16 +1258,18 @@ class MachineCom(object):
reason = None
if self._record_pause_position:
if self._record_pause_data:
reason = "pause"
self._record_pause_position = False
self._record_pause_data = False
self.pause_position.copy_from(self.last_position)
self.pause_temperature.copy_from(self.last_temperature)
self._pause_preparation_done()
if self._record_cancel_position:
if self._record_cancel_data:
reason = "cancel"
self._record_cancel_position = False
self._record_cancel_data = False
self.cancel_position.copy_from(self.last_position)
self.cancel_temperature.copy_from(self.last_temperature)
self._cancel_preparation_done()
self._callback.on_comm_position_update(self.last_position.as_dict(), reason=reason)
@@ -1231,7 +1286,7 @@ class MachineCom(object):
self._heatupWaitStartTime = time.time()
self._processTemperatures(line)
self._callback.on_comm_temperature_update(self._temp, self._bedTemp)
self._callback.on_comm_temperature_update(self.last_temperature.tools, self.last_temperature.bed)
elif supportRepetierTargetTemp and ('TargetExtr' in line or 'TargetBed' in line):
matchExtr = regex_repetierTempExtr.match(line)
@@ -1241,23 +1296,15 @@ class MachineCom(object):
toolNum = int(matchExtr.group(1))
try:
target = float(matchExtr.group(2))
if toolNum in self._temp.keys() and self._temp[toolNum] is not None and isinstance(self._temp[toolNum], tuple):
(actual, oldTarget) = self._temp[toolNum]
self._temp[toolNum] = (actual, target)
else:
self._temp[toolNum] = (None, target)
self._callback.on_comm_temperature_update(self._temp, self._bedTemp)
self.last_temperature.set_tool(toolNum, target=target)
self._callback.on_comm_temperature_update(self.last_temperature.tools, self.last_temperature.bed)
except ValueError:
pass
elif matchBed is not None:
try:
target = float(matchBed.group(1))
if self._bedTemp is not None and isinstance(self._bedTemp, tuple):
(actual, oldTarget) = self._bedTemp
self._bedTemp = (actual, target)
else:
self._bedTemp = (None, target)
self._callback.on_comm_temperature_update(self._temp, self._bedTemp)
self.last_temperature.set_bed(target=target)
self._callback.on_comm_temperature_update(self.last_temperature.tools, self.last_temperature.bed)
except ValueError:
pass
@@ -1285,7 +1332,7 @@ class MachineCom(object):
firmware_name = firmware_name.strip()
self._logger.info("Printer reports firmware name \"{}\"".format(firmware_name))
if "repetier" in firmware_name.lower():
if "repetier" in firmware_name.lower() or "anet_a8" in firmware_name.lower():
self._logger.info("Detected Repetier firmware, enabling relevant features for issue free communication")
self._alwaysSendChecksum = True
@@ -1692,11 +1739,13 @@ class MachineCom(object):
if self.isBusy():
return self._timeout_intervals.get("temperature", busy_default)
for temp in [self._temp[k][1] for k in self._temp.keys()]:
tools = self.last_temperature.tools
for temp in [tools[k][1] for k in tools.keys()]:
if temp > self._temperatureTargetSetThreshold:
return self._timeout_intervals.get("temperatureTargetSet", target_default)
if self._bedTemp and len(self._bedTemp) > 0 and self._bedTemp[1] > self._temperatureTargetSetThreshold:
bed = self.last_temperature.bed
if bed and len(bed) > 0 and bed[1] > self._temperatureTargetSetThreshold:
return self._timeout_intervals.get("temperatureTargetSet", target_default)
return self._timeout_intervals.get("temperature", busy_default)
@@ -2120,16 +2169,19 @@ class MachineCom(object):
def _enqueue_for_sending(self, command, linenumber=None, command_type=None, on_sent=None):
"""
Enqueues a command an optional linenumber to use for it in the send queue.
Enqueues a command and optional linenumber to use for it in the send queue.
Arguments:
command (str): The command to send.
linenumber (int): The line number with which to send the command. May be ``None`` in which case the command
will be sent without a line number and checksum.
command_type (str): Optional command type, if set and command type is already in the queue the
command won't be enqueued
on_sent (callable): Optional callable to call after command has been sent to printer.
"""
try:
self._send_queue.put((command, linenumber, command_type, on_sent), item_type=command_type)
self._send_queue.put((command, linenumber, command_type, on_sent, False), item_type=command_type)
return True
except TypeAlreadyInQueue as e:
self._logger.debug("Type already in send queue: " + e.type)
@@ -2160,7 +2212,7 @@ class MachineCom(object):
self._dwelling_until = False
# fetch command, command type and optional linenumber and sent callback from queue
command, linenumber, command_type, on_sent = entry
command, linenumber, command_type, on_sent, processed = entry
# some firmwares (e.g. Smoothie) might support additional in-band communication that will not
# stick to the acknowledgement behaviour of GCODE, so we check here if we have a GCODE command
@@ -2173,28 +2225,35 @@ class MachineCom(object):
self._do_send_with_checksum(command, linenumber)
else:
# trigger "sending" phase
results = self._process_command_phase("sending", command, command_type, gcode=gcode)
if not processed:
# trigger "sending" phase if we didn't so far
results = self._process_command_phase("sending", command, command_type, gcode=gcode)
if not results:
# No, we are not going to send this, that was a last-minute bail.
# However, since we already are in the send queue, our _monitor
# loop won't be triggered with the reply from this unsent command
# now, so we try to tickle the processing of any active
# command queues manually
self._continue_sending()
if not results:
# No, we are not going to send this, that was a last-minute bail.
# However, since we already are in the send queue, our _monitor
# loop won't be triggered with the reply from this unsent command
# now, so we try to tickle the processing of any active
# command queues manually
self._continue_sending()
# and now let's fetch the next item from the queue
continue
# and now let's fetch the next item from the queue
continue
# we explicitly throw away plugin hook results that try
# to perform command expansion in the sending/sent phase,
# so "results" really should only have more than one entry
# at this point if our core code contains a bug
assert len(results) == 1
if len(results) > 1:
# last command gets on_sent attached
last = results[-1]
self._send_queue.prepend((last[0], None, None, on_sent, True))
on_sent = None
# we only use the first (and only!) entry here
command, _, gcode = results[0]
# middle gets prepended reversed (so order gets restored)
if len(results) > 2:
to_prepend = reversed(results[1:-1])
for m in to_prepend:
self._send_queue.prepend((m[0], None, None, None, True))
# we only actually send the first entry here
command, _, gcode = results[0]
if command.strip() == "":
self._logger.info("Refusing to send an empty line to the printer")
@@ -2268,13 +2327,7 @@ class MachineCom(object):
self._logger.exception("Error while processing hook {name} for phase {phase} and command {command}:".format(**locals()))
else:
normalized = _normalize_command_handler_result(command, command_type, gcode, hook_results)
# make sure we don't allow multi entry results in anything but the queuing phase
if not phase in ("queuing",) and len(normalized) > 1:
self._logger.error("Error while processing hook {name} for phase {phase} and command {command}: Hook returned multi-entry result for phase {phase} and command {command}. That's not supported, if you need to do multi expansion of commands you need to do this in the queuing phase. Ignoring hook result and sending command as-is.".format(**locals()))
new_results.append((command, command_type, gcode))
else:
new_results += normalized
new_results += normalized
if not new_results:
# hook handler returned None or empty list for all commands, so we'll stop here and return a full out empty result
return []
@@ -2392,10 +2445,23 @@ class MachineCom(object):
##~~ command handlers
def _gcode_T_queuing(self, cmd, cmd_type=None):
toolMatch = regexes_parameters["intT"].search(cmd)
if toolMatch:
current_tool = self._currentTool
new_tool = int(toolMatch.group("value"))
before = self._getGcodeScript("beforeToolChange", replacements=dict(tool=dict(old=current_tool, new=new_tool)))
after = self._getGcodeScript("afterToolChange", replacements=dict(tool=dict(old=current_tool, new=new_tool)))
return before + [cmd] + after
def _gcode_T_sent(self, cmd, cmd_type=None):
toolMatch = regexes_parameters["intT"].search(cmd)
if toolMatch:
old = self._currentTool
self._currentTool = int(toolMatch.group("value"))
eventManager().fire(Events.TOOL_CHANGE, dict(old=old, new=self._currentTool))
def _gcode_G0_sent(self, cmd, cmd_type=None):
if "Z" in cmd or "F" in cmd:
@@ -2475,12 +2541,8 @@ class MachineCom(object):
if match:
try:
target = float(match.group("value"))
if toolNum in self._temp.keys() and self._temp[toolNum] is not None and isinstance(self._temp[toolNum], tuple):
(actual, oldTarget) = self._temp[toolNum]
self._temp[toolNum] = (actual, target)
else:
self._temp[toolNum] = (None, target)
self._callback.on_comm_temperature_update(self._temp, self._bedTemp)
self.last_temperature.set_tool(toolNum, target=target)
self._callback.on_comm_temperature_update(self.last_temperature.tools, self.last_temperature.bed)
except ValueError:
pass
@@ -2492,12 +2554,8 @@ class MachineCom(object):
if match:
try:
target = float(match.group("value"))
if self._bedTemp is not None and isinstance(self._bedTemp, tuple):
(actual, oldTarget) = self._bedTemp
self._bedTemp = (actual, target)
else:
self._bedTemp = (None, target)
self._callback.on_comm_temperature_update(self._temp, self._bedTemp)
self.last_temperature.set_bed(target=target)
self._callback.on_comm_temperature_update(self.last_temperature.tools, self.last_temperature.bed)
except ValueError:
pass
+110 -20
View File
@@ -10,8 +10,7 @@ import os
import base64
import zlib
import logging
from octoprint.settings import settings
import codecs
class Vector3D(object):
@@ -178,18 +177,18 @@ class AnalysisAborted(Exception):
class gcode(object):
def __init__(self):
def __init__(self, progress_callback=None):
self._logger = logging.getLogger(__name__)
self.layerList = None
self.extrusionAmount = [0]
self.extrusionVolume = [0]
self.totalMoveTimeMinute = 0
self.filename = None
self.progressCallback = None
self._abort = False
self._reenqueue = True
self._filamentDiameter = 0
self._minMax = MinMax3D()
self._progress_callback = progress_callback
@property
def dimensions(self):
@@ -207,20 +206,19 @@ class gcode(object):
maxY=self._minMax.max.y,
maxZ=self._minMax.max.z)
def load(self, filename, printer_profile, throttle=None):
def load(self, filename, throttle=None, speedx=6000, speedy=6000, offsets=None, max_extruders=10, g90_extruder=False):
if os.path.isfile(filename):
self.filename = filename
self._fileSize = os.stat(filename).st_size
import codecs
with codecs.open(filename, encoding="utf-8", errors="replace") as f:
self._load(f, printer_profile, throttle=throttle)
self._load(f, throttle=throttle, speedx=speedx, speedy=speedy, offsets=offsets, max_extruders=max_extruders, g90_extruder=g90_extruder)
def abort(self, reenqueue=True):
self._abort = True
self._reenqueue = reenqueue
def _load(self, gcodeFile, printer_profile, throttle=None):
def _load(self, gcodeFile, throttle=None, speedx=6000, speedy=6000, offsets=None, max_extruders=10, g90_extruder=False):
lineNo = 0
readBytes = 0
pos = Vector3D(0.0, 0.0, 0.0)
@@ -236,21 +234,23 @@ class gcode(object):
fwretractTime = 0
fwretractDist = 0
fwrecoverTime = 0
feedrate = min(printer_profile["axes"]["x"]["speed"], printer_profile["axes"]["y"]["speed"])
feedrate = min(speedx, speedy)
if feedrate == 0:
# some somewhat sane default if axes speeds are insane...
feedrate = 2000
offsets = printer_profile["extruder"]["offsets"]
g90InfluencesExtruder = settings().getBoolean(["feature", "g90InfluencesExtruder"])
if offsets is None or not isinstance(offsets, (list, tuple)):
offsets = []
if len(offsets) < max_extruders:
offsets += [(0, 0)] * (max_extruders - len(offsets))
for line in gcodeFile:
if self._abort:
raise AnalysisAborted(reenqueue=self._reenqueue)
lineNo += 1
readBytes += len(line)
readBytes += len(line.encode("utf-8"))
if isinstance(gcodeFile, (file)):
if isinstance(gcodeFile, (file, codecs.StreamReaderWriter)):
percentage = float(readBytes) / float(self._fileSize)
elif isinstance(gcodeFile, (list)):
percentage = float(lineNo) / float(len(gcodeFile))
@@ -258,8 +258,8 @@ class gcode(object):
percentage = None
try:
if self.progressCallback is not None and (lineNo % 1000 == 0) and percentage is not None:
self.progressCallback(percentage)
if self._progress_callback is not None and (lineNo % 1000 == 0) and percentage is not None:
self._progress_callback(percentage)
except:
pass
@@ -395,11 +395,11 @@ class gcode(object):
pos.z = center.z
elif G == 90: #Absolute position
relativeMode = False
if g90InfluencesExtruder:
if g90_extruder:
relativeE = False
elif G == 91: #Relative position
relativeMode = True
if g90InfluencesExtruder:
if g90_extruder:
relativeE = True
elif G == 92:
x = getCodeFloat(line, 'X')
@@ -440,7 +440,7 @@ class gcode(object):
fwrecoverTime = (fwretractDist + s) / f
elif T is not None:
if T > settings().getInt(["gcodeAnalysis", "maxExtruders"]):
if T > max_extruders:
self._logger.warn("GCODE tried to select tool %d, that looks wrong, ignoring for GCODE analysis" % T)
else:
toolOffset.x -= offsets[currentExtruder][0] if currentExtruder < len(offsets) else 0
@@ -463,8 +463,8 @@ class gcode(object):
if throttle is not None:
throttle(lineNo, readBytes)
if self.progressCallback is not None:
self.progressCallback(100.0)
if self._progress_callback is not None:
self._progress_callback(100.0)
self.extrusionAmount = maxExtrusion
self.extrusionVolume = [0] * len(maxExtrusion)
@@ -476,6 +476,13 @@ class gcode(object):
def _parseCuraProfileString(self, comment, prefix):
return {key: value for (key, value) in map(lambda x: x.split("=", 1), zlib.decompress(base64.b64decode(comment[len(prefix):])).split("\b"))}
def get_result(self):
return dict(total_time=self.totalMoveTimeMinute,
extrusion_length=self.extrusionAmount,
extrusion_volume=self.extrusionVolume,
dimensions=self.dimensions,
printing_area=self.printing_area)
def getCodeInt(line, code):
n = line.find(code) + 1
if n < 1:
@@ -503,3 +510,86 @@ def getCodeFloat(line, code):
return val if not (math.isnan(val) or math.isinf(val)) else None
except:
return None
if __name__ == "__main__":
import click
import time
import yaml
import sys
@click.command()
@click.option("--throttle", "throttle", type=float, default=None)
@click.option("--throttle-lines", "throttle_lines", type=int, default=None)
@click.option("--speed-x", "speedx", type=float, default=6000)
@click.option("--speed-y", "speedy", type=float, default=6000)
@click.option("--speed-z", "speedz", type=float, default=300)
@click.option("--offset", "offset", type=(float, float), multiple=True)
@click.option("--max-t", "maxt", type=int, default=10)
@click.option("--g90-extruder", "g90_extruder", is_flag=True)
@click.option("--progress", "progress", is_flag=True)
@click.argument("path", type=click.Path())
def main(path, speedx, speedy, speedz, offset, maxt, throttle, throttle_lines, g90_extruder, progress):
throttle_callback = None
if throttle:
def throttle_callback(filePos, readBytes):
if filePos % throttle_lines == 0:
# only apply throttle every $throttle_lines lines
time.sleep(throttle)
offsets = offset
if offsets is None:
offsets = []
elif isinstance(offset, tuple):
offsets = list(offsets)
offsets = [(0, 0)] + offsets
if len(offsets) < maxt:
offsets += [(0, 0)] * (maxt - len(offsets))
start_time = time.time()
progress_callback = None
if progress:
def progress_callback(percentage):
print("PROGRESS:{}".format(percentage))
interpreter = gcode(progress_callback=progress_callback)
interpreter.load(path,
speedx=speedx,
speedy=speedy,
offsets=offsets,
throttle=throttle_callback,
max_extruders=maxt,
g90_extruder=g90_extruder)
print("DONE:{}s".format(time.time() - start_time))
print("RESULTS:")
print(yaml.safe_dump(interpreter.get_result(), default_flow_style=False, indent=" ", allow_unicode=True))
# os args are gained differently on win32
try:
from click.utils import get_os_args
args = get_os_args()
except ImportError:
# for whatever reason we are running an older Click version?
args = sys.argv[1:]
if len(args) >= len(sys.argv):
# Now some ugly preprocessing of our arguments starts. We have a somewhat difficult situation on our hands
# here if we are running under Windows and want to be able to handle utf-8 command line parameters (think
# plugin parameters such as names or something, e.g. for the "dev plugin:new" command) while at the same
# time also supporting sys.argv rewriting for debuggers etc (e.g. PyCharm).
#
# So what we try to do here is solve this... Generally speaking, sys.argv and whatever Windows returns
# for its CommandLineToArgvW win32 function should have the same length. If it doesn't however and
# sys.argv is shorter than the win32 specific command line arguments, obviously stuff was cut off from
# sys.argv which also needs to be cut off of the win32 command line arguments.
#
# So this is what we do here.
# -1 because first entry is the script that was called
sys_args_length = len(sys.argv) - 1
# cut off stuff from the beginning
args = args[-1 * sys_args_length:] if sys_args_length else []
main(args=args, prog_name="octoprint-gcode-analysis")
+84 -1
View File
@@ -1,10 +1,11 @@
import unittest
import mock
import ddt
import octoprint.plugin
import octoprint.plugin.core
@ddt.ddt
class PluginTestCase(unittest.TestCase):
def setUp(self):
@@ -191,3 +192,85 @@ class PluginTestCase(unittest.TestCase):
plugin = self.plugin_manager.enabled_plugins["deprecated_plugin"]
self.assertTrue(hasattr(plugin.instance, plugin.__class__.attr_implementation))
self.assertFalse(hasattr(plugin.instance, plugin.__class__.attr_implementations))
@ddt.data(
(["octoprint.some_hook"], ["octoprint.some_hook", "octoprint.another_hook"], True),
(["octoprint.*"], ["octoprint.some_hook", "octoprint.another_hook"], True),
(["octoprint.some_hook"], ["octoprint.another_hook"], False),
(["octoprint.some_hook"], [], False),
([], ["octoprint.some_hook"], False)
)
@ddt.unpack
def test_has_any_of_hooks(self, hooks_to_test_for, plugin_hooks, expected):
plugin = mock.MagicMock()
plugin.hooks = dict((hook, hook) for hook in plugin_hooks)
actual = octoprint.plugin.core.PluginManager.has_any_of_hooks(plugin, hooks_to_test_for)
self.assertEqual(actual, expected)
def test_has_any_of_hooks_varargs(self):
plugin = mock.MagicMock()
plugin.hooks = dict((hook, hook) for hook in ["octoprint.some_hook", "octoprint.another_hook"])
result = octoprint.plugin.core.PluginManager.has_any_of_hooks(plugin, "octoprint.some_hook", "octoprint.some_other_hook")
self.assertTrue(result)
def test_has_any_of_hooks_nohooks(self):
plugin = mock.MagicMock()
result = octoprint.plugin.core.PluginManager.has_any_of_hooks(plugin, "octoprint.some_hook", "octoprint.some_other_hook")
self.assertFalse(result)
@ddt.data(
("octoprint.some_hook", ["octoprint.another_hook", "octoprint.some_hook"], True),
("octoprint.some_hook", ["octoprint.*"], True),
("octoprint.some_hook", ["octoprint.some_hook*"], True),
("octoprint.some_hook", ["octoprint.*_hook"], True),
("octoprint.some_hook", ["octoprint.another_hook.*"], False),
("", ["octoprint.some_hook"], False),
(None, ["octoprint.some_hook"], False),
("octoprint.some_hook", [], False),
("octoprint.some_hook", None, False),
("octoprint.some_hook", [None], False)
)
@ddt.unpack
def test_hook_matches_hooks(self, hook, hooks, expected):
actual = octoprint.plugin.core.PluginManager.hook_matches_hooks(hook, hooks)
self.assertEqual(actual, expected)
def test_hook_matches_hooks_varargs(self):
result = octoprint.plugin.core.PluginManager.hook_matches_hooks("octoprint.some_hook",
"octoprint.another_hook", "octoprint.some_hook")
self.assertTrue(result)
@ddt.data(
([octoprint.plugin.RestartNeedingPlugin], [octoprint.plugin.Plugin, octoprint.plugin.RestartNeedingPlugin], True),
([octoprint.plugin.RestartNeedingPlugin], [octoprint.plugin.Plugin], False),
([], [octoprint.plugin.Plugin], False),
([octoprint.plugin.RestartNeedingPlugin], [], False)
)
@ddt.unpack
def test_has_any_of_mixins(self, mixins_to_test_for, plugin_mixins, expected):
plugin = mock.MagicMock()
plugin.implementation = mock.MagicMock()
for mixin in plugin_mixins:
plugin.implementation.mock_add_spec(mixin)
actual = octoprint.plugin.core.PluginManager.has_any_of_mixins(plugin, mixins_to_test_for)
self.assertEqual(actual, expected)
def test_has_any_of_mixins_varargs(self):
plugin = mock.MagicMock()
plugin.implementation = mock.MagicMock()
plugin.implementation.mock_add_spec(octoprint.plugin.Plugin)
plugin.implementation.mock_add_spec(octoprint.plugin.RestartNeedingPlugin)
result = octoprint.plugin.core.PluginManager.has_any_of_mixins(plugin, octoprint.plugin.RestartNeedingPlugin)
self.assertTrue(result)
def test_has_any_of_mixins_noimplementation(self):
plugin = mock.MagicMock()
result = octoprint.plugin.core.PluginManager.has_any_of_mixins(plugin, octoprint.plugin.RestartNeedingPlugin)
self.assertFalse(result)
+26 -7
View File
@@ -21,17 +21,36 @@ class SessionUserTestCase(unittest.TestCase):
session1 = octoprint.users.SessionUser(self.user)
session2 = octoprint.users.SessionUser(self.user)
self.assertNotEqual(session1.get_session(), session2.get_session())
self.assertEqual(session1._user, session2._user)
self.assertEqual(session1._username, session2._username)
# session should be different, wrapped object should be identical
self.assertNotEqual(session1.session, session2.session)
self.assertEqual(session1.__wrapped__, session2.__wrapped__)
self.assertEqual(session1.get_name(), session2.get_name())
def test_settings_change_propagates(self):
user = octoprint.users.SessionUser(self.user)
self.user.set_setting("otherkey", "othervalue")
session1 = octoprint.users.SessionUser(self.user)
session2 = octoprint.users.SessionUser(self.user)
self.assertDictEqual(dict(key="value", otherkey="othervalue"), user.get_all_settings())
# change should propagate from User to SessionUser
self.user.set_setting("otherkey", "othervalue")
self.assertDictEqual(dict(key="value", otherkey="othervalue"), session1.get_all_settings())
# change should propagate from SessionUser to SessionUser
session2.set_setting("otherkey", "yetanothervalue")
self.assertDictEqual(dict(key="value", otherkey="yetanothervalue"), session1.get_all_settings())
def test_repr(self):
user = octoprint.users.SessionUser(self.user)
expected = "SessionUser(id=username,name=username,active=True,user=True,admin=False,session={},created={})".format(user._session, user._created)
expected = "SessionUser({!r},session={},created={})".format(self.user, user.session, user.created)
self.assertEqual(expected, repr(user))
def test_isinstance(self):
session = octoprint.users.SessionUser(self.user)
# needs to be detected as User instance
self.assertTrue(isinstance(session, octoprint.users.User))
# also needs to be detected as SessionUser instance
self.assertTrue(isinstance(session, octoprint.users.SessionUser))
# but wrapped user should NOT be detected as SessionUser instance of course
self.assertFalse(isinstance(self.user, octoprint.users.SessionUser))
+31
View File
@@ -0,0 +1,31 @@
# coding=utf-8
from __future__ import absolute_import
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
import unittest
import octoprint.util
class MiscTestCase(unittest.TestCase):
def test_get_class(self):
octoprint.util.get_class("octoprint.users.FilebasedUserManager")
def test_get_class_wrongmodule(self):
try:
octoprint.util.get_class("octoprint2.users.FilebasedUserManager")
self.fail("This should have thrown an ImportError")
except ImportError:
# success
pass
def test_get_class_wrongclass(self):
try:
octoprint.util.get_class("octoprint.users.FilebasedUserManagerBzzztWrong")
self.fail("This should have thrown an ImportError")
except ImportError:
# success
pass