Compare commits

...
Author SHA1 Message Date
Gina Häußge b94e513960 Merge remote-tracking branch 'origin/fix/betterPluginDependencyTracking' into fix/betterPluginDependencyTracking 2017-07-05 12:42:27 +02:00
Gina Häußge 875f69ea50 Fixed a unit test 2017-07-05 12:41:17 +02:00
Gina Häußge 5b7639590c Minor refactoring 2017-07-05 12:30:15 +02:00
Gina Häußge 2cd627ec6a Merge branch 'maintenance' into fix/betterPluginDependencyTracking
# Conflicts:
#	src/octoprint/plugin/__init__.py
#	src/octoprint/plugin/core.py
#	src/octoprint/plugins/pluginmanager/__init__.py
#	src/octoprint/plugins/softwareupdate/version_checks/github_release.py
2017-07-05 11:35:54 +02:00
Gina Häußge 3cdc59d7f1 Fix offset passing to analysis subprocess 2017-07-05 08:58:42 +02:00
Gina Häußge 5156cdbe68 Very minor refactoring & cleanup 2017-07-05 08:58:08 +02:00
Gina Häußge 0915c45f72 Merge branch 'maintenance' of github.com:foosel/OctoPrint into maintenance 2017-07-04 16:48:42 +02:00
Gina Häußge b2c1bb4b53 Option to automatically send temperature fine adjustments
As suggested by a loyal Patron ;)
2017-07-04 16:44:23 +02:00
Gina Häußge 8ad165c625 Fix blur of temp input focus on submit
Also separated "clear offset" button in offset editor from input
field, looks better this way.
2017-07-03 16:08:41 +02:00
Gina Häußge 841b86a017 Merge branch 'maintenance' into improve/temperatureInput 2017-07-03 16:07:19 +02:00
Mark Walker c0c249ece9 Typo: red->read 2017-07-01 10:37:51 -07:00
Gina Häußge 5fc194accd Docs: Added sequence diagrams for web interface lifecycle
For now only startup and reconnect to server.
2017-06-30 18:28:49 +02:00
Gina Häußge ed6c01c12a Remove current_user from template contexts
That should never have been enabled for our usage scenario in the
first place.
2017-06-30 14:37:37 +02:00
Gina Häußge e309646504 Prevent unnecessary settings fetch during startup
We fetch settings once explicitly after passive login but before
completed startup. Without this patch we fetched them again after
onUserLoggedIn got fired (if it got fired by the passive login)
during startup. That's not necessary because we did the passive login
before our initial settings fetch, so IF that already logged us in,
our settings fetch already was done with us logged in as well and
the onUserLoggedIn later only tells us what we already knew.
2017-06-30 14:36:18 +02:00
Gina Häußge 96ee80afd2 Only trigger onUserLogged(In|Out) if login state actually changed
This also includes triggering an initial onUserLoggedIn after
initialization if the user turned out to be logged in by passive login.
2017-06-30 14:34:05 +02:00
Gina Häußge 8aec836d22 Minor refactoring of the web interface startup (again)
We still had some concurrent requests triggered through onStartup that
managed to overtake the passive login (and hence nuke the session
data on the client). This should now really not be possible any longer.

Also created a sequence diagram of the new process and linked it from
a lengthy comment.
2017-06-30 11:59:52 +02:00
Gina Häußge a3ece229f2 Fixed button types & update displayed current offset in dialog 2017-06-21 12:40:59 +02:00
Gina Häußge fc53febb87 WIP: Improved temperature controls 2017-06-20 16:53:41 +02:00
Gina Häußge 2aa74866ac Match OctoPrint version against required one from plugin setup.py requires 2016-01-20 17:42:20 +01:00
Gina Häußge 3764eec9eb Allow defining required OctoPrint versions in setup_requires 2016-01-20 17:18:45 +01:00
Gina Häußge 083601c978 Extracted version matching against specs into utility methods
Adjusted plugin manager and software update plugin to utilize new methods in
octoprint.util.version
2016-01-20 16:59:46 +01:00
28 changed files with 1133 additions and 243 deletions

No files matched your search

+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.
+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)
+3 -2
View File
@@ -65,9 +65,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 -1
View File
@@ -329,7 +329,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
"--max-t={}".format(max_extruders), "--throttle={}".format(throttle),
"--throttle-lines={}".format(throttle_lines)]
for offset in offsets[1:]:
command += ["--offset", offset[0], offset[1]]
command += ["--offset", str(offset[0]), str(offset[1])]
if g90_extruder:
command += ["--g90-extruder"]
command.append(self._current.absolute_path)
+25 -8
View File
@@ -45,7 +45,8 @@ def _validate_plugin(phase, plugin_info):
return True
def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_entry_points=None, plugin_disabled_list=None,
plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, plugin_validators=None):
plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, plugin_validators=None,
plugin_checked_module_dependencies=None):
"""
Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.plugin.core.PluginManager`
singleton.
@@ -71,6 +72,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
plugin_obsolete_hooks (list): A list of hooks that have been declared obsolete. Plugins implementing them will
not be enabled since they might depend on functionality that is no longer available.
plugin_validators (list): A list of additional plugin validators through which to process each plugin.
plugin_checked_module_dependencies (dict): A dictionary of package name-version-pairs for which to enable
dependency checking during plugin loading.
Returns:
PluginManager: A fully initialized :class:`~octoprint.plugin.core.PluginManager` instance to be used for plugin
@@ -114,6 +117,9 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
plugin_validators = [_validate_plugin]
else:
plugin_validators.append(_validate_plugin)
if plugin_checked_module_dependencies is None:
from octoprint import __version__ as octoprint_version
plugin_checked_module_dependencies = dict(octoprint=octoprint_version)
_instance = PluginManager(plugin_folders,
plugin_types,
@@ -122,7 +128,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
plugin_disabled_list=plugin_disabled_list,
plugin_restart_needing_hooks=plugin_restart_needing_hooks,
plugin_obsolete_hooks=plugin_obsolete_hooks,
plugin_validators=plugin_validators)
plugin_validators=plugin_validators,
plugin_checked_module_dependencies=plugin_checked_module_dependencies)
else:
raise ValueError("Plugin Manager not initialized yet")
return _instance
@@ -264,13 +271,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)
@@ -286,13 +297,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)
+20 -2
View File
@@ -41,6 +41,8 @@ try:
except ImportError:
from scandir import scandir
from octoprint.util.version import version_matches_spec
EntryPointOrigin = namedtuple("EntryPointOrigin", "type, entry_point, module_name, package_name, package_version")
FolderOrigin = namedtuple("FolderOrigin", "type, folder")
@@ -464,7 +466,7 @@ class PluginManager(object):
def __init__(self, plugin_folders, plugin_types, plugin_entry_points, logging_prefix=None,
plugin_disabled_list=None, plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None,
plugin_validators=None):
plugin_validators=None, plugin_checked_module_dependencies=None):
self.logger = logging.getLogger(__name__)
if logging_prefix is None:
@@ -485,6 +487,7 @@ class PluginManager(object):
self.plugin_restart_needing_hooks = plugin_restart_needing_hooks
self.plugin_obsolete_hooks = plugin_obsolete_hooks
self.plugin_validators = plugin_validators
self.plugin_dependency_checks = plugin_checked_module_dependencies
self.logging_prefix = logging_prefix
self.enabled_plugins = dict()
@@ -619,6 +622,20 @@ class PluginManager(object):
module_name = entry_point.module_name
version = entry_point.dist.version
if self.plugin_dependency_checks:
requires = entry_point.dist.requires()
missing_requirements = []
for require in requires:
if require.key in self.plugin_dependency_checks:
available_version = self.plugin_dependency_checks[require.key]
spec = str(require.specifier)
if not version_matches_spec(available_version, spec, package=require.key, base=True):
missing_requirements.append("{}{}".format(require.key, spec))
if missing_requirements:
self.logger.warn("Plugin \"{}\" is missing requirements, skipping it: {}".format(key, ", ".join(missing_requirements)))
continue
if key in existing or key in result or (ignore_uninstalled and key in self.marked_plugins["uninstalled"]):
# plugin is already defined or marked as uninstalled, ignore it
continue
@@ -661,7 +678,8 @@ class PluginManager(object):
return result
def _import_plugin_from_module(self, key, folder=None, module_name=None, name=None, version=None, summary=None, author=None, url=None, license=None):
def _import_plugin_from_module(self, key, folder=None, module_name=None, name=None, version=None, summary=None,
author=None, url=None, license=None):
# TODO error handling
try:
if folder:
+18 -45
View File
@@ -14,6 +14,7 @@ from octoprint.settings import valid_boolean_trues
from octoprint.server.util.flask import restricted_access, with_revalidation_checking, check_etag
from octoprint.server import admin_permission, VERSION
from octoprint.util.pip import LocalPipCaller, UnknownPip
from octoprint.util.version import parse_version, version_matches_any_spec
from flask import jsonify, make_response
from flask.ext.babel import gettext
@@ -723,7 +724,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
return False
current_os = self._get_os()
octoprint_version = self._get_octoprint_version(base=True)
parsed_octoprint_version = self._get_octoprint_version()
def map_repository_entry(entry):
result = copy.deepcopy(entry)
@@ -738,7 +739,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
if "compatibility" in entry:
if "octoprint" in entry["compatibility"] and entry["compatibility"]["octoprint"] is not None and isinstance(entry["compatibility"]["octoprint"], (list, tuple)) and len(entry["compatibility"]["octoprint"]):
result["is_compatible"]["octoprint"] = self._is_octoprint_compatible(octoprint_version, entry["compatibility"]["octoprint"])
result["is_compatible"]["octoprint"] = self._is_octoprint_compatible(parsed_octoprint_version, entry["compatibility"]["octoprint"])
if "os" in entry["compatibility"] and entry["compatibility"]["os"] is not None and isinstance(entry["compatibility"]["os"], (list, tuple)) and len(entry["compatibility"]["os"]):
result["is_compatible"]["os"] = self._is_os_compatible(current_os, entry["compatibility"]["os"])
@@ -817,20 +818,15 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
Tests if the current ``octoprint_version`` is compatible to any of the provided ``compatibility_entries``.
"""
for octo_compat in compatibility_entries:
try:
if not any(octo_compat.startswith(c) for c in ("<", "<=", "!=", "==", ">=", ">", "~=", "===")):
octo_compat = ">={}".format(octo_compat)
spec_matcher = ("<", "<=", "!=", "==", ">=", ">", "~=", "===")
specs = map(lambda x: x if any(x.startswith(c) for c in spec_matcher) else ">={}".format(x),
compatibility_entries)
s = next(pkg_resources.parse_requirements("OctoPrint" + octo_compat))
if octoprint_version in s:
break
except:
self._logger.exception("Something is wrong with this compatibility string for OctoPrint: {}".format(octo_compat))
else:
return False
return True
try:
return version_matches_any_spec(octoprint_version, specs, package="OctoPrint", base=True)
except:
self._logger.exception("Something is wrong with these compatibility specs: {!r}".format(specs))
return False
@staticmethod
def _is_os_compatible(current_os, compatibility_entries):
@@ -864,38 +860,15 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
else:
return "unmapped"
def _get_octoprint_version_string(self):
return VERSION
def _get_octoprint_version(self, base=False):
octoprint_version_string = self._get_octoprint_version_string()
if "-" in octoprint_version_string:
octoprint_version_string = octoprint_version_string[:octoprint_version_string.find("-")]
octoprint_version = pkg_resources.parse_version(octoprint_version_string)
# A leading v is common in github release tags and old setuptools doesn't remove it. While OctoPrint's
# versions should never contains such a prefix, we'll make sure to have stuff behave the same
# regardless of setuptools version anyhow.
if octoprint_version and isinstance(octoprint_version, tuple) and octoprint_version[0].lower() == "*v":
octoprint_version = octoprint_version[1:]
if base:
if isinstance(octoprint_version, tuple):
# old setuptools
base_version = []
for part in octoprint_version:
if part.startswith("*"):
break
base_version.append(part)
base_version.append("*final")
octoprint_version = tuple(base_version)
else:
# new setuptools
octoprint_version = pkg_resources.parse_version(octoprint_version.base_version)
@staticmethod
def _get_octoprint_version_string():
from octoprint import __version__ as octoprint_version
return octoprint_version
@staticmethod
def _get_octoprint_version(base=False):
return parse_version(PluginManagerPlugin._get_octoprint_version_string(), base=base)
@property
def _reconnect_hooks(self):
reconnect_hooks = self.__class__.RECONNECT_HOOKS
@@ -8,6 +8,8 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import requests
import logging
from octoprint.util.version import parse_version
RELEASE_URL = "https://api.github.com/repos/{user}/{repo}/releases"
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.github_release")
@@ -139,44 +141,8 @@ def _get_sanitized_version(version_string):
return version_string
def _get_base_from_version_tuple(version_tuple):
"""
Reduces version tuple to base version.
Tests:
>>> _get_base_from_version_tuple(("1", "2", "15"))
('1', '2', '15')
>>> _get_base_from_version_tuple(("1", "2", "15", "*", "dev12"))
('1', '2', '15')
"""
base_version = []
for part in version_tuple:
if part.startswith("*"):
break
base_version.append(part)
return tuple(base_version)
def _get_comparable_version_pkg_resources(version_string, force_base=True):
import pkg_resources
version = pkg_resources.parse_version(version_string)
# A leading v is common in github release tags and old setuptools doesn't remove it.
if version and isinstance(version, tuple) and version[0].lower() == "*v":
version = version[1:]
if force_base:
if isinstance(version, tuple):
# old setuptools
version = _get_base_from_version_tuple(version)
else:
# new setuptools
version = pkg_resources.parse_version(version.base_version)
return version
return parse_version(version_string, base=force_base)
def _get_comparable_version_semantic(version_string, force_base=True):
+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``
+1 -1
View File
@@ -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()
+5 -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"]),
@@ -388,6 +390,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"])
+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];
}
};
+16
View File
@@ -983,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);
}
+42 -12
View File
@@ -613,6 +613,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) {
@@ -648,30 +649,59 @@ $(function() {
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 with this in place.
viewModelMap["loginStateViewModel"].requestData()
// 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 overriding each other's
// session during app intialization, and has the additional benefit of reducing the
// number of required requests since we don't have re-request data that might have
// changed if we turn out to be logged in.
// 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, onServerConnect);
var dataUpdater = new DataUpdater(allViewModels);
dataUpdater.connect()
.done(function() {
// onServerConnect will have been called just before this.
//
// Decoupled settings fetch, for the reasons see above's lengthy description
// on a weird JQuery AJAX issue with ETag headers and promise handling.
window.setTimeout(fetchSettings, 0);
// make sure we trigger onServerConnect should we dis- and reconnect to the server
dataUpdater.connectCallback = onServerConnect;
// perform passive login first
onServerConnect().done(function() {
// then trigger a settings fetch
window.setTimeout(fetchSettings, 0);
});
});
}
);
@@ -52,16 +52,21 @@ $(function() {
self.fromResponse = function(response) {
var process = function() {
var currentLoggedIn = self.loggedIn();
if (response && response.name) {
self.loggedIn(true);
self.updateCurrentUserData(response);
callViewModels(self.allViewModels, "onUserLoggedIn", [response]);
log.info("User " + response.name + " logged in")
if (!currentLoggedIn) {
callViewModels(self.allViewModels, "onUserLoggedIn", [response]);
log.info("User " + response.name + " logged in")
}
} else {
self.loggedIn(false);
self.resetCurrentUserData();
callViewModels(self.allViewModels, "onUserLoggedOut");
log.info("User logged out");
if (currentLoggedIn) {
callViewModels(self.allViewModels, "onUserLoggedOut");
log.info("User logged out");
}
}
};
@@ -195,6 +195,8 @@ $(function() {
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([]);
@@ -884,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");
@@ -400,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);
}
};
@@ -503,13 +680,28 @@ $(function() {
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;
@@ -531,6 +723,10 @@ $(function() {
}
};
self.onStartup = function() {
self.changeOffsetDialog = $("#change_offset_dialog");
};
self.onStartupComplete = function() {
self._printerProfileUpdated();
};
@@ -540,6 +736,6 @@ $(function() {
OCTOPRINT_VIEWMODELS.push([
TemperatureViewModel,
["loginStateViewModel", "settingsViewModel"],
"#temp"
["#temp", "#change_offset_dialog"]
]);
});
+80 -5
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,
@@ -1238,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,
@@ -1245,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
@@ -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>
+1
View File
@@ -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>
+189
View File
@@ -0,0 +1,189 @@
# coding=utf-8
from __future__ import absolute_import, unicode_literals
__author__ = "Gina Häußge <gina@octoprint.org>"
__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 pkg_resources
from past.builtins import basestring
def _get_base_from_version_tuple(version_tuple):
"""
Reduces the version tuple to base version.
Example::
>>> _get_base_from_version_tuple((b"1", b"2", b"5"))
('1', '2', '5', '*final')
>>> _get_base_from_version_tuple((b"1", b"2", b"15", b"*", b"dev12"))
('1', '2', '15', '*final')
Args:
version_tuple (tuple): the version tuple to reduce to the base version
Returns:
(tuple): a version tuple reduced to base version
"""
assert len(version_tuple) > 0
base_version = []
for part in version_tuple:
if part.startswith("*"):
break
base_version.append(part)
if base_version and base_version[-1] != b'*final':
base_version.append(b'*final')
return tuple(base_version)
def parse_version(version_string, base=False):
"""
Parses the given ``version_string`` using ``pkg_resources.parse_version``
If ``base`` is ``True``, the version will be reduced to the base version (e.g. ``1.2.0.dev.123`` will be reduced
to ``1.2.0``) before returning.
If a ``-`` is contains in the version string, it and any following parts of the version stirng will be stripped
(e.g. ``1.2.0-dev-123`` is turned into ``1.2.0``) to ensure the string is parsable using ``pkg_resources``.
Parameters:
version_string (str, unicode): the version string to parse
base (boolean): whether to reduce the version to the base version before returning
Returns:
(tuple or object): the parsed version, as either a tuple or a ``setuptools`` version object, depending on the
installed ``setuptools`` version
"""
assert isinstance(version_string, basestring)
if "-" in version_string:
version_string = version_string[:version_string.find("-")]
try:
version = pkg_resources.parse_version(version_string)
except:
raise ValueError("Invalid version: {!r}".format(version_string))
# A leading v is common in github release tags and old setuptools doesn't remove it.
if version and isinstance(version, tuple) and version[0].lower() == "*v":
version = version[1:]
if base:
if isinstance(version, tuple):
# old setuptools
version = _get_base_from_version_tuple(version)
else:
# new setuptools
version = pkg_resources.parse_version(version.base_version)
return version
def version_matches_any_spec(version, specs, package=None, base=False):
"""
Checks if the supplied version matches any of the supplied specs.
See `Requirements Parsing <https://pythonhosted.org/setuptools/pkg_resources.html#requirements-parsing>`_ for
details on the format. The version spec does not need to start with ``package``, it will be added automatically
if it's missing.
Example::
>>> version_matches_any_spec("1.2.0", ["Foo>=1.1.0,<1.2.0", "Foo>=1.2.0,<1.3.0", "Foo>=1.3.0"])
True
>>> version_matches_any_spec("1.2.0", ["Foo>=1.1.0,<1.2.0", "Foo>=1.3.0"])
False
Arguments:
version (str, unicode, parsed version): version to check
specs (list of str or unicode): version specs to check against
package (str or unicode): name of the package to use in the spec
base (boolean): If True, only check the base version of the version against the spec. Defaults
to False.
Returns:
(boolean) True if the version matches any of the version specs, False otherwise.
"""
if isinstance(version, basestring):
version = parse_version(version, base=base)
for spec in specs:
if package is not None and not spec.lower().startswith(package.lower()):
spec = package.lower() + spec
try:
parsed_spec = next(pkg_resources.parse_requirements(spec))
except:
raise ValueError("Invalid spec: {!r}".format(spec))
if version in parsed_spec:
return True
else:
return False
def version_matches_spec(version, spec, package=None, base=False):
"""
Checks if the supplied version matches the supplied spec.
See `Requirements Parsing <https://pythonhosted.org/setuptools/pkg_resources.html#requirements-parsing>`_ for
details on the format. The version spec does not need to start with ``package``, it will be added automatically
if it's missing.
Example::
>>> version_matches_spec("1.2.0", "Foo>=1.2.0,<1.3.0")
True
>>> version_matches_spec("1.2.0", "Foo>=1.3.0")
False
>>> version_matches_spec("1.2.0", ">=1.2.0,<1.3.0", package="Foo")
True
>>> version_matches_spec("1.2.0.dev.123", ">=1.2.0", package="Foo")
False
>>> version_matches_spec("1.2.0.dev.123", ">=1.2.0", package="Foo", base=True)
True
Arguments:
version (str, unicode, parsed version): version to check
spec (str or unicode): version spec to check against
package (str or unicode): name of the package to use in the spec
base (boolean): If True, only check the base version of the version against the spec. Defaults
to False.
Returns:
(boolean) True if the version matches the version spec, False otherwise.
"""
return version_matches_any_spec(version, [spec], package=package, base=base)
def octoprint_version_matches(spec, base=False):
"""
Checks if the current OctoPrint version matches the provided spec.
See `Requirements Parsing <https://pythonhosted.org/setuptools/pkg_resources.html#requirements-parsing>`_ for
details on the format. The version spec does not need to start with "OctoPrint", it will be added automatically
if it's missing.
Example::
octoprint_version_matches(">=1.2.0")
octoprint_version_matches("OctoPrint>=1.3.0", base=True)
Arguments:
spec (str or unicode): version spec to check against
base (boolean): If True, only check the base version of the OctoPrint version against the spec. Defaults
to False.
Returns:
(boolean) True if the version matches the version spec, False otherwise.
"""
from octoprint import __version__
return version_matches_any_spec(__version__, [spec], package="OctoPrint", base=base)
+5 -1
View File
@@ -480,7 +480,11 @@ def create_plugin_setup_parameters(identifier="todo", name="TODO", version="0.1"
requires = ["OctoPrint"]
if not isinstance(requires, list):
raise ValueError("requires must be a list")
if "OctoPrint" not in requires:
for require in requires:
requirement = pkg_resources.Requirement.parse(require)
if requirement.key == "octoprint":
break
else:
requires = ["OctoPrint"] + list(requires)
if extra_requires is None:
+103
View File
@@ -0,0 +1,103 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
import unittest
import ddt
import mock
from octoprint.util.version import version_matches_spec, version_matches_any_spec, octoprint_version_matches, parse_version
@ddt.ddt
class VersionUtilTest(unittest.TestCase):
@ddt.data(("1.2.0", "foo>=1.2.0,<1.3.0", None, False, True),
("1.2.0", "foo>=1.3.0", None, False, False),
("1.2.0-dev-405", "foo>=1.2.0", None, True, True),
("1.2.0.dev.405", "foo>=1.2.0", None, False, False),
("1.2.0.dev.405", "foo>=1.2.0", None, True, True),
("1.2.0", ">=1.2.0,<1.3.0", "foo", False, True),
("1.2.0", "FoO>=1.2.0,<1.3.0", "foo", False, True),
("1.2.0", ">=1.2.0,<1.3.0", None, False, ValueError),
("1.2.fnord", ">=1.2.0", None, False, ValueError)
)
@ddt.unpack
def test_version_matches_spec(self, version, spec, package, base, expected):
self.assertExpected(version_matches_spec, (version, spec), dict(package=package, base=base), expected)
def test_version_matches_any_spec(self):
self.assertTrue(version_matches_any_spec("1.2.0", [">=1.1.0,<1.2.0", ">=1.2.0,<1.3.0", "==1.3.0"], package="foo"))
def test_version_matches_any_spec_nomatch(self):
self.assertFalse(version_matches_any_spec("1.2.0", [">=1.1.0,<1.2.0", "==1.3.0"], package="foo"))
@ddt.data((">=1.2.0,<1.3.0", False, "1.2.0", True),
(">=1.2.0,<1.3.0", False, "1.3.0.dev.123", False),
(">=1.2.0,<1.3.0", False, "1.2.0.dev.123", False),
(">=1.2.0,<1.3.0", True, "1.2.0.dev.123", True))
@ddt.unpack
def test_octoprint_version_matches(self, spec, base, mocked_version, expected):
import octoprint
old_version = octoprint.__version__
try:
octoprint.__version__ = mocked_version
self.assertExpected(octoprint_version_matches, (spec,), dict(base=base), expected)
finally:
octoprint.__version__ = old_version
@ddt.data(("1.2.0", False, "1.2.0", ("00000001", "00000002", "00000000", "*final"), ("00000001", "00000002", "00000000", "*final"), "1.2.0"),
("1.2.0-dev-123", False, "1.2.0", ("00000001", "00000002", "00000000", "*final"), ("00000001", "00000002", "00000000", "*final"), "1.2.0"),
("1.2.0-dev-123", True, "1.2.0", ("00000001", "00000002", "00000000", "*final"), ("00000001", "00000002", "00000000", "*final"), "1.2.0"),
("1.2.0.dev.123", False, "1.2.0.dev.123", ("00000001", "00000002", "00000000", "*@", "00000123", "*final"), ("00000001", "00000002", "00000000", "*@", "00000123", "*final"), "1.2.0"),
("1.2.0.dev.123", True, "1.2.0.dev.123", ("00000001", "00000002", "00000000", "*@", "00000123", "*final"), ("00000001", "00000002", "00000000", "*final"), "1.2.0"),
("v1.1.0", False, "v1.1.0", ("*v", "00000001", "00000001", "00000000", "*final"), ("00000001", "00000001", "00000000", "*final"), "1.1.0"),
("V1.2.0.dev.123", True, "V1.2.0.dev.123", ("*V", "00000001", "00000002", "00000000", "*@", "00000123", "*final"), ("00000001", "00000002", "00000000", "*final"), "1.2.0"))
@ddt.unpack
def test_parse_version(self, version, base, stripped_version, mocked_tuple, expected_tuple, mocked_base_version):
mocked_obj = mock.MagicMock()
mocked_obj.base_version = mocked_base_version
# old setuptools return a tuple for parse_version, we simulate that here
with mock.patch("pkg_resources.parse_version") as mocked_parse_version:
mocked_parse_version.return_value = mocked_tuple
result = parse_version(version, base=base)
self.assertEqual(expected_tuple, result)
mocked_parse_version.assert_called_with(stripped_version)
# newer setuptools return a version object, we simulate that here
with mock.patch("pkg_resources.parse_version") as mocked_parse_version:
mocked_parse_version.return_value = mocked_obj
result = parse_version(version, base=base)
self.assertEqual(mocked_obj, result)
expected_calls = [mock.call(stripped_version)]
if base:
expected_calls.append(mock.call(mocked_base_version))
self.assertListEqual(expected_calls, mocked_parse_version.call_args_list)
def assertExpected(self, method, args, kwargs, expected):
"""
Helper for checking the return value against an expected one.
Maybe an exception class in which case a try-catch-block is created and a test for the correct
exception is set up.
"""
if isinstance(expected, type) and issubclass(expected, Exception):
try:
method(*args, **kwargs)
self.fail("Expected {}".format(expected))
except Exception as e:
if not isinstance(e, expected):
self.fail("Expected exception of type {}, got {} instead".format(expected, e.__class__.__name__))
else:
self.assertEqual(expected, method(*args, **kwargs))