Compare commits

..
29 changed files with 426 additions and 1136 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', 'sphinxcontrib.mermaid']
'sphinx.ext.napoleon']
todo_include_todos = True
# Add any paths that contain templates here, relative to this directory.
-124
View File
@@ -299,130 +299,6 @@ 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>`_
+27 -85
View File
@@ -7,99 +7,41 @@ __copyright__ = "Copyright (C) 2015 Gina Häußge - Released under terms of the
import codecs
import requests
from contextlib import closing
import urllib2
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
from sphinx.directives import LiteralInclude, dedent_lines
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 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
def read_with_encoding(self, filename, document, codec_info, encoding):
global cache
f = None
try:
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)]
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]]
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)
@@ -111,4 +53,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)
+2 -3
View File
@@ -65,10 +65,9 @@ EXTRA_REQUIRES = dict(
"ddt",
# Documentation dependencies
"sphinx>=1.6,<1.7",
"sphinx>=1.3,<1.4",
"sphinxcontrib-httpdomain",
"sphinxcontrib-mermaid",
"sphinx_bootstrap_theme",
"sphinx_rtd_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", str(offset[0]), str(offset[1])]
command += ["--offset", offset[0], offset[1]]
if g90_extruder:
command += ["--g90-extruder"]
command.append(self._current.absolute_path)
+8 -25
View File
@@ -45,8 +45,7 @@ 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_checked_module_dependencies=None):
plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, plugin_validators=None):
"""
Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.plugin.core.PluginManager`
singleton.
@@ -72,8 +71,6 @@ 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
@@ -117,9 +114,6 @@ 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,
@@ -128,8 +122,7 @@ 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_checked_module_dependencies=plugin_checked_module_dependencies)
plugin_validators=plugin_validators)
else:
raise ValueError("Plugin Manager not initialized yet")
return _instance
@@ -271,17 +264,13 @@ class PluginSettings(object):
:returns: The retrieved settings value.
:rtype: object
.. method:: get_int(path, min=None, max=None)
.. method:: get_int(path)
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.
Like :func:`get` but tries to convert the retrieved value to ``int``.
.. method:: get_float(path, min=None, max=None)
.. method:: get_float(path)
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.
Like :func:`get` but tries to convert the retrieved value to ``float``.
.. method:: get_boolean(path)
@@ -297,19 +286,13 @@ 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, min=None, max=None)
.. method:: set_int(path, value, force=False)
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, min=None, max=None)
.. method:: set_float(path, value, force=False)
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)
+2 -20
View File
@@ -41,8 +41,6 @@ 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")
@@ -466,7 +464,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_checked_module_dependencies=None):
plugin_validators=None):
self.logger = logging.getLogger(__name__)
if logging_prefix is None:
@@ -487,7 +485,6 @@ 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()
@@ -622,20 +619,6 @@ 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
@@ -678,8 +661,7 @@ 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:
+45 -18
View File
@@ -14,7 +14,6 @@ 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
@@ -724,7 +723,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
return False
current_os = self._get_os()
parsed_octoprint_version = self._get_octoprint_version()
octoprint_version = self._get_octoprint_version(base=True)
def map_repository_entry(entry):
result = copy.deepcopy(entry)
@@ -739,7 +738,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(parsed_octoprint_version, entry["compatibility"]["octoprint"])
result["is_compatible"]["octoprint"] = self._is_octoprint_compatible(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"])
@@ -818,15 +817,20 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
Tests if the current ``octoprint_version`` is compatible to any of the provided ``compatibility_entries``.
"""
spec_matcher = ("<", "<=", "!=", "==", ">=", ">", "~=", "===")
specs = map(lambda x: x if any(x.startswith(c) for c in spec_matcher) else ">={}".format(x),
compatibility_entries)
for octo_compat in compatibility_entries:
try:
if not any(octo_compat.startswith(c) for c in ("<", "<=", "!=", "==", ">=", ">", "~=", "===")):
octo_compat = ">={}".format(octo_compat)
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
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
@staticmethod
def _is_os_compatible(current_os, compatibility_entries):
@@ -860,14 +864,37 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
else:
return "unmapped"
@staticmethod
def _get_octoprint_version_string():
from octoprint import __version__ as octoprint_version
return octoprint_version
def _get_octoprint_version_string(self):
return VERSION
@staticmethod
def _get_octoprint_version(base=False):
return parse_version(PluginManagerPlugin._get_octoprint_version_string(), base=base)
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)
return octoprint_version
@property
def _reconnect_hooks(self):
@@ -8,8 +8,6 @@ __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")
@@ -141,8 +139,44 @@ 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):
return parse_version(version_string, base=force_base)
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
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 read from a GCODE file while printing.
Sets the temperature ``offsets`` to apply to target temperatures red from a GCODE file while printing.
Arguments:
offsets (dict): A dictionary specifying the offsets to apply. Keys must match the format for the ``heater``
+9 -2
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, add_context_processor=False)
loginManager.init_app(app)
# register API blueprint
self._setup_blueprints()
@@ -634,7 +634,8 @@ class Server(object):
return Locale.parse(request.accept_languages.best_match(LANGUAGES))
def _setup_app(self, app):
from octoprint.server.util.flask import ReverseProxiedEnvironment, OctoPrintFlaskRequest, OctoPrintFlaskResponse
from octoprint.server.util.flask import ReverseProxiedEnvironment, OctoPrintFlaskRequest, \
OctoPrintFlaskResponse, ServerSideSessionInterface
s = settings()
@@ -668,6 +669,11 @@ class Server(object):
app.request_class = OctoPrintFlaskRequest
app.response_class = OctoPrintFlaskResponse
def session_persistent(app, request):
return "X-Preemptive-Cache" not in request.headers
app.session_interface = ServerSideSessionInterface(s.getBaseFolder("sessions"),
persistent_callback=session_persistent)
@app.before_request
def before_request():
g.locale = self._get_locale()
@@ -850,6 +856,7 @@ class Server(object):
headers = kwargs.get("headers", dict())
headers["X-Force-View"] = plugin if plugin else "_default"
headers["X-Preemptive-Record"] = "no"
headers["X-Preemptive-Cache"] = "true"
kwargs["headers"] = headers
builder = EnvironBuilder(**kwargs)
+1 -5
View File
@@ -168,9 +168,7 @@ def getSettings():
},
"temperature": {
"profiles": s.get(["temperature", "profiles"]),
"cutoff": s.getInt(["temperature", "cutoff"]),
"sendAutomatically": s.getBoolean(["temperature", "sendAutomatically"]),
"sendAutomaticallyAfter": s.getInt(["temperature", "sendAutomaticallyAfter"], min=0, max=30),
"cutoff": s.getInt(["temperature", "cutoff"])
},
"system": {
"actions": s.get(["system", "actions"]),
@@ -390,8 +388,6 @@ 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"])
+173 -1
View File
@@ -21,13 +21,23 @@ import threading
import logging
import netaddr
import os
import uuid
import collections
import pylru
try:
from os import scandir, walk
except ImportError:
from scandir import scandir, walk
from octoprint.settings import settings
import octoprint.server
import octoprint.users
import octoprint.plugin
import octoprint.util
from werkzeug.contrib.cache import BaseCache
from werkzeug.datastructures import CallbackDict
from past.builtins import basestring
@@ -476,6 +486,168 @@ class OctoPrintFlaskResponse(flask.Response):
flask.Response.set_cookie(self, key, expires=0, max_age=0, path=path, domain=domain)
#~~ Sessions
class ServerSideSession(CallbackDict, flask.sessions.SessionMixin):
def __init__(self, sid, path, serializer, persistent=True, new=False):
def on_update(self):
self.modified = True
CallbackDict.__init__(self, on_update=on_update)
self.sid = sid
self.path = path
self.new = new
self.modified = False
self._logger = logging.getLogger(__name__ + ".sessions.session")
self._persistent = persistent
self._serializer = serializer
self._lock = threading.RLock()
self.read()
@property
def persistent(self):
return self._persistent
def read(self):
with self._lock:
if not os.path.exists(self.path):
return
try:
with open(self.path, "rb") as f:
data = self._serializer.loads(f.read())
self.clear()
self.update(data)
self.modified = False
return
except:
self._logger.exception("Could not read session file for session {}".format(self.sid))
def save(self):
if not self.persistent:
return
from octoprint.util import atomic_write
with self._lock:
try:
with atomic_write(self.path, mode="wb") as f:
f.write(self._serializer.dumps(dict(self)))
self.modified = False
except:
self._logger.exception("Could not write session file for session {}".format(self.sid))
self._logger.debug("Saved session file for session {}".format(self.sid))
def remove(self):
with self._lock:
if not os.path.exists(self.path):
return
try:
os.remove(self.path)
self._logger.debug("Removed session file for session {}".format(self.sid))
except:
self._logger.exception("Could not remove session file for session {}".format(self.sid))
class ServerSideSessionInterface(flask.sessions.SessionInterface):
serializer = flask.sessions.session_json_serializer
session_class = ServerSideSession
def __init__(self, directory, persistent_callback=None, min_cleanup_interval=300):
self.directory = directory
self.persistent_callback = persistent_callback
self.min_cleanup_interval = min_cleanup_interval
self._cleanup_lock = threading.RLock()
self._last_cleanup = None
self._logger = logging.getLogger(__name__ + ".sessions.interface")
def open_session(self, app, request):
self.cleanup_stale_sessions(app)
persistent = self.persistent_callback(app, request) if callable(self.persistent_callback) else True
sid = request.cookies.get(app.session_cookie_name)
try:
uuid.UUID(octoprint.util.to_str(sid))
except:
sid = None
is_new = False
if not sid:
sid = self.generate_sid()
is_new = True
if persistent:
self._logger.debug("Generated a new SID {} for path {}".format(sid, request.path))
return self.session_class(sid, self.path_for_sid(sid), self.serializer, persistent=persistent, new=is_new)
def save_session(self, app, session, response):
domain = self.get_cookie_domain(app)
path = self.get_cookie_path(app)
if not session:
if session.persistent:
session.remove()
if session.modified:
response.delete_cookie(app.session_cookie_name,
domain=domain, path=path)
return
session.save()
httponly = self.get_cookie_httponly(app)
secure = self.get_cookie_secure(app)
expires = self.get_expiration_time(app, session)
response.set_cookie(app.session_cookie_name, session.sid,
httponly=httponly, secure=secure, expires=expires,
domain=domain, path=path)
def generate_sid(self):
while True:
sid = str(uuid.uuid4())
if not os.path.exists(self.path_for_sid(sid)):
return sid
def cleanup_stale_sessions(self, app):
if self._last_cleanup is not None and self._last_cleanup - time.time() < self.min_cleanup_interval:
return
maxage = flask.sessions.total_seconds(app.permanent_session_lifetime)
cutoff = time.time() - maxage
to_clean = []
with self._cleanup_lock:
for entry in scandir(self.directory):
try:
if entry.stat().st_mtime < cutoff:
to_clean.append(entry.path)
except:
self._logger.exception("Error checking session file for session {} for staleness".format(entry.name))
for path in to_clean:
try:
os.remove(path)
self._logger.debug("Cleaned up session file for stale session {}".format(os.path.basename(path)))
except:
self._logger.exception("Error while removing session file for stale session {}".format(os.path.basename(path)))
pass
self._last_cleanup = time.time()
def path_for_sid(self, sid):
return os.path.join(self.directory, sid)
#~~ passive login helper
def passive_login():
@@ -609,7 +781,7 @@ def cached(timeout=5 * 60, key=lambda: "view:%s" % flask.request.path, unless=No
def decorator(f):
@functools.wraps(f)
def decorated_function(*args, **kwargs):
logger = logging.getLogger(__name__)
logger = logging.getLogger(__name__ + ".cache")
cache_key = key()
+5 -42
View File
@@ -224,16 +224,15 @@ default_settings = {
"scripts": None,
"translations": None,
"generated": None,
"data": None
"data": None,
"sessions": None
},
"temperature": {
"profiles": [
{"name": "ABS", "extruder" : 210, "bed" : 100 },
{"name": "PLA", "extruder" : 180, "bed" : 60 }
],
"cutoff": 30,
"sendAutomatically": False,
"sendAutomaticallyAfter": 1,
"cutoff": 30
},
"printerProfiles": {
"default": None
@@ -1277,43 +1276,23 @@ 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:
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
return int(value)
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:
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
return float(value)
except ValueError:
self._logger.warn("Could not convert %r to a valid integer when getting option %r" % (value, path))
return None
@@ -1469,16 +1448,8 @@ 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
@@ -1490,16 +1461,8 @@ 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
+28 -35
View File
@@ -301,16 +301,10 @@ var doParse = function () {
var tool = 0;
var prev_extrude = [{a: 0, b: 0, c: 0, e: 0, abs: 0}];
var prev_retract = [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;
var offset = toolOffsets[0];
model = [];
for (i = 0; i < gcode.length; i++) {
for (var i = 0; i < gcode.length; i++) {
x = undefined;
y = undefined;
z = undefined;
@@ -331,24 +325,24 @@ var doParse = function () {
var log = false;
if (/^(?:G0|G1|G2|G3)\s/i.test(line)) {
args = line.split(/\s/);
var args = line.split(/\s/);
for (j = 0; j < args.length; j++) {
for (var j = 0; j < args.length; j++) {
switch (argChar = args[j].charAt(0).toLowerCase()) {
case 'x':
if (relativeMode) {
x = prevX + Number(args[j].slice(1)) + activeToolOffset.x;
x = prevX + Number(args[j].slice(1)) + offset.x;
} else {
x = Number(args[j].slice(1)) + activeToolOffset.x;
x = Number(args[j].slice(1)) + offset.x;
}
break;
case 'y':
if (relativeMode) {
y = prevY + Number(args[j].slice(1)) + activeToolOffset.y;
y = prevY + Number(args[j].slice(1)) + offset.y;
} else {
y = Number(args[j].slice(1)) + activeToolOffset.y;
y = Number(args[j].slice(1)) + offset.y;
}
break;
@@ -382,7 +376,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;
@@ -404,9 +398,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;
}
@@ -417,7 +411,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;
}
@@ -440,12 +434,12 @@ var doParse = function () {
} else if (/^(?:M103)/i.test(line)) {
dcExtrude = false;
} else if (/^(?:G92)/i.test(line)) {
args = line.split(/\s/);
var args = line.split(/\s/);
for (j = 0; j < args.length; j++) {
for (var 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;
@@ -457,11 +451,11 @@ var doParse = function () {
} else {
switch (argChar = args[j].charAt(0).toLowerCase()) {
case 'x':
x = Number(args[j].slice(1)) + activeToolOffset.x;
x = Number(args[j].slice(1)) + offset.x;
break;
case 'y':
y = Number(args[j].slice(1)) + activeToolOffset.y;
y = Number(args[j].slice(1)) + offset.y;
break;
case 'z':
@@ -490,9 +484,9 @@ var doParse = function () {
}
} else if (/^(?:G28)/i.test(line)) {
args = line.split(/\s/);
var args = line.split(/\s/);
if (args.length === 1) {
if (args.length == 1) {
// G28 with no arguments => home all axis
x = 0;
y = 0;
@@ -516,11 +510,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;
}
@@ -529,13 +523,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;
activeToolOffset = toolOffsets[tool];
if (!activeToolOffset) activeToolOffset = {x: 0, y: 0};
offset = toolOffsets[tool];
if (!offset) offset = {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;
}
@@ -544,7 +538,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 {
@@ -555,7 +549,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 {
@@ -615,7 +609,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 = [];
@@ -635,7 +629,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;
@@ -672,7 +666,6 @@ 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,22 +983,6 @@ 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);
}
+12 -42
View File
@@ -613,7 +613,6 @@ $(function() {
// startup complete
callViewModels(allViewModels, "onStartupComplete");
setOnViewModels(allViewModels, "_startupComplete", true);
// make sure we can track the browser tab visibility
OctoPrint.coreui.onBrowserVisibilityChange(function(status) {
@@ -649,59 +648,30 @@ $(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 on the LoginStateViewModel with this in place.
return viewModelMap["loginStateViewModel"].requestData()
// onServerConnect/onServerReconnect with this in place.
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
// 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.
dataUpdater.initialized();
});
};
var dataUpdater = new DataUpdater(allViewModels);
var dataUpdater = new DataUpdater(allViewModels, onServerConnect);
dataUpdater.connect()
.done(function() {
// 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);
});
// 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);
});
}
);
@@ -52,21 +52,16 @@ $(function() {
self.fromResponse = function(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")
}
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");
}
callViewModels(self.allViewModels, "onUserLoggedOut");
log.info("User logged out");
}
};
@@ -195,8 +195,6 @@ $(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([]);
@@ -886,14 +884,12 @@ $(function() {
};
self.onUserLoggedIn = function() {
// we might have other user rights now, refresh (but only if startup has fully completed)
if (!self._startupComplete) return;
// we might have other user rights now, refresh
self.requestData();
};
self.onUserLoggedOut = function() {
// we might have other user rights now, refresh (but only if startup has fully completed)
if (!self._startupComplete) return;
// we might have other user rights now, refresh
self.requestData();
}
}
@@ -6,7 +6,7 @@ $(function() {
self.settingsViewModel = parameters[1];
self._createToolEntry = function() {
var entry = {
return {
name: ko.observable(),
key: ko.observable(),
actual: ko.observable(0),
@@ -14,63 +14,11 @@ $(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");
@@ -452,191 +400,66 @@ $(function() {
return maxTemp;
};
self.incrementTarget = function(item) {
self.setTarget = function(item) {
var value = item.newTarget();
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 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();
if (!value) return;
var onSuccess = function() {
item.target(value);
item.newTarget("");
};
if (item.key() == "bed") {
return self._setBedTemperature(value)
self._setBedTemperature(value)
.done(onSuccess);
} else {
return self._setToolTemperature(item.key(), value)
self._setToolTemperature(item.key(), value)
.done(onSuccess);
}
};
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());
self.setTargetFromProfile = function(item, profile) {
if (!profile) return;
self.changeOffsetDialog.modal("show");
};
var onSuccess = function() {
item.newTarget("");
};
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
if (item.key() == "bed") {
self._setBedTemperature(profile.bed)
.done(onSuccess);
} else {
self._setToolTemperature(item.key(), profile.extruder)
.done(onSuccess);
}
};
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.setTargetToZero = function(item) {
var onSuccess = function() {
item.newTarget("");
};
if (item.key() == "bed") {
self._setBedTemperature(0)
.done(onSuccess);
} else {
self._setToolTemperature(item.key(), 0)
.done(onSuccess);
}
};
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 === 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();
if (!value) return;
var onSuccess = function() {
item.offset(value);
item.newOffset("");
};
if (item.key() == "bed") {
return self._setBedOffset(value)
self._setBedOffset(value)
.done(onSuccess);
} else {
return self._setToolOffset(item.key(), value)
self._setToolOffset(item.key(), value)
.done(onSuccess);
}
};
@@ -680,28 +503,13 @@ $(function() {
self.handleEnter = function(event, type, item) {
if (event.keyCode == 13) {
if (type == "target") {
self.setTarget(item)
.done(function() {
event.target.blur();
});
self.setTarget(item);
} else if (type == "offset") {
self.confirmChangeOffset();
self.setOffset(item);
}
}
};
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;
@@ -723,10 +531,6 @@ $(function() {
}
};
self.onStartup = function() {
self.changeOffsetDialog = $("#change_offset_dialog");
};
self.onStartupComplete = function() {
self._printerProfileUpdated();
};
@@ -736,6 +540,6 @@ $(function() {
OCTOPRINT_VIEWMODELS.push([
TemperatureViewModel,
["loginStateViewModel", "settingsViewModel"],
["#temp", "#change_offset_dialog"]
"#temp"
]);
});
+5 -80
View File
@@ -400,6 +400,7 @@ table {
width: 80px;
.actioncol;
}
}
}
@@ -412,54 +413,14 @@ table {
background: url("../img/graph-background.png") no-repeat center;
}
#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%;
}
}
}
/** Various */
.tab-content, .tab-pane {
overflow: visible;
}
.tempInput {
width: 50px;
}
#temp_newTemp, #temp_newBedTemp, #speed_innerWall, #speed_outerWall, #speed_fill, #speed_support,
#webcam_timelapse_interval, #webcam_timelapse_postRoll, #webcam_timelapse_fps, #webcam_timelapse_retractionZHop {
text-align: right;
@@ -1277,27 +1238,6 @@ _::-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,
@@ -1305,25 +1245,10 @@ _::-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>{{ _('Graph') }}</h3>
<h3>{{ _('Temperature Graph') }}</h3>
<div class="control-group">
<label class="control-label">{{ _('Graph cutoff') }}</label>
<div class="controls">
@@ -10,26 +10,7 @@
<span class="help-block">{{ _('Needs a restart of OctoPrint to become active.') }}</span>
</div>
</div>
<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>
<h3>{{ _('Temperature Presets') }}</h3>
<div class="row-fluid">
<div class="offset4 span3"><h4>{{ _('Extruder') }}</h4></div>
<div class="span3"><h4>{{ _('Bed') }}</h4></div>
@@ -1,34 +0,0 @@
<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,7 +131,6 @@
{% include 'dialogs/wizard.jinja2' %}
{% include 'dialogs/about.jinja2' %}
{% include 'dialogs/files.jinja2' %}
{% include 'dialogs/temperature.jinja2' %}
<!-- End of dialogs -->
<!-- Overlays -->
+25 -33
View File
@@ -5,12 +5,12 @@
{% endif %}
<div class="row-fluid">
<table id="temperature-table" class="table table-bordered table-hover">
<table class="table table-bordered table-hover" style="table-layout: fixed; width: 100%; margin-top: 20px">
<tr>
<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>
<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>
</tr>
<!-- ko foreach: tools -->
<tr data-bind="template: { name: 'temprow-template' }"></tr>
@@ -19,45 +19,37 @@
</table>
<script type="text/html" id="temprow-template">
<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>
<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>
<div class="btn-group">
<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()">
<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()">
<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="javascript:void(0)" data-bind="click: function() {$root.setTargetFromProfile($parent, $data);}, text: 'Set ' + name + ' (' + ($parent.key() == 'bed' ? bed : extruder) + '&deg;C)'"></a>
<a href="#" 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>
</form>
</div>
</td>
<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 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>
</script>
</div>
-189
View File
@@ -1,189 +0,0 @@
# 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)
+1 -5
View File
@@ -480,11 +480,7 @@ 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")
for require in requires:
requirement = pkg_resources.Requirement.parse(require)
if requirement.key == "octoprint":
break
else:
if "OctoPrint" not in requires:
requires = ["OctoPrint"] + list(requires)
if extra_requires is None:
-103
View File
@@ -1,103 +0,0 @@
# 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))